@runtypelabs/persona 4.17.0 → 4.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-BpWGm7_6.d.cts → types-DsmTD8TO.d.cts} +12 -0
- package/dist/animations/{types-BpWGm7_6.d.ts → types-DsmTD8TO.d.ts} +12 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-3I2S3I5P.js +1 -0
- package/dist/chunk-76IELU7F.js +1 -0
- package/dist/chunk-EFJBUH5F.js +1 -0
- package/dist/chunk-PDPVORUF.js +1 -0
- package/dist/chunk-Q735PSZL.js +1 -0
- package/dist/chunk-VK6JOIYJ.js +1 -0
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
- package/dist/context-mentions.cjs +9 -8
- package/dist/context-mentions.d.cts +1224 -14
- package/dist/context-mentions.d.ts +1224 -14
- package/dist/context-mentions.js +9 -8
- package/dist/event-stream-view-4EZ7BGFK.js +1 -0
- package/dist/event-stream-view.cjs +129 -0
- package/dist/event-stream-view.d.cts +8384 -0
- package/dist/event-stream-view.d.ts +8384 -0
- package/dist/event-stream-view.js +129 -0
- package/dist/history-view-BD6OXLNA.js +898 -0
- package/dist/history-view.cjs +898 -0
- package/dist/history-view.d.cts +1461 -0
- package/dist/history-view.d.ts +1461 -0
- package/dist/history-view.js +898 -0
- package/dist/index.cjs +77 -77
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2040 -21
- package/dist/index.d.ts +2040 -21
- package/dist/index.global.js +67 -66
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +77 -77
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +5 -4
- package/dist/launcher.global.js.map +1 -1
- package/dist/plugin-kit.cjs +1 -1
- package/dist/plugin-kit.d.cts +0 -8
- package/dist/plugin-kit.d.ts +0 -8
- package/dist/plugin-kit.js +1 -1
- package/dist/smart-dom-reader.d.cts +1224 -14
- package/dist/smart-dom-reader.d.ts +1224 -14
- package/dist/theme-editor-preview.cjs +970 -73
- package/dist/theme-editor-preview.d.cts +1343 -15
- package/dist/theme-editor-preview.d.ts +1343 -15
- package/dist/theme-editor-preview.js +81 -81
- package/dist/theme-editor.cjs +7 -7
- package/dist/theme-editor.d.cts +1227 -15
- package/dist/theme-editor.d.ts +1227 -15
- package/dist/theme-editor.js +9 -9
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +226 -7
- package/dist/theme-reference.d.ts +226 -7
- package/dist/theme-reference.js +1 -1
- package/dist/webmcp-polyfill.js +2 -2
- package/dist/widget.css +1 -1
- package/package.json +18 -6
- package/src/client-history-rest.test.ts +1034 -0
- package/src/client-visitor-history.test.ts +596 -0
- package/src/client.ts +1040 -24
- package/src/components/artifact-inline.ts +8 -1
- package/src/components/artifact-pane.test.ts +278 -1
- package/src/components/artifact-pane.ts +135 -67
- package/src/components/artifact-preview.test.ts +14 -1
- package/src/components/artifact-preview.ts +9 -0
- package/src/components/header-builder.ts +3 -0
- package/src/components/header-layouts.test.ts +171 -7
- package/src/components/header-layouts.ts +83 -53
- package/src/components/header-parts.test.ts +154 -1
- package/src/components/header-parts.ts +266 -138
- package/src/components/history-confirm-dialog.ts +177 -0
- package/src/components/history-shell-copy.ts +99 -0
- package/src/components/history-view/announcer.ts +40 -0
- package/src/components/history-view/copy.ts +105 -0
- package/src/components/history-view/css.ts +1078 -0
- package/src/components/history-view/grouping.test.ts +142 -0
- package/src/components/history-view/grouping.ts +142 -0
- package/src/components/history-view/icons.ts +73 -0
- package/src/components/history-view/rows.ts +341 -0
- package/src/components/history-view/state.ts +309 -0
- package/src/components/history-view.test.ts +2660 -0
- package/src/components/history-view.ts +1891 -0
- package/src/components/launcher-surface.test.ts +133 -0
- package/src/components/launcher.test.ts +18 -0
- package/src/components/launcher.ts +7 -7
- package/src/components/panel.ts +17 -7
- package/src/components/welcome.ts +72 -2
- package/src/defaults.ts +36 -3
- package/src/event-stream-view-bundle.test.ts +69 -0
- package/src/event-stream-view-entry.ts +19 -0
- package/src/event-stream-view-loader.ts +31 -0
- package/src/event-stream-view.ts +19 -0
- package/src/generated/runtype-openapi-contract.ts +54 -4
- package/src/history-render.ts +325 -0
- package/src/history-view-bundle.test.ts +78 -0
- package/src/history-view-entry.ts +41 -0
- package/src/history-view-loader.test.ts +30 -0
- package/src/history-view-loader.ts +32 -0
- package/src/history-view.ts +28 -0
- package/src/index-core.ts +50 -2
- package/src/index-global.ts +55 -0
- package/src/internal/demo-history-provider.test.ts +402 -0
- package/src/internal/demo-history-provider.ts +689 -0
- package/src/internal/history-provider-registry.ts +25 -0
- package/src/internal/history-provider.ts +150 -0
- package/src/internal/runtype-history-provider.test.ts +313 -0
- package/src/internal/runtype-history-provider.ts +240 -0
- package/src/plugin-kit.test.ts +16 -0
- package/src/plugin-kit.ts +13 -5
- package/src/plugins/types.ts +177 -1
- package/src/session-history.test.ts +1397 -0
- package/src/session.ts +1200 -26
- package/src/styles/widget-styles.test.ts +133 -0
- package/src/styles/widget.css +227 -8
- package/src/theme-editor/preview-utils.test.ts +19 -0
- package/src/theme-editor/preview-utils.ts +15 -1
- package/src/theme-editor/preview.ts +7 -1
- package/src/theme-editor/role-mappings.ts +4 -1
- package/src/theme-editor/sections.test.ts +168 -1
- package/src/theme-editor/sections.ts +136 -7
- package/src/theme-editor/webmcp/summary.ts +16 -2
- package/src/theme-reference.ts +20 -6
- package/src/types/theme.ts +213 -7
- package/src/types.ts +927 -7
- package/src/ui.artifact-rail-resize.test.ts +235 -0
- package/src/ui.attachments-drop.test.ts +1 -0
- package/src/ui.header-update-stability.test.ts +2 -2
- package/src/ui.history-chunk.test.ts +72 -0
- package/src/ui.history-config-provider.test.ts +318 -0
- package/src/ui.history-controller.test.ts +711 -0
- package/src/ui.history-lifecycle.test.ts +456 -0
- package/src/ui.history-render-hooks.test.ts +904 -0
- package/src/ui.history-shell.test.ts +1887 -0
- package/src/ui.rail-overlay.test.ts +573 -0
- package/src/ui.rail-resize.test.ts +284 -0
- package/src/ui.rebuild-composer.test.ts +21 -0
- package/src/ui.render-welcome.test.ts +42 -0
- package/src/ui.shortcuts.test.ts +166 -0
- package/src/ui.ts +3071 -240
- package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
- package/src/utils/artifact-file.ts +15 -0
- package/src/utils/artifact-gate.test.ts +4 -0
- package/src/utils/artifact-gate.ts +13 -17
- package/src/utils/artifact-resize.test.ts +28 -0
- package/src/utils/artifact-resize.ts +9 -2
- package/src/utils/buttons.ts +188 -1
- package/src/utils/config-merge.test.ts +91 -0
- package/src/utils/dropdown.ts +10 -1
- package/src/utils/history-messages.test.ts +284 -0
- package/src/utils/history-messages.ts +284 -0
- package/src/utils/icons.ts +3 -0
- package/src/utils/shortcuts.test.ts +288 -0
- package/src/utils/shortcuts.ts +221 -0
- package/src/utils/theme.test.ts +501 -4
- package/src/utils/theme.ts +42 -3
- package/src/utils/tokens.ts +153 -15
- package/src/utils/tooltip-timing.ts +4 -0
- package/src/utils/tooltip.test.ts +249 -7
- package/src/utils/tooltip.ts +146 -4
- package/src/utils/visitor-store.test.ts +425 -0
- package/src/utils/visitor-store.ts +337 -0
- package/dist/chunk-QJ4LV2KW.js +0 -1
package/dist/index.js
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
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(!
|
|
3
|
-
`):e};var
|
|
1
|
+
var Dw=Object.defineProperty;var Ps=(e,t)=>()=>(e&&(t=e(e=0)),t);var gp=(e,t)=>{for(var n in t)Dw(e,n,{get:t[n],enumerable:!0})};var xm={};gp(xm,{DOMPurify:()=>Nw,Marked:()=>_w});import{Marked as _w}from"marked";import Nw from"dompurify";var Sm=Ps(()=>{"use strict"});var Os,Bp=Ps(()=>{"use strict";Os=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 i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,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 i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function pS(e){return e.replace(/\/+$/,"")}async function uS(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 Kl,Oh=Ps(()=>{"use strict";Bp();Kl=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 Os(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=`${pS(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,i=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(!i.ok||!i.body)throw new Error(await uS(i));let l=i.body.getReader();for(;;){let{done:d,value:u}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;u&&u.byteLength>0&&r.enqueue(u)}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 Gl,Dh=Ps(()=>{"use strict";Gl=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 _h={};gp(_h,{FallbackSpeechEngine:()=>Gl,RuntypeSpeechEngine:()=>Kl});var Nh=Ps(()=>{"use strict";Oh();Dh()});var $h={};gp($h,{createReconnectController:()=>fS});function fS(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},i=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},d=()=>{i()},u=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},g=b=>new Promise(x=>{n=x,o=setTimeout(()=>{o=null,n=null,x()},b)}),y=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let x=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,x=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):x&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},m=async()=>{let b=e.config.reconnect?.backoffMs??gS,x=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<x;){t+=1,e.setStatus("resuming");let L=e.getResumable(),D=L.lastEventId,k=new AbortController;e.setAbortController(k),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let A=null;try{let W=await T({executionId:L.executionId,after:L.lastEventId,signal:k.signal});W&&W.ok&&W.body&&(A=W.body)}catch{A=null}if(k.signal.aborted)return;if(A){let W=e.getMessages().find(R=>R.id===L.assistantMessageId)?.content,I=typeof W=="string"?W:"";try{await e.resumeConnect(A,L.assistantMessageId,I)}catch{}if(k.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==D&&(t=0)}if(e.getResumable()&&t<x&&(e.setStatus("paused"),await g(b[Math.min(t-1,b.length-1)]??1e3),k.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,u(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var gS,jh=Ps(()=>{"use strict";gS=[1e3,2e3,4e3,8e3,8e3]});import{Marked as jw}from"marked";import zw from"dompurify";var ro=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:p=>{o=p,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:p=>{r=p},getSync:()=>r}};var{setLoader:fP,load:Fw,provide:$w,getSync:fp}=ro({fallbackImport:()=>Promise.resolve().then(()=>(Sm(),xm))}),Rl=new Set,Am=()=>{let e=[...Rl];Rl.clear();for(let t of e)try{t()}catch{}};var Tm=()=>{let e=fp();return e?Promise.resolve(e):Fw().then(t=>(Am(),t))},qi=e=>fp()?()=>{}:(Rl.add(e),Tm().catch(()=>{}),()=>{Rl.delete(e)}),Em=e=>{$w(e),Am()},Lo=fp;Em({Marked:jw,DOMPurify:zw});var Uw=e=>{if(e)return e},Wl=e=>{let t=null;return n=>{let o=Lo();if(!o)return Ho(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 i=Uw(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Ls=e=>e?Wl({markedOptions:e.options,renderer:e.renderer}):Wl(),qw=Wl(),km=e=>qw(e),Ho=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Pm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Mm=e=>`%%FORM_PLACEHOLDER_${e}%%`,Lm=(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 i=Mm(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=Mm(t.length);return t.push({token:s,type:r}),s}),n},Vw=e=>{let t=Ls(e);return n=>{let o=[],r=Lm(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Pm(l)}"></div>`;s=s.replace(d,p)}),s}},Kw=e=>{let t=[],n=Lm(e,t),o=km(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Pm(s)}"></div>`;o=o.replace(i,d)}),o};var Gw={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"]},Yw=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Hm=()=>{let e=null;return t=>{let n=Lo();if(!n)return Ho(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 i=s.attrValue;i.toLowerCase().startsWith("data:")&&!Yw.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Gw)}},Vi=e=>e===!1?null:typeof e=="function"?e:Hm();var Im=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Rm=e=>e.includes("|"),Wm=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())},Jw=e=>`| ${e.join(" | ")} |`,Xw=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Qw=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Bm=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(!Rm(r)||Im.test(r)||!Im.test(s))continue;let i=Wm(r).length;if(i<1)continue;let l=Xw(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let u=t[d];if(u.trim()===""||!Rm(u))break;let p=Jw(Qw(Wm(u),i));t[d]!==p&&(t[d]=p,n=!0)}o=d-1}return n?t.join(`
|
|
3
|
+
`):e};var Om="var(--persona-md-table-scroll-fade, 24px)",Dm=new WeakSet;function Nm(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 _m(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":Om),e.style.setProperty("--persona-fade-r",r<=1?"0px":Om)}function mp(e){Dm.has(e)||(Dm.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&_m(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(_m)}var so="webmcp:",hp=new Map,Fm=e=>{hp.clear();for(let t of e){let n=t.title?.trim();n&&hp.set(t.name,n)}},Gi=e=>hp.get(yp(e)),Bl={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},$m=null;function zm(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}:${Zw(t.join(""))}`}function jm(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 Zw(e){let t=jm(e,0).toString(36),n=jm(e,2654435761).toString(36);return`${t}.${n}`}var Ki=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 Bl.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Fm(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}:{}},i=tx(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Jn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Jn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=yp(t),i;try{i=await r.getTools()}catch(b){let x=b instanceof Error?b.message:String(b);return Jn(`Failed to read WebMCP registry: ${x}`)}Fm(i);let l=i.find(b=>b.name===s);if(!l)return Jn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Jn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Jn("Aborted by cancel()");let d=Gi(s),u={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(u))return Jn("User declined the tool call.");if(o?.aborted)return Jn("Aborted by cancel()");let p=new AbortController,g=!1,y=setTimeout(()=>{g=!0,p.abort()},this.timeoutMs),m=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",m,{once:!0}));try{let b=await r.executeTool(l,sx(n),{signal:p.signal});return nx(b)}catch(b){if(g)return Jn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Jn("Aborted by cancel()");let x=b instanceof Error?b.message:String(b);return Jn(x)}finally{clearTimeout(y),o&&o.removeEventListener("abort",m)}}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}($m?await $m():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Bl.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,Bl.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??ox;try{return await n(t)}catch(o){return Bl.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=>ex(t,o))}},yp=e=>e.startsWith(so)?e.slice(so.length):e,Nr=e=>e.startsWith(so),ex=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},tx=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},nx=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:ix(t)}]}},Jn=e=>({isError:!0,content:[{type:"text",text:e}]}),ox=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=rx(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)},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,"\\"),
|
|
10
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let
|
|
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.17.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(`
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},rx=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)}},sx=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},ix=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function kn(e){return e==="card"?"collapsed":e}function Fr(e){return e.split(";",1)[0].trim().toLowerCase()}function ax(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Fr(r)===t)return{mode:kn(s),selector:Fr(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Fr(r)===o)return{mode:kn(s),selector:o}}function Um(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:kn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Fr(t.file.mimeType):void 0,d=l?ax(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:kn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:kn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:kn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:kn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:kn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Io(e,t){return Um(e,t).mode}function Yi(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 lx="agent_",cx="flow_";function qm(e){return e.startsWith(lx)?{kind:"agentId",agentId:e}:e.startsWith(cx)?{kind:"flowId",flowId:e}:null}function Vm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let u=qm(l);if(u)return u;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[i];if(!d)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=qm(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 dx,ARR as px,OBJ as ux,STR as gx}from"partial-json";var v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Km=()=>document.createDocumentFragment(),ue=(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,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let d=i[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Fn=(...e)=>e.filter(Boolean).join(" ");var Ol="ask_user_question",Ji=8,Hs="data-persona-ask-sheet-for",fx="Other",mx="Other\u2026",Ym="Type your own answer here",Jm="Send",hx="Next",yx="Back",bx="Submit all",vx="Skip",Cx=3,bp="data-ask-current-index",vp="data-ask-question-count",Xm="data-ask-answers",Cp="data-ask-grouped",Qm="data-ask-layout",wx=e=>e.layout==="pills"?"pills":"rows",xx=e=>e.getAttribute(Qm)==="pills"?"pills":"rows",Gm=!1,Zm=e=>e.replace(/["\\]/g,"\\$&"),Qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ol,Dl=e=>e?.features?.askUserQuestion??{},Zo=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=dx(r,gx|ux|px);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Xi=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ji&&!Gm&&(Gm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ji}.`)),t.slice(0,Ji)},Sx=e=>Xi(e)[0]??null,Ax=(e,t)=>Xi(e)[t]??null,eh=(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))},th=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Tx=(e,t,n,o)=>{let s=v("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 i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let u=v("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}s.appendChild(i);let d=th(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Ex=e=>{let n=v("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},Mx=(e,t,n,o)=>{let s=v("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 i=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<Cx;p++)s.appendChild(Ex(o));return s}if(d.forEach((p,g)=>{s.appendChild(Tx(p,g,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?fx:mx;if(o==="rows"){let g=v("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(d.length)),g.setAttribute("data-ask-other-row","true");let y=v("span","persona-ask-row-content"),m=document.createElement("input");m.type="text",m.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",m.placeholder=t.freeTextPlaceholder??Ym,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",t.freeTextLabel??p),y.appendChild(m),g.appendChild(y);let b=th(o,i,d.length);b&&g.appendChild(b),s.appendChild(g)}else{let g=v("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??p,s.appendChild(g)}}return s},nh=(e,t)=>{let o=v("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??Ym,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Jm,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},kx=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Jm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Px=(e,t,n)=>{let o=v("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=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??yx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??vx,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??bx:n.nextLabel??hx,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},$r=e=>{let t=e.getAttribute(Xm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},oh=(e,t)=>{e.setAttribute(Xm,JSON.stringify(t))},$n=e=>{let t=Number(e.getAttribute(bp)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Lx=(e,t)=>{e.setAttribute(bp,String(Math.max(0,Math.floor(t))))},Is=e=>{let t=Number(e.getAttribute(vp)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},er=e=>e.getAttribute(Cp)==="true",Hx=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},Ix=(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)))},_l=(e,t)=>{let{payload:n}=Zo(t),o=Xi(n),r=$r(e),s={},i=new Set;return o.forEach((l,d)=>{let u=typeof l?.question=="string"?l.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,d)&&(s[u]=r[d]))}),s},rh=e=>{let t=$r(e),n=$n(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 u=d.getAttribute("data-option-label")??"",p=r.has(u);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},sh=e=>{if(!er(e))return;let t=$r(e),n=$n(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 i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},wp=(e,t,n)=>{let o=Dl(n),r=xx(e),{payload:s,complete:i}=Zo(t),l=er(e),d=$n(e),u=Is(e),p=l?Ax(s,d):Sx(s),g=!!p?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${u}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let D=typeof p?.question=="string"?p.question:"";b.textContent=D,b.classList.toggle("persona-ask-question-skeleton",!D&&!i)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let D=Mx(p,o,i,r);x.replaceWith(D)}if(r!=="rows"){let D=e.querySelector('[data-ask-free-text-row="true"]');D&&D.replaceWith(nh(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!T?e.appendChild(kx(o)):(!g||l)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(l){let D=Px(d,u,o);L?L.replaceWith(D):e.appendChild(D)}else L&&L.remove();rh(e),sh(e)},Rx=(e,t,n)=>{let o=Dl(t),r=wx(o),s=e.toolCall.id,i=Xi(n),l=Math.max(1,i.length),d=l>1,u=Hx(e,i),p=d?Ix(e,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Hs,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(vp,String(l)),g.setAttribute(bp,String(p)),g.setAttribute(Cp,d?"true":"false"),g.setAttribute(Qm,r),oh(g,u),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),eh(g,o);let y=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",y.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",y.appendChild(b),g.appendChild(y);let T=v("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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),r!=="rows"&&g.appendChild(nh(o,r)),wp(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Wx=(e,t,n)=>{let{payload:o}=Zo(t),r=Math.max(1,Xi(o).length);r>Is(e)&&(e.setAttribute(vp,String(r)),r>1&&!er(e)&&e.setAttribute(Cp,"true")),wp(e,t,n)},Bx=(e,t)=>{let n=v("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=Dl(t);eh(n,o);let r=v("span","persona-ask-stub-label"),{complete:s}=Zo(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Qi=(e,t,n)=>{if(!n||!Qo(e)||Dl(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Hs}]`).forEach(u=>{u.getAttribute(Hs)!==r&&u.remove()});let i=n.querySelector(`[${Hs}="${Zm(r)}"]`);if(i){Wx(i,e,t);return}let{payload:l}=Zo(e),d=Rx(e,t,l);n.appendChild(d)},jr=(e,t)=>{if(!e)return;let n=t?`[${Hs}="${Zm(t)}"]`:`[${Hs}]`;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)})},xp=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),tr=(e,t)=>{let n=$r(e),o=$n(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,oh(e,n),rh(e),sh(e)},Nl=(e,t,n,o)=>{let r=Is(e),s=Math.max(0,Math.min(r-1,o));Lx(e,s),wp(e,t,n)};var io="suggest_replies";var ah={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},Sp={name:io,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:ah,origin:"sdk",annotations:{readOnlyHint:!0}},Ap=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Rs=e=>e.variant==="tool"&&e.toolCall?.name===io,lh=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 l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});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},Tp=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Rs(n))continue;let o=lh(n.toolCall?.args);return o.length>0?o:null}return null},ih=new Set,Ox=(e,t,n)=>{let o=`${e}:${t}:${n}`;ih.has(o)||(ih.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},nr=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],d=n?.[i];l===void 0||d===void 0||l!==d&&Ox(i,d,l)};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 ch={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ji,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},dh={name:Ol,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:ch,origin:"sdk",annotations:{readOnlyHint:!0}},Zi=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(dh),nr(e).expose&&t.push(Sp),t};import{parse as ph,STR as uh,OBJ as gh}from"partial-json";var Fl=e=>e.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),or=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)}},Dx=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`},fh=e=>e.status==="complete"?Dx(e):e.status==="pending"?"Waiting":"",_x=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 mh=e=>e.status==="complete"?_x(e):"Using tool...",$l=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ta=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 $l(t)},jl=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return $l(t)},Ep=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=ta(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},zl=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&ea(o,n.slice(s,i.index),[]),i[1]!==void 0?ea(o,i[1],["bold"]):i[2]!==void 0?ea(o,i[2],["italic"]):i[3]!==void 0&&ea(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&ea(o,n.slice(s),[]),o},ea=(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})},Nx=()=>{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
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[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()=>{}}},na=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Mp=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},kp=()=>{let e=Nx();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)}},Pp=()=>{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=ph(n,uh|gh);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Fl(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Fl(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Fx=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?Fl(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Fl(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=ph(s,uh|gh),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Lp=()=>{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 hh="4.18.0";var Ro=hh;var Ws="[Image]";function jx(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Hp(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function oa(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zx(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Wo(e){return{type:"text",text:e}}function Ip(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Ux(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 qx(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 yh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Vx=["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"],Bo=[...yh,...Vx];function Kx(e){return yh.includes(e)||e.startsWith("image/")}function Ul(e){return Kx(e.type)}function bh(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function vh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ul(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 Ch(e,t=Bo,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 Gx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wh(e,t){let n=Gx(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"}var Yx=["user","assistant","system"],Jx=0;function xh(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function ql(e){return typeof e=="string"?e:void 0}function Xx(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?Wo(t.text):null;case"image":return typeof t.image=="string"?Ip(t.image,{mimeType:ql(t.mimeType),alt:ql(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?bh(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...ql(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...ql(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function Qx(e,t){let n=xh(t),o=e.map(i=>xh(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,u=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,g=p!==null&&n!==null?Math.min(p,n):p??n;for(let y=0;y<d;y+=1)r[s+y]=g!==null?g-(d-y):u!==null?u+y+1:Jx+y;s=l+1}return r.map(i=>new Date(i).toISOString())}function Sh(e,t){let n=Qx(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!Yx.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(Xx).filter(p=>p!==null),u=Hp(d);o.push({id:r.id,role:i,content:u||(oa(d)?Ws:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function ra(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function sa(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var Zx="https://api.runtype.com/v1/dispatch",Ah="https://api.runtype.com",Oe=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},Th=32768,Rp=49152,Eh=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},Mh=e=>"reason"in e?e.reason:void 0,kh="The identity proof was not admitted; account history is unavailable",Ph="The identity proof was rejected",Lh="The request carried no visitor credential",Hh="The stored visitor belongs to a different signed-in user",Ih=(e,t)=>e instanceof Oe&&e.code===t;function eS(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 Wp=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 tS(e){switch(e){case"json":return Pp;case"regex-json":return kp;case"xml":return Lp;default:return Mp}}var Rh=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nS(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=Rh(n);if(!Rh(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=na(e);return na(t)!==null&&i===null?t:e}var Bs=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;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??Zx,this.headers={"Content-Type":"application/json","X-Persona-Version":Ro,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??tS(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 Ki(t.webmcp):null}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=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=Vm(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)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ah}getClientApiUrl(t){return`${this.clientApiBase()}/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}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&Mh(n)===Mh(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),s=r.agentId??r.flowId,i=n?t.conversationId:void 0,l={token:this.config.clientToken,...s&&{flowId:s},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...i?{conversationId:i}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ro},body:JSON.stringify(l)});if(!d.ok){let p=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&p.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),i)throw new Oe("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw n&&d.status===401&&p.error==="visitor_required"?new Oe("visitor_required","Visitor credential no longer resolves"):i&&d.status===404?new Oe("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):d.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let u=await d.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(t&&n)try{let o=await this.createClientSession({conversationId:t});return this.finishInit(o,t,!1)}catch(o){if(!Ih(o,"not_found")&&!Ih(o,"visitor_required"))throw o;return this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Oe("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/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":Ro},body:JSON.stringify(r)});if(!s.ok){let i=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(i.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})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Oe("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",kh);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ph);if(r.includes("visitor token required"))throw new Oe("visitor_token_missing",Lh);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Oe("visitor_identity_mismatch",Hh);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Oe("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new Oe("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new Oe("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Oe("proof_not_admitted",kh);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Oe("invalid_identity_proof",Ph)):r.includes("visitor token required")?new Oe("visitor_token_missing",Lh):r.includes("visitor_identity_mismatch")?new Oe("visitor_identity_mismatch",Hh):new Oe("unauthorized",o||"History request was not authorized")}return new Oe("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Oe("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Oe("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Oe("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let i=this.historyInternals.visitorStore,l=!1;for(;;){let d=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new Oe("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Ro,...u?{"X-Visitor-Token":u}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(p.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),s,o);continue}if(!p.ok)throw await this.historyErrorFor(p,o);let g=p.headers.get("X-History-Identity-Status"),y=await p.json().catch(()=>{});if(i&&i.revision()!==d)throw new Oe("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(g,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Oe("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(Eh),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:Eh(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>Th)throw new Oe("payload_too_large",`displayContent exceeds the ${Th} character limit`);o+=u}if(o>Rp)throw new Oe("payload_too_large",`Display projection batch exceeds the ${Rp} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=Rp,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&this.clientSession?.conversationId===t&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(t){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}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,i=this.isHistoryCapable(),l={sessionId:o.sessionId,messages:t.messages.filter(Wp).map(p=>{let g=i?ra(p):void 0;return{id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,...g!==void 0&&{displayContent:g}}}),...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:d,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let g={...l,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ro},body:JSON.stringify(g),signal:t.signal})});if(!d.ok){let p=await d.json().catch(()=>({error:"Chat request failed"}));if(d.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let y=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:y}),y}if(d.status===429){let y=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:y}),y}if(d.status===410&&p.error==="conversation_deleted"){let y=new Oe("conversation_deleted","This conversation was deleted");throw n({type:"error",error:y}),y}let g=new Error(p.error||"Failed to send message");throw n({type:"error",error:g}),g}if(!d.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}u(),n({type:"status",status:"connected"});try{await this.streamResponse(d.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!(r instanceof Oe)&&!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 i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}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(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}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 i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}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(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}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 o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,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),i=s?zm(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===i,u=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,g;for(let y=0;;y++){if(g=await o({...s&&(p||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&y===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ah}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(d.sessionId=i),r&&i){let u=[...Zi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:p,commit:g}=await this.sendWithClientToolsDiff(i,u,y=>{let m={...d,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(s,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return p.ok&&g(),p}return fetch(s,{method:"POST",headers:l,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(Wp).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Zi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);return i&&(r.context=i),r}async buildPayload(t){let n=t.slice().filter(Wp).sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,d]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=d);let s=[...Zi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let d=l;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return o.current=g,r(g),g},u=p=>o.current?o.current:d(p);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(i.current=l.partId);let p=u(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",d=Date.now(),u=0,p=()=>d+u++,g=N=>{let ee=N.reasoning?{...N.reasoning,chunks:[...N.reasoning.chunks]}:void 0,w=N.toolCall?{...N.toolCall,chunks:N.toolCall.chunks?[...N.toolCall.chunks]:void 0}:void 0,S=N.tools?N.tools.map(H=>({...H,chunks:H.chunks?[...H.chunks]:void 0})):void 0;return{...N,reasoning:ee,toolCall:w,tools:S}},y=N=>{if(N.role!=="assistant"||N.variant)return!0;let ee=Array.isArray(N.contentParts)&&N.contentParts.length>0,w=typeof N.rawContent=="string"&&N.rawContent.trim()!=="";return typeof N.content=="string"&&N.content.trim()!==""||ee||w||!!N.stopReason},m=N=>{y(N)&&n({type:"message",message:g(N)})},b=null,x=null,T={current:null},L={current:null},D=null,k="",A=new Map,W=new Map,I=new Map,R=new Map,z=new Map,q={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},$=N=>{if(N==null)return null;try{return String(N)}catch{return null}},J=N=>$(N.stepId??N.step_id??N.step??N.parentId??N.flowStepId??N.flow_step_id),pe=N=>$(N.callId??N.call_id??N.requestId??N.request_id??N.toolCallId??N.tool_call_id??N.stepId??N.step_id),we=o,ve=!1,he=()=>{if(b)return b;let N,ee="",w=D;return!ve&&we?(N=we,ve=!0,ee=r??""):we&&w?N=`${we}_${w}`:N=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:N,role:"assistant",content:ee,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(b),b},ne=(N,ee)=>{q.lastId=ee,N&&q.byStep.set(N,ee)},ae=(N,ee)=>{let w=N.reasoningId??N.id,S=J(N);if(w){let P=String(w);return ne(S,P),P}if(S){let P=q.byStep.get(S);if(P)return q.lastId=P,P}if(q.lastId&&!ee)return q.lastId;if(!ee)return null;let H=`reason-${p()}`;return ne(S,H),H},ie=N=>{let ee=R.get(N);if(ee)return ee;let w={id:`reason-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:N,status:"streaming",chunks:[]}};return R.set(N,w),m(w),w},M=(N,ee)=>{Q.lastId=ee,N&&Q.byCall.set(N,ee)},Z=new Set,de=new Map,Ce=new Set,fe=new Map,xe=N=>{if(!N)return!1;let ee=N.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},Pe=(N,ee)=>{let w=N.toolId??N.id,S=pe(N);if(w){let P=String(w);return M(S,P),P}if(S){let P=Q.byCall.get(S);if(P)return Q.lastId=P,P}if(Q.lastId&&!ee)return Q.lastId;if(!ee)return null;let H=`tool-${p()}`;return M(S,H),H},Le=N=>{let ee=z.get(N);if(ee)return ee;let w={id:`tool-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:N,status:"pending"}};return z.set(N,w),m(w),w},Je=N=>{if(typeof N=="number"&&Number.isFinite(N))return N;if(typeof N=="string"){let ee=Number(N);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let w=Date.parse(N);if(!Number.isNaN(w))return w}return Date.now()},Be=N=>{if(typeof N=="string")return N;if(N==null)return"";try{return JSON.stringify(N)}catch{return String(N)}},Re=new Map,et=new Map,be=new Map,_e=(N,ee,w)=>{let S=be.get(N);S||(S=[],be.set(N,S));let H=0,P=S.length;for(;H<P;){let G=H+P>>>1;S[G].seq<ee?H=G+1:P=G}S[H]?.seq===ee?S[H]={seq:ee,text:w}:S.splice(H,0,{seq:ee,text:w});let B="";for(let G=0;G<S.length;G++)B+=S[G].text;return B},gt=(N,ee)=>{let w=Be(ee),S=et.get(N.id),H=nS(S,w);N.rawContent=H;let P=Re.get(N.id),B=le=>{let ct=N.content??"";le.trim()!==""&&(ct.trim().length===0||le.startsWith(ct)||le.trimStart().startsWith(ct.trim()))&&(N.content=le)},G=()=>{if(P){let le=P.close?.();le instanceof Promise&&le.catch(()=>{})}Re.delete(N.id),et.delete(N.id),N.streaming=!1,m(N)};if(!P){B(w),G();return}let X=na(H);if(X!==null&&X.trim()!==""){B(X),G();return}let K=le=>{let ct=typeof le=="string"?le:le?.text??null;if(ct!==null&&ct.trim()!=="")return ct;let ot=P.getExtractedText();return ot!==null&&ot.trim()!==""?ot:w},V;try{V=P.processChunk(H)}catch{B(w),G();return}if(V instanceof Promise){V.then(le=>{B(K(le)),G()}).catch(()=>{B(w),G()});return}B(K(V)),G()},Se=null,Ne=(N,ee,w,S)=>{N.rawContent=ee,Re.has(N.id)||Re.set(N.id,this.createStreamParser());let H=Re.get(N.id),P=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(P&&et.set(N.id,ee),H.__isPlainTextParser===!0){N.content=S!==void 0?ee:N.content+w,et.delete(N.id),Re.delete(N.id),N.rawContent=void 0,m(N);return}let G=H.processChunk(ee);if(G instanceof Promise)G.then(X=>{let K=typeof X=="string"?X:X?.text??null;K!==null&&K.trim()!==""?(N.content=K,m(N)):!P&&!ee.trim().startsWith("<")&&(N.content=S!==void 0?ee:N.content+w,et.delete(N.id),Re.delete(N.id),N.rawContent=void 0,m(N))}).catch(()=>{N.content=S!==void 0?ee:N.content+w,et.delete(N.id),Re.delete(N.id),N.rawContent=void 0,m(N)});else{let X=typeof G=="string"?G:G?.text??null;X!==null&&X.trim()!==""?(N.content=X,m(N)):!P&&!ee.trim().startsWith("<")&&(N.content=S!==void 0?ee:N.content+w,et.delete(N.id),Re.delete(N.id),N.rawContent=void 0,m(N))}},it=(N,ee)=>{let w=ee??N.content;if(w==null||w===""){N.streaming=!1,m(N);return}let H=et.get(N.id)??Be(w);N.rawContent=H;let P=Re.get(N.id),B=null,G=!1;if(P&&(B=P.getExtractedText(),B===null&&(B=na(H)),B===null)){let X=P.processChunk(H);X instanceof Promise?(G=!0,X.then(K=>{let V=typeof K=="string"?K:K?.text??null;V!==null&&(N.content=V,N.streaming=!1,Re.delete(N.id),et.delete(N.id),m(N))}).catch(()=>{})):B=typeof X=="string"?X:X?.text??null}if(!G){B!==null&&B.trim()!==""?N.content=B:et.has(N.id)||(N.content=Be(w));let X=Re.get(N.id);if(X){let K=X.close?.();K instanceof Promise&&K.catch(()=>{}),Re.delete(N.id)}et.delete(N.id),N.streaming=!1,m(N)}},Kt=(N,ee,w)=>{let S=W.get(N);if(S)return S;let H={id:`nested-${ee}-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...w?{variant:w}:{},...w==="reasoning"?{reasoning:{id:N,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return W.set(N,H),m(H),H},zt=[],Un,Ze=new Map,tt=0,vt="agent",Qt=!1,fo=null,It=null,No=new Map,rs=this.config.iterationDisplay??"separate";for(Un=()=>{for(let N=0;N<zt.length;N++){let ee=zt[N].payloadType,w=zt[N].payload;if(!Qt&&vt!=="flow"&&typeof w.stepType=="string"&&(vt="flow"),ee==="reasoning_start"){let S=typeof w.id=="string"?w.id:null,H=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(S&&H){A.set(S,H),Kt(S,H,"reasoning");continue}let P=ae(w,!0)??`reason-${p()}`,B=ie(P);B.reasoning=B.reasoning??{id:P,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Je(w.startedAt??w.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(B.reasoning.scope=w.scope),B.streaming=!0,B.reasoning.status="streaming",m(B)}else if(ee==="reasoning_delta"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)&&W.has(S)){let G=W.get(S),X=w.reasoningText??w.text??w.delta??"";X&&w.hidden!==!0&&G.reasoning&&(G.reasoning.chunks.push(String(X)),m(G));continue}let H=ae(w,!1)??ae(w,!0)??`reason-${p()}`,P=ie(H);P.reasoning=P.reasoning??{id:H,status:"streaming",chunks:[]},P.reasoning.startedAt=P.reasoning.startedAt??Je(w.startedAt??w.timestamp);let B=w.reasoningText??w.text??w.delta??"";if(B&&w.hidden!==!0){let G=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(G!==void 0){let X=_e(H,G,String(B));P.reasoning.chunks=[X]}else P.reasoning.chunks.push(String(B))}if(P.reasoning.status=w.done?"complete":"streaming",w.done){P.reasoning.completedAt=Je(w.completedAt??w.timestamp);let G=P.reasoning.startedAt??Date.now();P.reasoning.durationMs=Math.max(0,(P.reasoning.completedAt??Date.now())-G)}P.streaming=P.reasoning.status!=="complete",m(P)}else if(ee==="reasoning_complete"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)&&W.has(S)){let X=W.get(S);if(X.reasoning){let K=typeof w.text=="string"?w.text:"";K&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(K),X.reasoning.status="complete",X.streaming=!1,m(X)}A.delete(S),W.delete(S);continue}let H=ae(w,!1)??ae(w,!0)??`reason-${p()}`,P=typeof w.text=="string"?w.text:"";!R.get(H)&&(P||w.scope==="loop")&&ie(H);let B=R.get(H);if(B?.reasoning){(w.scope==="loop"||w.scope==="turn")&&(B.reasoning.scope=w.scope),P&&B.reasoning.chunks.length===0&&B.reasoning.chunks.push(P),B.reasoning.status="complete",B.reasoning.completedAt=Je(w.completedAt??w.timestamp);let X=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-X),B.streaming=!1,m(B)}let G=J(w);G&&q.byStep.delete(G)}else if(ee==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof w.iteration=="number"&&(tt=w.iteration);let S=(typeof w.toolCallId=="string"?w.toolCallId:void 0)??Pe(w,!0)??`tool-${p()}`,H=w.toolName??w.name;if(xe(H)){Z.add(S);continue}M(pe(w),S);let P=Le(S),B=P.toolCall??{id:S,status:"pending"};B.name=H??B.name,B.status="running",w.parameters!==void 0?B.args=w.parameters:w.args!==void 0&&(B.args=w.args),B.startedAt=B.startedAt??Je(w.startedAt??w.timestamp),B.completedAt=void 0,B.durationMs=void 0,P.toolCall=B,P.streaming=!0,w.executionId&&(P.agentMetadata={executionId:w.executionId,iteration:w.iteration}),m(P)}else if(ee==="tool_output_delta"){let S=Pe(w,!1)??Pe(w,!0)??`tool-${p()}`;if(Z.has(S))continue;let H=Le(S),P=H.toolCall??{id:S,status:"running"};P.startedAt=P.startedAt??Je(w.startedAt??w.timestamp);let B=w.text??w.delta??w.message??"";B&&(P.chunks=P.chunks??[],P.chunks.push(String(B))),P.status="running",H.toolCall=P,H.streaming=!0;let G=w.agentContext;(G||w.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:G?.executionId??w.executionId,iteration:G?.iteration??w.iteration}),m(H)}else if(ee==="tool_complete"){let S=Pe(w,!1)??Pe(w,!0)??`tool-${p()}`;if(Z.has(S)){Z.delete(S);continue}let H=Le(S),P=H.toolCall??{id:S,status:"running"};P.status="complete",w.result!==void 0&&(P.result=w.result),typeof w.duration=="number"&&(P.duration=w.duration),P.completedAt=Je(w.completedAt??w.timestamp);let B=w.duration??w.executionTime;if(typeof B=="number")P.durationMs=B;else{let K=P.startedAt??Date.now();P.durationMs=Math.max(0,(P.completedAt??Date.now())-K)}H.toolCall=P,H.streaming=!1;let G=w.agentContext;(G||w.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:G?.executionId??w.executionId,iteration:G?.iteration??w.iteration}),m(H);let X=pe(w);X&&Q.byCall.delete(X)}else if(ee==="await"&&w.toolName){let S=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,H=S??w.toolId??`local-${p()}`,P=Le(H),B=w.toolName,G=w.origin==="webmcp"&&!Nr(B)?`webmcp:${B}`:B,X=Nr(G),K=P.toolCall??{id:H,status:"pending"};K.name=G,K.args=w.parameters,K.status=X?"running":"complete",K.chunks=K.chunks??[],K.startedAt=K.startedAt??Je(w.startedAt??w.timestamp??w.awaitedAt),X?(K.completedAt=void 0,K.duration=void 0,K.durationMs=void 0):K.completedAt=K.completedAt??K.startedAt,P.toolCall=K,P.streaming=!1,P.agentMetadata={...P.agentMetadata,executionId:w.executionId??P.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},m(P)}else if(ee==="text_start"){let S=typeof w.id=="string"?w.id:null,H=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(S&&H){A.set(S,H);continue}let P=b;P&&(vt==="flow"?(it(P),Se=P):(P.streaming=!1,m(P)),b=null),D=typeof w.id=="string"?w.id:D,k=""}else if(ee==="text_delta"){let S=typeof w.id=="string"?w.id:null,H=S?A.get(S):void 0;if(S&&H){let B=typeof w.delta=="string"?w.delta:"",G=(I.get(S)??"")+B;if(I.set(S,G),G.trim()==="")continue;let X=Kt(S,H);X.agentMetadata={...X.agentMetadata,executionId:w.executionId,parentToolId:H},Ne(X,G,B,void 0);continue}if(D=typeof w.id=="string"?w.id:D,vt==="flow"){let B=typeof w.delta=="string"?w.delta:"";if(k+=B,k.trim()==="")continue;let G=he();G.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ne(G,k,B,void 0),x=G;continue}let P=he();P.content+=w.delta??"",P.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:fo??void 0,agentName:It?.agentName},x=P,m(P)}else if(ee==="text_complete"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)){let P=W.get(S);P&&it(P),A.delete(S),I.delete(S),W.delete(S);continue}let H=b;H&&(vt==="flow"?(it(H),Se=H):((H.content??"")===""&&typeof w.text=="string"&&(H.content=w.text),H.streaming=!1,m(H)),b=null),D=null,k=""}else if(ee==="step_complete"){let S=w.stepType,H=w.executionType;if(S==="tool"||H==="context")continue;if(w.success===!1){let P=w.error,B=typeof P=="string"&&P!==""?P:P!=null&&typeof P=="object"&&Reflect.has(P,"message")?String(P.message??"Step failed"):"Step failed";n({type:"error",error:new Error(B)});let G=b;G&&G.streaming&&(G.streaming=!1,m(G)),n({type:"status",status:"idle"});continue}{let P=Se;Se=null;let B=w.stopReason,G=w.result?.response;if(P)B&&(P.stopReason=B),G!=null?gt(P,G):P.streaming!==!1&&(Re.delete(P.id),et.delete(P.id),P.streaming=!1,m(P));else{let X=G!=null&&G!=="";if(X||B){let K=he();B&&(K.stopReason=B),X?it(K,G):(K.streaming=!1,m(K))}}continue}}else if(ee==="execution_start")vt=w.kind==="flow"?"flow":"agent",Qt=!0,vt==="agent"&&(It={executionId:w.executionId,agentId:w.agentId??"virtual",agentName:w.agentName??"",status:"running",currentIteration:0,maxTurns:w.maxTurns??1,startedAt:Je(w.startedAt)});else if(ee==="turn_start"){let S=typeof w.iteration=="number"?w.iteration:tt;if(S!==tt){if(It&&(It.currentIteration=S),rs==="separate"&&S>1){let H=b;H&&(H.streaming=!1,m(H),No.set(S-1,H),b=null)}tt=S}fo=typeof w.id=="string"?w.id:null,x=null}else if(ee==="tool_input_delta"){let S=w.toolCallId??Q.lastId;if(S){let H=z.get(S);H?.toolCall&&(H.toolCall.chunks=H.toolCall.chunks??[],H.toolCall.chunks.push(w.delta??""),m(H))}}else{if(ee==="tool_input_complete")continue;if(ee==="turn_complete"){let S=w.stopReason,H=b??x;if(S&&H!==null){let P=w.id;(!P||H.agentMetadata?.turnId===P)&&(H.stopReason=S,m(H))}fo===w.id&&(fo=null)}else if(ee==="media_start"){let S=String(w.id);Ze.set(S,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ee==="media_delta"){let S=Ze.get(String(w.id));S&&typeof w.delta=="string"&&S.parts.push(w.delta)}else if(ee==="media_complete"){let S=String(w.id),H=Ze.get(S);Ze.delete(S);let P=(typeof w.mediaType=="string"?w.mediaType:void 0)??H?.mediaType??"application/octet-stream",B=typeof w.data=="string"?w.data:void 0,G=typeof w.url=="string"?w.url:H&&H.parts.length>0?H.parts.join(""):void 0,X=null;if(B)X={type:"media",data:B,mediaType:P};else if(G){let ct=P.toLowerCase();X={type:ct==="image"||ct.startsWith("image/")?"image-url":"file-url",url:G,mediaType:P}}let K=w.toolCallId??H?.toolCallId,V=X?[X]:[],le=[];for(let ct of V){if(!ct||typeof ct!="object")continue;let ot=ct,Ct=typeof ot.type=="string"?ot.type:void 0,me=typeof ot.mediaType=="string"?ot.mediaType.toLowerCase():"",ye=null,Zt="";if(Ct==="media"){let ze=typeof ot.data=="string"?ot.data:void 0;if(!ze)continue;Zt=me.length>0?me:"application/octet-stream",ye=`data:${Zt};base64,${ze}`}else if(Ct==="image-url"){let ze=typeof ot.url=="string"?ot.url:void 0;if(!ze)continue;Zt=me,ye=ze}else if(Ct==="file-url"){let ze=typeof ot.url=="string"?ot.url:void 0;if(!ze)continue;Zt=me,ye=ze}else continue;if(ye)if(Ct==="image-url"||Zt.startsWith("image/"))le.push({type:"image",image:ye,...Zt.includes("/")?{mimeType:Zt}:{}});else if(Zt.startsWith("audio/"))le.push({type:"audio",audio:ye,mimeType:Zt});else if(Zt.startsWith("video/"))le.push({type:"video",video:ye,mimeType:Zt});else{let ze=Zt||"application/octet-stream";le.push({type:"file",data:ye,mimeType:ze,filename:eS(ze)})}}if(le.length>0){let ct=p(),ot=K,me={id:`agent-media-${typeof ot=="string"&&ot.length>0?`${ot}-${ct}`:String(ct)}`,role:"assistant",content:"",contentParts:le,createdAt:new Date().toISOString(),streaming:!1,sequence:ct,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:tt}};m(me);let ye=b;ye&&(ye.streaming=!1,m(ye)),b=null,T.current=null}}else if(ee==="execution_complete"){let S=w.kind??vt;S==="agent"&&It&&(It.status=w.success?"complete":"error",It.completedAt=Je(w.completedAt),It.stopReason=w.stopReason);let H=b;H&&(S==="flow"&&H.streaming!==!1?it(H):(H.streaming=!1,m(H)),b=null),D=null,k="",Se=null,n({type:"status",status:"idle",terminal:!0})}else if(ee==="execution_error"){let S=typeof w.error=="string"?w.error:w.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(ee!=="ping"){if(ee==="approval_start"){let S=w.approvalId??`approval-${p()}`,H={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:"pending",agentId:It?.agentId??"virtual",executionId:w.executionId??It?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};m(H)}else if(ee==="step_await"&&w.awaitReason==="approval_required"){let S=w.approvalId??`approval-${p()}`,H={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:"pending",agentId:It?.agentId??"virtual",executionId:w.executionId??It?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};m(H)}else if(ee==="approval_complete"){let S=w.approvalId;if(S){let P={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:w.decision??"approved",agentId:It?.agentId??"virtual",executionId:w.executionId??It?.executionId??"",toolName:w.toolName??"",description:w.description??"",resolvedAt:Date.now()}};m(P)}}else if(ee==="artifact_start"||ee==="artifact_delta"||ee==="artifact_update"||ee==="artifact_complete"){if(ee==="artifact_start"){let S=w.artifactType,H=String(w.id),P=typeof w.title=="string"?w.title:void 0,B=w.file,G;B&&typeof B=="object"&&!Array.isArray(B)&&typeof B.path=="string"&&typeof B.mimeType=="string"&&(G={path:B.path,mimeType:B.mimeType,...typeof B.language=="string"?{language:B.language}:{}}),n({type:"artifact_start",id:H,artifactType:S,title:P,component:typeof w.component=="string"?w.component:void 0,...G?{file:G}:{}});let X=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?{...w.props}:void 0;if(fe.set(H,{markdown:"",title:P,file:G,...X?{props:X}:{}}),!Ce.has(H)){Ce.add(H);let K=Io(this.config.features?.artifacts,{artifactType:S,...G?{file:G}:{}}),V=typeof w.component=="string"?w.component:void 0,le={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:Yi(K,{artifactId:H,title:P,artifactType:S,status:"streaming",...G?{file:G}:{},...V?{component:V}:{}})};de.set(H,le),m(le)}}else if(ee==="artifact_delta"){let S=String(w.id),H=typeof w.delta=="string"?w.delta:String(w.delta??"");n({type:"artifact_delta",id:S,artDelta:H});let P=fe.get(S);P&&(P.markdown+=H)}else if(ee==="artifact_update"){let S=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:S,component:typeof w.component=="string"?w.component:void 0});let H=fe.get(String(w.id));H&&(H.props={...H.props??{},...S})}else if(ee==="artifact_complete"){let S=String(w.id);n({type:"artifact_complete",id:S});let H=de.get(S);if(H){H.streaming=!1;try{let P=JSON.parse(H.rawContent??"{}");if(P.props){P.props.status="complete";let B=fe.get(S);B?.markdown&&(P.props.markdown=B.markdown),B?.file&&(P.props.file=B.file),P.component==="PersonaArtifactInline"&&B?.props&&Object.keys(B.props).length>0&&(P.props.componentProps=B.props)}H.rawContent=JSON.stringify(P)}catch{}fe.delete(S),m(H),de.delete(S)}}}else if(ee==="transcript_insert"){let S=w.message;if(!S||typeof S!="object")continue;let H=String(S.id??`msg-${p()}`),P=S.role,G={id:H,role:P==="user"?"user":P==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:p()};if(m(G),G.rawContent)try{let K=JSON.parse(G.rawContent)?.props?.artifactId;typeof K=="string"&&Ce.add(K)}catch{}b=null,T.current=null,Re.delete(H),et.delete(H)}else if(ee==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let S=typeof w.error=="string"?w.error:w.error?.message!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(S)});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}else if(ee==="step_error"||ee==="dispatch_error"||ee==="flow_error"){let S=null;if(w.error instanceof Error)S=w.error;else if(ee==="dispatch_error"){let H=w.message??w.error;H!=null&&H!==""&&(S=new Error(String(H)))}else{let H=w.error;typeof H=="string"&&H!==""?S=new Error(H):H!=null&&typeof H=="object"&&Reflect.has(H,"message")&&(S=new Error(String(H.message??H)))}if(S){n({type:"error",error:S});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}}}}zt.length=0};;){let{done:N,value:ee}=await s.read();if(N)break;l+=i.decode(ee,{stream:!0});let w=l.split(`
|
|
12
12
|
|
|
13
|
-
`);
|
|
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,`
|
|
13
|
+
`);l=w.pop()??"";for(let S of w){let H=S.split(`
|
|
14
|
+
`),P="message",B="",G=null;for(let le of H)le.startsWith("event:")?P=le.replace("event:","").trim():le.startsWith("data:")?B+=le.replace("data:","").trim():le.startsWith("id:")&&(G=le.slice(3).trim());let X=()=>{G!==null&&G!==""&&n({type:"cursor",id:G})};if(!B){X();continue}let K;try{K=JSON.parse(B)}catch(le){n({type:"error",error:le instanceof Error?le:new Error("Failed to parse chat stream payload")});continue}let V=P!=="message"?P:K.type??"message";if(this.onSSEEvent?.(V,K),this.parseSSEEvent){T.current=b;let le=await this.handleCustomSSEEvent(K,n,T,m,p,L);if(T.current&&T.current!==b&&(b=T.current),le){X();continue}}zt.push({payloadType:V,payload:K}),Un(),X()}}Un()}};function oS(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ia(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function zr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xn=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function rS(e){return e instanceof Xn}Bp();var Wh=16e3,sS=24e3,iS=4096,aS=1380533830;function lS(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===aS?new Uint8Array(e,44):new Uint8Array(e)}function cS(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 aa=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){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:Wh,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Wh});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Os(sS);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(g=>g.stop()),l.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 u=`${cS(o)}/ws/agents/${encodeURIComponent(t)}/voice`,p=new WebSocket(u,["runtype.bearer",n]);p.binaryType="arraybuffer",this.ws=p,p.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,p,r))},p.onmessage=g=>this.handleMessage(g,r),p.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},p.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let y=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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 i=t.createScriptProcessor(iS,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),u=new Int16Array(d.length);for(let p=0;p<d.length;p++){let g=Math.max(-1,Math.min(1,d[p]));u[p]=g<0?g*32768:g*32767}o.send(u.buffer)},s.connect(i),i.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=lS(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 Ur=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 qr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new aa(e.runtype);case"browser":if(!Ur.isSupported())throw new Error("Browser speech recognition not supported");return new Ur(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 Op(e){if(e?.type==="custom"&&e.custom)return qr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return qr({type:"runtype",runtype:e.runtype});if(Ur.isSupported())return qr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Vl(e){try{return Op(e),!0}catch{return!1}}function la(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 Vr=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 i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):la(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"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 Ds=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 Dp(e){if(!e)return"";let t=dS(e);return Bh(t!==null?t:e)}function dS(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 Bh(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 Fh=null;var _p=()=>Fh?Fh():Promise.resolve().then(()=>(Nh(),_h));var mS=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function hS(e,t){return mS.some(n=>e[n]!==t[n])}var ao=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function Np(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 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(`
|
|
18
|
+
_Details: ${n.message}_`:o}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),zh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Uh=e=>Nr(e)||e===io,da=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;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.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ds(()=>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&&(Nr(n.name)||n.name===io&&nr(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,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());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.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Bs(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,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||_p().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 Vl(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=Vr.isSupported()?new Vr({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,i=t.browserFallback!==!1;if(o&&r&&s)return _p().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let u=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new d(u,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&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=qr(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,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let d=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=d.id}if(l){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:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let d=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=d.id}l&&(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;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);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){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;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)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new ao("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let n=this.requireHistoryProvider(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new Xn("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new ao("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await o.getPage(t,{context:r});if(s!==this.historyOpenEpoch)throw new ao("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new ao("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||t,this.activeConversationRevision=l.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),i=n??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,d=this.olderPageRequests.get(l);if(d)return d;let u=this.fetchOlderPage(r,t,i,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,u),u}async fetchOlderPage(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=sa(this.messages,i.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=i.nextCursor;for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new ao("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new ao("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new ao("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:t});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new ao("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),d=this.messages.some(g=>l.has(g.id)),u=i.messages[0]?.createdAt,p;if(!d)p=i.messages.map(g=>this.ensureSequence(g));else{let g=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(m=>l.has(m.id)||m.id===g?!0:u!==void 0&&m.createdAt<u);p=sa(y,i.messages).map(m=>this.ensureSequence(m))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let g of i.messages)this.acknowledgedProjections.set(g.id,g.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=ra(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=ra(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof Oe&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof Oe?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof Oe&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o},this.handleEvent);return}catch(s){if(!e.isConversationDeleted(s))throw s;let i=await this.recoverFromDeletedConversation(r);if(!i)throw s;this.recordDispatchedProjections([i]),await this.client.dispatch({messages:[i],signal:n.signal,assistantMessageId:o},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!hS(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 Bs(this.config,this.historyInternals),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:i,createdAt:l,sequence:d,streaming:u=!1,voiceProcessing:p,rawContent:g}=t,m={id:i??(n==="user"?ia():n==="assistant"?zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}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:i,contentParts:l,id:d,createdAt:u,sequence:p,streaming:g=!1,voiceProcessing:y,rawContent:m}=o,x={id:d??(r==="user"?ia():r==="assistant"?zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...m!==void 0&&{rawContent:m}};n.push(x)}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:i,createdAt:l,sequence:d}=t,u={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
19
19
|
|
|
20
|
-
`),
|
|
20
|
+
`),i=[s,n].filter(Boolean).join(`
|
|
21
21
|
|
|
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===""||
|
|
24
|
-
`||
|
|
25
|
-
`).some(
|
|
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(`
|
|
22
|
+
`),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let u=[];s&&u.push(Wo(s)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(d){let u=[];i&&u.push(Wo(i)),u.push(...r.contentParts),t.contentParts=u}else s&&(t.llmContent=i);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.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ia(),s=zr();this.activeAssistantMessageId=null;let i=n?.contentParts&&oa(n.contentParts)?Ws:"",l={id:r,role:"user",content:o||i,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(l),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let p=this.messages.find(g=>g.id===r)??l;if(await this.applyMentionBundle(p,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,d,s,r)}catch(p){if(this.status==="resuming"||this.reconnecting)return;let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));if(!g){let y=Np(p,this.config.errorMessage);if(y){let m={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(p instanceof Error?this.callbacks.onError?.(p):this.callbacks.onError?.(new Error(String(p))))}}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=zr();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 i=Np(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}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()},i=this.messages.find(p=>p.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),p){let g=null;if(p instanceof Response){if(!p.ok){let y=await p.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${p.status}`)}g=p.body}else p instanceof ReadableStream&&(g=p);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(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}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(p=>p.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 i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let p=t.toolCall?.args,g=Array.isArray(p?.questions)?p.questions:[];if(g.length===1){let y=typeof g[0]?.question=="string"?g[0].question:"";y&&(i={[y]:n})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((g,y)=>{let m=typeof g?.question=="string"?g.question:"";if(!m)return;let b=p[m],x=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[s]:n});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}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!==io?!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(i=>i.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 i=await Promise.all(n.map(async d=>{let u=d.toolCall?.name,p=d.toolCall?.id;if(!u||!p)return null;let g=`${t}:${p}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(g),o.push(g);let y=this.markWebMcpToolRunning(d),m=d.agentMetadata?.webMcpToolCallId??u;if(u===io)return{dedupeKey:g,resumeKey:m,output:Ap(),toolMessage:d,startedAt:y,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let x=this.client.executeWebMcpToolCall(u,d.toolCall?.args,b.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(L){let D=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return D||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(d,ca(D?"Aborted by cancel()":zh(L)),y),this.webMcpInflightKeys.delete(g),null}return b.signal.aborted?(this.markWebMcpToolComplete(d,ca("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:m,output:T,toolMessage:d,startedAt:y,completedAt:Date.now()}})),l=[];try{if(l=i.filter(p=>p!==null),l.length===0)return;let d={};for(let p of l)d[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,d,{signal:s.signal});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of l)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===io?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.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 p of l)this.markWebMcpToolComplete(p.toolMessage,ca("Aborted by cancel()"),p.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(x){this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let u=o===io,p=t.toolCall?.args,g=u?null:this.client.executeWebMcpToolCall(o,p,d),y="execute",m=i;try{let b;if(u?b=Ap():g?b=await g:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),i);return}let x=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,x,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,b,i,m,u?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(b){let x=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(y==="execute"||x||d.aborted)&&this.markWebMcpToolComplete(t,ca(x||d.aborted?"Aborted by cancel()":zh(b)),i),x||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),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 i=await s.json().catch(()=>null);throw new Error(i?.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=Io(this.config.features?.artifacts,t),r=Yi(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(i=>i.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(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Io(this.config.features?.artifacts,n),s=Yi(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(()=>(jh(),$h)).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=>Np(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=zr(),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=Dp(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Dp(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 i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let p=r.approval,g=n.approval;i.approval={...p,...g,executionId:g.executionId||p.executionId,toolName:g.toolName||p.toolName,description:g.description||p.description,toolType:g.toolType??p.toolType,reason:g.reason??p.reason,parameters:g.parameters??p.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(l&&Uh(l)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let p=`${d}:${u}`,g=this.webMcpInflightKeys.has(p),y=this.webMcpResolvedKeys.has(p),m=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===u&&m!==void 0&&Uh(m)&&r.toolCall?.status==="complete";(g||y||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),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 i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};import{Activity as yS,ArrowDown as bS,ArrowUp as vS,ArrowUpRight as CS,Bot as wS,ChevronDown as xS,ChevronUp as SS,ChevronRight as AS,ChevronLeft as TS,Check as ES,Clipboard as MS,ClipboardCopy as kS,CodeXml as PS,Copy as LS,File as HS,FileCode as IS,FileSpreadsheet as RS,FileText as WS,ImagePlus as BS,Loader as OS,LoaderCircle as DS,Mic as _S,Paperclip as NS,RefreshCw as FS,Search as $S,Send as jS,ShieldAlert as zS,ShieldCheck as US,ShieldX as qS,Square as VS,ThumbsDown as KS,ThumbsUp as GS,Upload as YS,Volume2 as JS,X as XS,User as QS,Mail as ZS,Phone as eA,Calendar as tA,Clock as nA,Building as oA,MapPin as rA,Lock as sA,Key as iA,CreditCard as aA,AtSign as lA,Hash as cA,Globe as dA,Link as pA,CircleCheck as uA,CircleX as gA,TriangleAlert as fA,Info as mA,Ban as hA,Shield as yA,ArrowLeft as bA,ArrowRight as vA,ExternalLink as CA,Ellipsis as wA,EllipsisVertical as xA,Menu as SA,House as AA,PanelLeft as TA,Plus as EA,Minus as MA,Pencil as kA,PenLine as PA,Trash as LA,Trash2 as HA,Save as IA,Download as RA,Share as WA,Funnel as BA,Settings as OA,RotateCw as DA,Maximize as _A,Minimize as NA,ShoppingCart as FA,ShoppingBag as $A,Package as jA,Truck as zA,Tag as UA,Gift as qA,Receipt as VA,Wallet as KA,Store as GA,DollarSign as YA,Percent as JA,Play as XA,Pause as QA,VolumeX as ZA,Camera as eT,Image as tT,Film as nT,Headphones as oT,MessageCircle as rT,MessageSquare as sT,Bell as iT,Heart as aT,Star as lT,Eye as cT,EyeOff as dT,Bookmark as pT,CalendarDays as uT,History as gT,Timer as fT,Folder as mT,FolderOpen as hT,Files as yT,ChartColumn as bT,Sparkles as vT,Zap as CT,Sun as wT,Moon as xT,Flag as ST,Lightbulb as AT,Monitor as TT,Smartphone as ET}from"lucide";var MT={activity:yS,"arrow-down":bS,"arrow-up":vS,"arrow-up-right":CS,bot:wS,"chevron-down":xS,"chevron-up":SS,"chevron-right":AS,"chevron-left":TS,check:ES,clipboard:MS,"clipboard-copy":kS,"code-xml":PS,copy:LS,file:HS,"file-code":IS,"file-spreadsheet":RS,"file-text":WS,"image-plus":BS,loader:OS,"loader-circle":DS,mic:_S,paperclip:NS,"refresh-cw":FS,search:$S,send:jS,"shield-alert":zS,"shield-check":US,"shield-x":qS,square:VS,"thumbs-down":KS,"thumbs-up":GS,upload:YS,"volume-2":JS,x:XS,user:QS,mail:ZS,phone:eA,calendar:tA,clock:nA,building:oA,"map-pin":rA,lock:sA,key:iA,"credit-card":aA,"at-sign":lA,hash:cA,globe:dA,link:pA,"circle-check":uA,"circle-x":gA,"triangle-alert":fA,info:mA,ban:hA,shield:yA,"arrow-left":bA,"arrow-right":vA,"external-link":CA,ellipsis:wA,"ellipsis-vertical":xA,menu:SA,house:AA,"panel-left":TA,plus:EA,minus:MA,pencil:kA,"pen-line":PA,trash:LA,"trash-2":HA,save:IA,download:RA,share:WA,funnel:BA,settings:OA,"rotate-cw":DA,maximize:_A,minimize:NA,"shopping-cart":FA,"shopping-bag":$A,package:jA,truck:zA,tag:UA,gift:qA,receipt:VA,wallet:KA,store:GA,"dollar-sign":YA,percent:JA,play:XA,pause:QA,"volume-x":ZA,camera:eT,image:tT,film:nT,headphones:oT,"message-circle":rT,"message-square":sT,bell:iT,heart:aT,star:lT,eye:cT,"eye-off":dT,bookmark:pT,"calendar-days":uT,history:gT,timer:fT,folder:mT,"folder-open":hT,files:yT,"chart-column":bT,sparkles:vT,zap:CT,sun:wT,moon:xT,flag:ST,lightbulb:AT,monitor:TT,smartphone:ET},ce=(e,t=24,n="currentColor",o=2)=>{let r=MT[e];return r?kT(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 kT(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 i=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([u,p])=>{u!=="stroke"&&d.setAttribute(u,String(p))}),r.appendChild(d)}),r}var Yl={allowedTypes:Bo,maxFileSize:10*1024*1024,maxFiles:4};function PT(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function LT(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 _s=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Yl.allowedTypes,maxFileSize:t.maxFileSize??Yl.maxFileSize,maxFiles:t.maxFiles??Yl.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:Yl.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=Ch(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 vh(n),s=Ul(n)?URL.createObjectURL(n):null,i={id:PT(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}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=Ul(t.file),o=v("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 i=v("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=v("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=LT(t.file.type),d=ce(l,20,"var(--persona-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=v("span");u.textContent=wh(t.file.type,t.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--persona-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),o.appendChild(i)}let r=v("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=ce("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",i=>{i.preventDefault(),i.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 qh=/\s/;function HT(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===""||qh.test(o)}function IT(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return HT(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
|
|
24
|
+
`||i==="\uFFFC"||!r&&qh.test(i))return null;s--}return null}function Vh(e,t,n){for(let o of n){let r=IT(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Kh(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Gh(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 _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Jt=1e5,Ns=Jt+1;var RT=8,WT=8,Fp=10,Yh=200,Jh=300,Xh=0,Jl=e=>Math.max(0,e);function Qh(e){e.delayMs!==void 0&&(Yh=Jl(e.delayMs)),e.skipDelayMs!==void 0&&(Jh=Jl(e.skipDelayMs))}var BT=()=>Date.now()<Xh,OT=e=>{Xh=e>0?Date.now()+e:0},$p=new WeakMap,Zh=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,DT=e=>{let t=e.getRootNode?.();return Zh(t)?t:e.ownerDocument.body},jp=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),_T=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Xt(e){$p.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=RT,viewportPadding:l=WT}=e,d=()=>t.ownerDocument,u=()=>d().defaultView??window,p=null,g=null,y=null,m=null,b,x=!1,T=!1,L=!1,D=()=>(typeof o=="function"?o():o).trim(),k=()=>(typeof r=="function"?r():r??"").trim(),A=()=>Jl(e.delayMs??Yh),W=()=>Jl(e.skipDelayMs??Jh),I=()=>{b!==void 0&&(u().clearTimeout(b),b=void 0)},R=()=>{I();let ie=p!==null;m?.(),m=null,p?.remove(),p=null,g=null,y=null,ie&&OT(W())},z=()=>{if(!p)return;let ie=d(),M=u(),Z=t.getBoundingClientRect(),de=p.getBoundingClientRect(),Ce=ie.documentElement.clientWidth||M.innerWidth,fe=ie.documentElement.clientHeight||M.innerHeight,xe=Ce-l-de.width,Pe=Z.left+Z.width/2-de.width/2,Le=jp(Pe,l,xe),Je=Z.top-l,Be=fe-l-Z.bottom,Re=de.height+i,et=Je>=Re||Je>=Be?"top":"bottom",be=et==="top"?Z.top-i-de.height:Z.bottom+i,_e=fe-l-de.height,gt=jp(be,l,_e),Se=Z.left+Z.width/2,Ne=Math.max(Fp,de.width-Fp),it=jp(Se-Le,Fp,Ne);p.dataset.placement=et,p.style.left=`${Le}px`,p.style.top=`${gt}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${it}px`)},q=()=>{if(L||!s||p||!t.isConnected)return;let ie=D(),M=DT(t);if(!ie||!M)return;let Z=d(),de=u();p=Z.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(Ns);let Ce=de.getComputedStyle?.(t);if(Ce){for(let Re of _T){let et=Ce.getPropertyValue(Re).trim();et&&p.style.setProperty(Re,et)}Ce.fontFamily&&(p.style.fontFamily=Ce.fontFamily)}g=Z.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ie,p.appendChild(g);let fe=k();fe&&(y=Z.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=fe,p.appendChild(y));let xe=Z.createElement("span");xe.className="persona-control-tooltip__arrow",p.appendChild(xe),M.appendChild(p),z(),p.dataset.state="open";let Pe=()=>{if(!t.isConnected){R();return}g&&(g.textContent=D()),y&&(y.textContent=k()),z()};de.addEventListener("scroll",Pe,!0),de.addEventListener("resize",Pe);let Le=t.getRootNode(),Je=Zh(Le)?Le:Z.documentElement,Be=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||R()});Be?.observe(Je,{childList:!0,subtree:!0}),m=()=>{de.removeEventListener("scroll",Pe,!0),de.removeEventListener("resize",Pe),Be?.disconnect()}},Q=ie=>{if(!(L||p)){if(I(),ie||A()<=0||BT()){q();return}b=u().setTimeout(()=>{b=void 0,q()},A())}},$=()=>{x||T?Q(T):R()},J=()=>{let ie=u();(!ie.matchMedia||!ie.matchMedia("(hover: none)").matches)&&(x=!0,$())},pe=()=>{x=!1,$()},we=()=>{try{T=t.matches(":focus-visible")}catch{T=!0}$()},ve=()=>{T=!1,$()},he=()=>{x=!1,T=!1,R()},ne=ie=>{ie.key==="Escape"&&he()};n.addEventListener("mouseenter",J),n.addEventListener("mouseleave",pe),t.addEventListener("focus",we),t.addEventListener("blur",ve),t.addEventListener("keydown",ne),t.addEventListener("click",he);let ae={get isOpen(){return p!==null},show:q,hide:R,reposition:z,destroy:()=>{L||(L=!0,R(),n.removeEventListener("mouseenter",J),n.removeEventListener("mouseleave",pe),t.removeEventListener("focus",we),t.removeEventListener("blur",ve),t.removeEventListener("keydown",ne),t.removeEventListener("click",he),$p.delete(t))}};return $p.set(t,ae),ae}function ey(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",d=v("div","persona-send-button-wrapper"),u=ue("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":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),p=ce(i,s,"currentColor",1.5);return p?u.appendChild(p):u.textContent="+",u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),d.appendChild(u),Xt({anchor:u,trigger:d,text:()=>u.getAttribute("aria-label")??l}),{button:u,wrapper:d}}var{setLoader:ZL,load:NT}=ro({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var zp=NT;var{setLoader:nH,load:FT}=ro({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var ty=FT;function ga(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ue("span",{className:Fn("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=ce(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ue("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function ny(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Gh(t).filter(k=>k.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(k=>k.sources.some(A=>typeof A.matchCommand=="function")),r=k=>o.some(A=>A.trigger?A.position==="line-start"?k.split(`
|
|
25
|
+
`).some(I=>I.startsWith(A.trigger)):(A.position==="anywhere"?k:k.split(`
|
|
26
|
+
`)[0]).startsWith(A.trigger):!1),s=(k,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${k}`,{detail:A}))}catch{}},i=ue("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,d=null,u=e.textarea,p=null,g=null,y=null,m=null,b=()=>{if(l)return Promise.resolve(l);if(d)return d;let k=zp().then(A=>(l=A.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:p??void 0,anchor:e.anchor,contextRow:i,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:D,emit:s}),l)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),d===k&&(d=null),null));return d=k,k},x=()=>{ty().then(k=>{let A=k.mountInlineComposer({textarea:e.textarea,renderToken:I=>ga(I,{render:t.renderMentionToken}),onMentionRemoved:I=>l?.untrackMention(I)});p=A.input,g=A.destroy;let W=u;W.replaceWith(A.element),u=A.element,m={next:A.element,prev:W},y?.(A.element,W),l?l.rebindComposer(A.input):d&&d.then(I=>I?.rebindComposer(A.input))}).catch(k=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",k)})};t.display==="inline"&&x();let T=[],L=new Map;for(let k of n){if(!k.showButton)continue;let A=ey({config:{...t,buttonIconName:k.buttonIconName,buttonTooltipText:k.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(W=>W?.openMenu(k.trigger))}});T.push(A),L.set(k.trigger,A.button)}let D=(k,A,W)=>{let I=L.get(A);I&&(I.setAttribute("aria-expanded",k?"true":"false"),k?I.setAttribute("aria-controls",W):I.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(k=>k.wrapper),contextRow:i,handleInput:k=>{if(l){l.handleInput();return}if(!Kh(k))return;let A=u,W=A.selectionStart??0;Vh(A.value,W,n)&&b().then(I=>I?.handleInput())},handleKeydown:k=>{if(l?.isMenuOpen())return l.handleKeydown(k);if(k.key==="Backspace"&&l?.hasMentions()&&!m){let A=u,W=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||W)&&l.removeLastChip())return k.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async k=>r(k)?(l??await b())?.dispatchInlineCommand(k)??null:null,clear:()=>l?.clear(),prefetch:()=>{zp().catch(()=>{})},onComposerSwap:k=>{y=k,m&&k(m.next,m.prev)},destroy:()=>{l?.destroy(),g?.();for(let k of T)k.wrapper.remove();i.remove()}}}var oy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fs(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];oy(s)&&oy(r)?n[o]=Fs(s,r):n[o]=r}return n}var jn="min(440px, calc(100vw - 24px))",Up="440px",$T={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:jn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",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",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)"},Qe={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",tooltip:{delayMs:200,skipDelayMs:300},launcher:$T,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"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},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 ry(e,t){if(!(!e&&!t))return e?t?Fs(e,t):e:t}function fa(e){return e?{...Qe,...e,theme:ry(Qe.theme,e.theme),darkTheme:ry(Qe.darkTheme,e.darkTheme),launcher:{...Qe.launcher,...e.launcher,dock:{...Qe.launcher?.dock,...e.launcher?.dock},clearChat:{...Qe.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...Qe.tooltip,...e.tooltip},copy:{...Qe.copy,...e.copy},sendButton:{...Qe.sendButton,...e.sendButton},statusIndicator:{...Qe.statusIndicator,...e.statusIndicator},voiceRecognition:{...Qe.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=Qe.features?.artifacts,n=e.features?.artifacts,o=Qe.features?.scrollToBottom,r=e.features?.scrollToBottom,s=Qe.features?.scrollBehavior,i=e.features?.scrollBehavior,l=Qe.features?.streamAnimation,d=e.features?.streamAnimation,u=Qe.features?.askUserQuestion,p=e.features?.askUserQuestion,g=Qe.features?.history,y=e.features?.history,m=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},x=s===void 0&&i===void 0?void 0:{...s,...i},T=l===void 0&&d===void 0?void 0:{...l,...d},L=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},D=g===void 0&&y===void 0?void 0:{...g,...y,copy:{...g?.copy,...y?.copy}};return{...Qe.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...x!==void 0?{scrollBehavior:x}:{},...m!==void 0?{artifacts:m}:{},...T!==void 0?{streamAnimation:T}:{},...L!==void 0?{askUserQuestion:L}:{},...D!==void 0?{history:D}:{}}})(),suggestionChips:e.suggestionChips??Qe.suggestionChips,suggestionChipsConfig:{...Qe.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Qe.layout,...e.layout,header:{...Qe.layout?.header,...e.layout?.header},messages:{...Qe.layout?.messages,...e.layout?.messages,avatar:{...Qe.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...Qe.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...Qe.layout?.slots,...e.layout?.slots}},markdown:{...Qe.markdown,...e.markdown,options:{...Qe.markdown?.options,...e.markdown?.options}},messageActions:{...Qe.messageActions,...e.messageActions}}:Qe}var Xl="16px",Ql="transparent",sy={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"}},iy={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"}},ay={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:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:jn,maxWidth:Up,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Xl,canvasBackground:Ql},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},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 dn(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."))?dn(e,o):o}function Vp(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let d=dn(e,i);d!==void 0&&(t[l]={path:l,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 i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ly(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 cy(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]=cy(s,r):n[o]=r}return n}function jT(e,t){return t?cy(e,t):e}function Zl(e,t={}){let n={palette:sy,semantic:iy,components:ay},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:jT(n.components,e?.components)};if(t.validate!==!1){let r=ly(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}var qp=e=>e.trim()==="0"?"0px":e;function Kp(e){let t=Vp(e),n={};for(let[M,Z]of Object.entries(t)){let de=M.replace(/\./g,"-");n[`--persona-${de}`]=Z.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-surface"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-primary"];let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],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"]??Xl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ql,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"];let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??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"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],n["--persona-header-control-size"]=n["--persona-components-header-controlSize"]??"32px",n["--persona-header-control-icon-size"]=n["--persona-components-header-controlIconSize"]??"20px";let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[M,Z]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let de=n[`--persona-components-history-overlay-${M}`];de&&(n[`--persona-history-overlay-${Z}`]=de)}for(let[M,Z]of[["background","bg"],["borderRadius","radius"]]){let de=n[`--persona-components-history-menu-${M}`];de&&(n[`--persona-history-menu-${Z}`]=de)}let g=e.components?.history?.motion;if(g){let M=Ce=>{if(Ce===void 0)return;let fe=String(Ce).trim();return/^\d+(\.\d+)?$/.test(fe)?`${fe}ms`:fe},Z=M(g.enterDurationMs);Z!==void 0&&(n["--persona-history-enter-ms"]=Z);let de=M(g.exitDurationMs);de!==void 0&&(n["--persona-history-exit-ms"]=de),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let M of["scrim","shadow"]){let Z=n[`--persona-components-history-confirm-${M}`];Z&&(n[`--persona-history-confirm-${M}`]=Z)}for(let[M,Z]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let de=n[`--persona-components-tooltip-${M}`];de&&(n[`--persona-tooltip-${Z}`]=de)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[M,Z]of[["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let de=n[`--persona-components-messageActions-${M}`];de&&(n[`--persona-message-action-${Z}`]=de)}n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let m=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],x=(!m||m==="transparent"||m==="none")&&(!b||b==="none"),T=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=x&&T==="1.5rem"?"1.5rem 0":T,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 L=n["--persona-components-markdown-heading-h1-fontSize"];L&&(n["--persona-md-h1-size"]=L);let D=n["--persona-components-markdown-heading-h1-fontWeight"];D&&(n["--persona-md-h1-weight"]=D);let k=n["--persona-components-markdown-heading-h2-fontSize"];k&&(n["--persona-md-h2-size"]=k);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let W=n["--persona-components-markdown-prose-fontFamily"];W&&W!=="inherit"&&(n["--persona-md-prose-font-family"]=W),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 I=e.components,R=I?.iconButton;R&&(R.background&&(n["--persona-icon-btn-bg"]=R.background),R.border&&(n["--persona-icon-btn-border"]=R.border),R.color&&(n["--persona-icon-btn-color"]=R.color),R.padding&&(n["--persona-icon-btn-padding"]=R.padding),R.borderRadius&&(n["--persona-icon-btn-radius"]=R.borderRadius),R.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=R.hoverBackground),R.hoverColor&&(n["--persona-icon-btn-hover-color"]=R.hoverColor),R.activeBackground&&(n["--persona-icon-btn-active-bg"]=R.activeBackground),R.activeBorder&&(n["--persona-icon-btn-active-border"]=R.activeBorder));let z=I?.labelButton;z&&(z.background&&(n["--persona-label-btn-bg"]=z.background),z.border&&(n["--persona-label-btn-border"]=z.border),z.color&&(n["--persona-label-btn-color"]=z.color),z.padding&&(n["--persona-label-btn-padding"]=z.padding),z.borderRadius&&(n["--persona-label-btn-radius"]=z.borderRadius),z.hoverBackground&&(n["--persona-label-btn-hover-bg"]=z.hoverBackground),z.fontSize&&(n["--persona-label-btn-font-size"]=z.fontSize),z.gap&&(n["--persona-label-btn-gap"]=z.gap));let q=I?.toggleGroup;q&&(q.gap&&(n["--persona-toggle-group-gap"]=q.gap),q.borderRadius&&(n["--persona-toggle-group-radius"]=q.borderRadius));let Q=I?.artifact;if(Q?.toolbar){let M=Q.toolbar;M.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=M.iconHoverColor),M.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=M.iconHoverBackground),M.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=M.iconPadding),M.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=M.iconBorderRadius),M.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=M.iconBorder),M.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=qp(M.toggleGroupGap)),M.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=M.toggleBorderRadius),M.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=qp(M.toggleGroupPadding)),M.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=M.toggleGroupBorder),M.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=M.toggleGroupBorderRadius),M.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=dn(e,M.toggleGroupBackground)??M.toggleGroupBackground),M.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=M.copyBackground),M.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=M.copyBorder),M.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=M.copyColor),M.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=qp(M.copyBorderRadius)),M.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=M.copyPadding),M.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=M.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??M.copyMenuBackground),M.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=M.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??M.copyMenuBorder),M.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=M.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??M.copyMenuShadow),M.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=M.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??M.copyMenuBorderRadius),M.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=M.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??M.copyMenuItemHoverBackground),M.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=M.iconBackground),M.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=M.toolbarBorder)}if(Q?.tab){let M=Q.tab;M.background&&(n["--persona-artifact-tab-bg"]=M.background),M.activeBackground&&(n["--persona-artifact-tab-active-bg"]=M.activeBackground),M.activeBorder&&(n["--persona-artifact-tab-active-border"]=M.activeBorder),M.borderRadius&&(n["--persona-artifact-tab-radius"]=M.borderRadius),M.textColor&&(n["--persona-artifact-tab-color"]=M.textColor),M.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=M.hoverBackground),M.listBackground&&(n["--persona-artifact-tab-list-bg"]=M.listBackground),M.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=M.listBorderColor),M.listPadding&&(n["--persona-artifact-tab-list-padding"]=M.listPadding)}if(Q?.pane){let M=Q.pane;if(M.toolbarBackground){let Z=dn(e,M.toolbarBackground)??M.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Z}}if(Q?.card){let M=Q.card;M.background&&(n["--persona-artifact-card-bg"]=M.background),M.border&&(n["--persona-artifact-card-border"]=M.border),M.borderRadius&&(n["--persona-artifact-card-radius"]=M.borderRadius),M.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=M.hoverBackground),M.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=M.hoverBorderColor)}if(Q?.inline){let M=Q.inline;M.background&&(n["--persona-artifact-inline-bg"]=dn(e,M.background)??M.background),M.border&&(n["--persona-artifact-inline-border"]=M.border),M.borderRadius&&(n["--persona-artifact-inline-radius"]=M.borderRadius),M.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=dn(e,M.chromeBackground)??M.chromeBackground),M.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=dn(e,M.chromeBorder)??M.chromeBorder),M.titleColor&&(n["--persona-artifact-inline-title-color"]=dn(e,M.titleColor)??M.titleColor),M.mutedColor&&(n["--persona-artifact-inline-muted-color"]=dn(e,M.mutedColor)??M.mutedColor),M.frameHeight&&(n["--persona-artifact-inline-frame-height"]=M.frameHeight)}let $=I?.code;$&&($.keywordColor&&(n["--persona-code-keyword-color"]=$.keywordColor),$.stringColor&&(n["--persona-code-string-color"]=$.stringColor),$.commentColor&&(n["--persona-code-comment-color"]=$.commentColor),$.numberColor&&(n["--persona-code-number-color"]=$.numberColor),$.tagColor&&(n["--persona-code-tag-color"]=$.tagColor),$.attrColor&&(n["--persona-code-attr-color"]=$.attrColor),$.propertyColor&&(n["--persona-code-property-color"]=$.propertyColor),$.lineNumberColor&&(n["--persona-code-line-number-color"]=$.lineNumberColor),$.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=$.gutterBorderColor),$.background&&(n["--persona-code-bg"]=dn(e,$.background)??$.background));let J=n["--persona-surface"],pe=n["--persona-container"],we=n["--persona-palette-colors-gray-100"]??"#f3f4f6",ve=n["--persona-palette-colors-gray-200"]??"#e5e7eb",he=n["--persona-palette-colors-gray-300"]??"#d1d5db",ne=!pe||pe===J,ae=ne?we:pe,ie=ne?ve:pe;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??ae,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ie,ne&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??he),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??ae,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??ae,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??ae,n}var zT={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 UT={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"}}},qT={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},dy=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ec=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",VT=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":ec()},Gp=e=>VT(e),KT=e=>Zl(e),GT=e=>{let t=Fs(qT,e??{})??{};return Zl({...t,palette:{...t.palette,colors:{...UT.colors,...t.palette?.colors}}},{validate:!1})},Kr=e=>{let t=Gp(e),n=dy(e?.theme),o=dy(e?.darkTheme);return t==="dark"?GT(Fs(n??{},o??{})):KT(n)},YT=e=>Kp(e),$s=(e,t)=>{let n=Kr(t),o=YT(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Gp(t))},ma=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(ec())});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(ec());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 rr=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var py=null;var Yp=()=>{if(py!==null)return py;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},JT="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",tc=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},nc=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return tc("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(tc("unsupported",e),null):(n==="space"&&(o.key=" "),o)},XT=e=>JT.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),uy=(e,t)=>{let n=nc(e);if(!n)return"";let o=Yp(),r=XT(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},oc=e=>uy(e,!1),ha=e=>uy(e,!0),QT=(e,t)=>t.key?.toLowerCase()===e.key&&(Yp()?t.metaKey:t.ctrlKey)===e.mod&&!(Yp()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,ZT=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},gy=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(QT(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&ZT(i))){s.preventDefault();try{l.run(s)}catch(d){tc(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let i=nc(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,d=t.get(l);return d?(tc(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",ha(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};function lo(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function fy(e){let t=lo(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function rc(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,
|
|
30
|
-
`);for(let
|
|
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=`
|
|
28
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Gr(e){let t=fy(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 sr(e){switch(Gr(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=fy(e.path);return t?t.toUpperCase():"File"}}}function sc(e){let t=e.markdown??"";return e.file?{filename:lo(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:rc(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function ic(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Jp="http://www.w3.org/2000/svg";function my(e){let t=document.createElementNS(Jp,"svg");t.setAttribute("class",Fn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Jp,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Jp,"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 ir=(e,t,n)=>{let o=n;for(let r of t){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function hy(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)),ir(e,t,0)}var Xp="persona-artifact-status-label",yy="persona-artifact-status-detail",by="data-artifact-status-label",Qp=new Map,vy=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function js(e){e&&Qp.delete(e)}function eE(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?sr(t):e.artifactType==="component"?"Component":"Document"}function zs(e,t,n){let o=eE(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=Qp.get(i);e.status!=="complete"&&l===void 0&&(l=vy(),Qp.set(i,l));let d=l===void 0?0:Math.max(0,vy()-l),u=e.artifactType==="component",p=!u&&typeof e.markdown=="string"?e.markdown:"",g=u?0:p.length,y=u||p===""?0:p.split(`
|
|
29
|
+
`).length,m=e.artifactType==="markdown"?e.file:void 0,b={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:m,chars:g,lines:y,elapsedMs:d,content:()=>u?"":p,surface:n};try{let x=s(b);return typeof x=="string"?{label:x}:x&&typeof x=="object"&&typeof x.label=="string"?{label:x.label,detail:typeof x.detail=="string"?x.detail:void 0}:{label:r}}catch{return{label:r}}}function tE(e){e.className=Xp,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 Yr(e,t,n){let o=e.querySelector(`:scope > .${Xp}`);o||(o=v("span",Xp),e.appendChild(o)),o.getAttribute(by)!==t.label&&(tE(o),hy(o,t.label,n),o.setAttribute(by,t.label));let r=e.querySelector(`:scope > .${yy}`),s=t.detail;s?(r||(r=v("span",yy),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var nE={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"},oE=15e4,ac={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 rE(e,t){let n=(e||"").trim().toLowerCase();if(n&&ac[n])return ac[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(ac[r])return ac[r]}}return null}function lc(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let d=l.re.exec(e);if(d&&d.index===o&&d[0].length>0){s(o);let u=l.map?l.map(d[0]):l.type;n.push({type:u,value:d[0]}),o+=d[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}var sE=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"]),iE=[{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=>sE.has(e)?"keyword":"plain"}];function Cy(e){return lc(e,iE)}var aE=[{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 lE(e){let t=lc(e,aE);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 cE=[{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 wy(e){let t=lc(e,cE),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 i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.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 dE=[{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 pE(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,d=e.slice(r,l);for(let p of lc(d,dE))t.push(p);r=l;let u=/^<\s*(script|style)\b/i.exec(d);if(u&&!/\/>\s*$/.test(d)){let p=u[1].toLowerCase(),y=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),m=y?r+y.index:o,b=e.slice(r,m),x=p==="script"?Cy(b):wy(b);for(let T of x)t.push(T);r=m}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function uE(e,t){switch(t){case"html":return pE(e);case"css":return wy(e);case"js":return Cy(e);case"json":return lE(e)}}function gE(e){let t=Km(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=nE[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
|
|
30
|
+
`);for(let i=0;i<s.length;i+=1)i>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
|
|
31
|
+
`)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function xy(e,t,n){let o=e.length<=oE?rE(t,n):null,r=o?uE(e,o):[{type:"plain",value:e}];return gE(r)}function Us(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Ns)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of t){if(b.dividerBefore){let L=document.createElement("hr");l.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",b.id),b.destructive&&x.setAttribute("data-destructive",""),b.icon){let L=ce(b.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let T=document.createElement("span");T.textContent=b.label,x.appendChild(T),x.addEventListener("click",L=>{L.stopPropagation(),g(),n(b.id)}),l.appendChild(x)}let d=null;function u(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function p(){let b=l.classList.contains("persona-hidden");u(),l.classList.remove("persona-hidden"),b&&i?.(!0),requestAnimationFrame(()=>{let x=T=>{!l.contains(T.target)&&!o.contains(T.target)&&g()};document.addEventListener("click",x,!0),d=()=>document.removeEventListener("click",x,!0)})}function g(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&i?.(!1)}function y(){l.classList.contains("persona-hidden")?p():g()}function m(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:g,toggle:y,destroy:m}}function st(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=e,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let u=ce(t,o??16,"currentColor",r??2);if(u&&d.appendChild(u),i&&d.addEventListener("click",i),l)for(let[p,g]of Object.entries(l))d.setAttribute(p,g);return d}function ar(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:d}=e,u="persona-label-btn";o!=="default"&&(u+=" persona-label-btn--"+o),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=v("button",u);if(p.type="button",p.setAttribute("aria-label",n),t){let y=ce(t,s??14,"currentColor",2);y&&p.appendChild(y)}let g=v("span");if(g.textContent=n,p.appendChild(g),l&&p.addEventListener("click",l),d)for(let[y,m]of Object.entries(d))p.setAttribute(y,m);return p}function lr(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function d(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let g;p.icon?g=st({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,d(),o(p.id)}}):(g=v("button","persona-icon-btn"+(p.className?" "+p.className:"")),g.type="button",g.setAttribute("aria-label",p.label),g.title=p.label,g.textContent=p.label,g.addEventListener("click",()=>{i=p.id,d(),o(p.id)})),g.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:g}),s.appendChild(g)}function u(p){i=p,d()}return{element:s,setSelected:u}}function Zp(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:d="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:g,className:y,primaryClassName:m,chevronClassName:b}=e,x=v("div","persona-split-btn"+(y?" "+y:"")),T={label:t,className:"persona-split-btn-primary"+(m?" "+m:""),onClick:l},L=r&&n?st({...T,icon:n,size:o??14}):ar({...T,icon:n,iconSize:o??14}),D=st({icon:"chevron-down",label:p,size:g??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});x.append(L,D);let k=null,A=()=>{if(k)return k;let W=(typeof u=="function"?u():u)??void 0;return k=Us({items:s,onSelect:i,anchor:x,position:d,portal:W,onOpenChange:I=>{D.setAttribute("aria-expanded",I?"true":"false")}}),W||x.appendChild(k.element),k};return x.isConnected?A():requestAnimationFrame(()=>{k||A()}),D.addEventListener("click",W=>{W.stopPropagation(),A().toggle()}),{element:x,primaryButton:L,chevronButton:D,openMenu:()=>A().show(),closeMenu:()=>k?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{k?.destroy(),x.remove()}}}function eu(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:d}=e,u=v("div","persona-combo-btn"+(l?" "+l:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=v("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let g=ce(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",u.appendChild(g)),d&&(u.style.borderRadius=d.borderRadius??"10px",u.style.padding=d.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=d.background??"",u.style.borderColor=d.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let y=Us({items:o,onSelect:b=>{u.setAttribute("aria-expanded","false"),r(b)},anchor:u,position:s,portal:i});i||u.appendChild(y.element);let m=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",b=>{if(b.stopPropagation(),m())return;let x=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),y.toggle()}),u.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u.click())}),{element:u,setLabel:b=>{p.textContent=b,u.setAttribute("aria-label",b)},open:()=>{u.setAttribute("aria-expanded","true"),y.show()},close:()=>{u.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let b=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",b?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),u.remove()}}}var cc="persona-artifact-custom-action-btn";function qs(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 "+cc+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+cc+(n?" persona-artifact-doc-icon-btn":"");o=v("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=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=ar({icon:e.icon,label:e.label,className:cc+(n?" persona-artifact-doc-copy-btn":"")}):o=st({icon:e.icon,label:e.label,className:cc+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function ya(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 Sy(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?lo(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",i=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",d=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,u=n?sr(n):l==="component"?"Component":"Document",p=document.createElement("div");p.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",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&p.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 y=document.createElement("div");y.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let x=t?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},L=zs(T,x,"card");Yr(b,L,x)}else s&&js(s),b.textContent=u;if(y.append(m,b),p.append(g,y),i==="complete"){let x=t?.config?.features?.artifacts?.cardActions;if(x&&x.length>0){let L={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let D of x)try{if(D.visible===void 0||D.visible(L)){let k=qs(D);k.setAttribute("data-artifact-custom-action",D.id),k.className=`${k.className} persona-flex-shrink-0`,p.append(k)}}catch{}}let T=ar({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),p.append(T)}return p}var dc=(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",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>Sy(e,t)});if(l)return l}return Sy(e,t)};var cr=new WeakMap;function tu(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=cr.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function ky(e){return cr.has(e)}function fE(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 i=e.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...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 Ay(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?lo(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?sr(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function mE(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 Ty=180,hE=240,yE=.8,bE=300,vE=500,CE="cubic-bezier(0.2, 0, 0, 1)",Ey=240,wE=.35;function xE(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 i=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:Ty,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of i)L.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let d=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!d||Math.abs(d-t)<1){l(),r();return}let u=Math.abs(t-d),p=Math.round(Math.min(vE,Math.max(bE,hE+u*yE))),g=Math.round(p*wE),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,m=y?y.animate([{opacity:0},{opacity:1}],{duration:Ey,delay:g,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:p,easing:CE});e.style.height=`${d}px`;let x=!1,T=()=>{x||(x=!0,l(),r())};Promise.allSettled([b.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(p,g+Ey)+120)},Ty)}function SE(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 ba="--persona-artifact-inline-body-height";function AE(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,i=t?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:t?.followOutput!==!1,u,p,g=t?.fadeMask;g===!0?(u=!0,p=!0):g===!1?(u=!1,p=!1):g&&typeof g=="object"?(u=g.top===!0,p=g.bottom===!0):l==="clip"?(u=!1,p=!0):(u=!0,p=!0);let y=t?.transition==="none"?"none":"auto",m=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:u,fadeBottom:p,transition:y,completeDisplay:m}}function My(e,t){let n=fE(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=SE(o),d=o?.inlineActions??[],u=AE(o),p=u.completeDisplay==="card",g=null,y=n,m=v("div","persona-artifact-inline persona-w-full persona-max-w-full");m.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&m.setAttribute("data-artifact-inline",n.id);let b=M=>dc(mE(M),t),x=null,T=M=>{x?.destroy(),x=null,m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(ba),m.replaceChildren(b(M)),cr.set(m,Z=>{m.replaceChildren(b(Z))})};if(p&&n.status==="complete")return T(n),m;let L=pc(n,{config:t.config,bodyLayout:u,resolveViewMode:()=>g??u.viewMode});x=L;let D=v("div","persona-artifact-inline-body");D.appendChild(L.el);let k=M=>{let Z=M.status!=="complete",de=Z?u.streamingHeight:u.completeHeight,Ce=typeof de=="number";Ce?m.style.setProperty(ba,`${de}px`):m.style.removeProperty(ba);let fe=!!L.el.querySelector(".persona-code-pre"),xe=!!L.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");D.classList.toggle("persona-artifact-content-flush",fe),D.classList.toggle("persona-artifact-inline-body--sized",Ce&&xe),D.classList.toggle("persona-artifact-inline-body--cap",!Z&&!xe&&typeof u.completeHeight=="number")},A=n.status,W=(M,Z)=>{A!=="complete"&&M.status==="complete"?(typeof u.completeHeight=="number"?m.style.setProperty(ba,`${u.completeHeight}px`):m.style.removeProperty(ba),Ly(D,Z?.suppressTransition?"none":u.transition,M.id,()=>{L.update(M),k(M)})):L.update(M),k(M),A=M.status};k(n);let I=u.overflow==="clip"&&i&&!!n.id;if(I&&(D.setAttribute("data-expand-artifact-inline",n.id),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.classList.add("persona-cursor-pointer"),D.setAttribute("aria-label",`Open ${Ay(n).title} in panel`)),!r)return m.appendChild(D),cr.set(m,W),m;let R=v("div","persona-artifact-inline-chrome");R.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let z=v("div","persona-artifact-inline-chrome-lead"),q=v("span","persona-flex persona-items-center persona-flex-shrink-0"),Q=ce("file-text",16,"currentColor",2);Q&&q.appendChild(Q);let $=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),J=v("span","persona-artifact-inline-type");z.append(q,$,J);let pe=v("div","persona-artifact-inline-chrome-actions"),we=v("span","persona-flex persona-items-center persona-gap-1"),ve=()=>g??u.viewMode,he=l?lr({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:ve(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:M=>{let Z=M==="source"?"source":"rendered";Z!==ve()&&(g=Z,L.update(y),k(y))}}):null,ne=s?st({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-copy-artifact",n.id);let ae=i?st({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ae&&n.id&&ae.setAttribute("data-expand-artifact-inline",n.id),pe.appendChild(we),he&&pe.appendChild(he.element),ne&&pe.appendChild(ne),ae&&pe.appendChild(ae),R.append(z,pe),m.append(R,D);let ie=M=>{let{title:Z,typeLabel:de}=Ay(M);$.textContent=Z,$.title=Z,I&&D.setAttribute("aria-label",`Open ${Z} in panel`);let Ce=M.status!=="complete";if(Ce){J.classList.contains("persona-artifact-inline-status")||(J.className="persona-artifact-inline-status",J.removeAttribute("data-preserve-animation"),J.replaceChildren());let fe=zs(M,o,"inline-chrome");Yr(J,fe,o)}else js(M.id),J.className="persona-artifact-inline-type",J.removeAttribute("data-preserve-animation"),J.replaceChildren(),J.textContent=de;if(ne&&ne.classList.toggle("persona-hidden",Ce),he){let fe=M.artifactType==="markdown"?M.file:void 0,xe=!1;if(!Ce&&fe&&u.viewMode!=="source"){let Pe=Gr(fe);Pe==="markdown"?xe=!0:(Pe==="html"||Pe==="svg")&&(xe=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!xe),he.setSelected(ve())}if(we.replaceChildren(),!Ce&&d.length>0){let fe=ya(M);if(fe)for(let xe of d)try{if(xe.visible===void 0||xe.visible(fe)){let Pe=qs(xe,{documentChrome:!0});Pe.setAttribute("data-artifact-custom-action",xe.id),Pe.classList.add("persona-flex-shrink-0"),we.appendChild(Pe)}}catch{}}};return ie(n),cr.set(m,(M,Z)=>{if(p&&A!=="complete"&&M.status==="complete"){let de=m.isConnected?m.getBoundingClientRect().height:0;A="complete";let Ce=M,fe=!1,xe=Pe=>{Ce=Pe,fe=!0};cr.set(m,xe),xE(m,de,{swap:()=>{T(Ce),fe=!1,cr.set(m,xe)},onSettled:()=>{fe?T(Ce):cr.set(m,Pe=>{m.replaceChildren(b(Pe))})}});return}(M.status!=="complete"||M.id!==y.id)&&(g=null),y=M,W(M,Z),ie(M)}),m}var Py=(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",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>My(e,t)});if(l)return l}return My(e,t)};var nu=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)})}},co=new nu;co.register("PersonaArtifactCard",dc,{bubbleChrome:!1});co.register("PersonaArtifactInline",Py,{bubbleChrome:!1});function va(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?rc(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var ou=!1;function TE(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ly(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"||ou||s){o();return}ou=!0;let i=TE(n);e.style.setProperty("view-transition-name",i);let l=()=>{ou=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var EE="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",ME="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function kE(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("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 PE(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 LE=220;function HE(){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 IE(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 RE(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(my());let s=null;return n.label!==!1&&(s=v("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 WE(e,t,n,o,r,s){let i=null,l=0,d=!1,u=new Set,p=()=>{u.forEach(k=>clearTimeout(k)),u.clear()},g=(k,A)=>{let W=setTimeout(()=>{u.delete(W),k()},A);u.add(W)},y=()=>{i&&i.parentElement&&i.remove(),i=null},m=()=>{if(i||d)return;let k=RE(r,s,o);i=k.el,e.appendChild(i),l=Date.now(),o.label!==!1&&g(k.revealLabel,o.labelDelayMs)},b=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),g(y,LE))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",D)},T=()=>{if(d||(d=!0,x(),p(),!i))return;let k=Math.max(0,o.minVisibleMs-(Date.now()-l));k>0?g(b,k):b()};function L(k){if(n===null)return;let A=k.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||k.source===t.contentWindow&&T()}function D(){let k=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};k(()=>k(()=>T()))}return g(m,o.delayMs),g(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",D),()=>{d=!0,p(),x(),y()}}function pc(e,t){let{config:n}=t,o=t.registry??co,r=t.bodyLayout,s=n.markdown?Ls(n.markdown):null,i=Vi(n.sanitize),l=e,d=!1,u=ne=>{let ae=Lo()!==null;s&&!ae&&!d&&(d=!0,qi(()=>he(l)));let ie=s?s(ne):Ho(ne);return s&&ae&&i?i(ie):ie},p=v("div","persona-artifact-preview-body"),g=null,y=null,m=null,b=()=>{m&&(m(),m=null),g=null,y=null},x=null,T=null,L=null,D=!1,k=()=>{x=null,T=null,L=null,D=!1},A=null,W=null,I=()=>{A=null,W=null},R=40,z=0,q=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),Q=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=R,$=ne=>{if(!r)return;let ae=ne.scrollHeight-ne.clientHeight>1,ie=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ae&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ae&&ie>1)},J=ne=>{z||(z=q(()=>{z=0,ne.scrollTop=ne.scrollHeight,$(ne)}))},pe=(ne,ae,ie,M)=>{let Z=!!r,de=ie.id+"|"+(Z?"w":"p");if(!x||L!==de||x.parentElement!==p){b(),I(),p.replaceChildren();let xe=v("pre",EE+" persona-code-pre"),Pe=v("code","persona-code");if(xe.appendChild(Pe),Z){let Le=v("div","persona-artifact-source-window");if(Le.appendChild(xe),p.appendChild(Le),!(r?.overflow==="clip")&&typeof Le.addEventListener=="function"){let Be=()=>Le.scrollHeight-Le.clientHeight>1;Le.addEventListener("scroll",()=>{Q(Le)&&(D=!1),$(Le)},{passive:!0}),Le.addEventListener("wheel",Re=>{Be()&&Re.deltaY<0&&(D=!0)},{passive:!0}),Le.addEventListener("touchmove",()=>{Be()&&(D=!0)},{passive:!0})}x=Le}else p.appendChild(xe),x=xe;T=Pe,L=de}let Ce=Z?x:null;Ce&&(Ce.classList.toggle("persona-artifact-source-window--fixed",M),Ce.classList.toggle("persona-artifact-source-window--clip",M&&r?.overflow==="clip"));let fe=Ce?Q(Ce):!0;if(T.replaceChildren(xy(ne,ae?.language,ae?.path)),Ce){let xe=ie.status!=="complete";M&&xe&&r?.followOutput&&!D&&fe?J(Ce):xe||(D=!1),$(Ce)}},we=ne=>{b(),k(),I(),p.replaceChildren();let ae=v("div",ME);ae.innerHTML=u(ne),p.appendChild(ae)},ve=ne=>{let ae=ne.id,ie=n.features?.artifacts,M=zs(ne,ie,"status-body");if(A&&W===ae&&A.parentElement===p){let Ce=A.querySelector(".persona-artifact-status-view-text");Ce&&Yr(Ce,M,ie);return}b(),k(),p.replaceChildren();let Z=v("div","persona-artifact-status-view"),de=v("div","persona-artifact-status-view-text");Yr(de,M,ie),Z.appendChild(de),p.appendChild(Z),A=Z,W=ae},he=ne=>{l=ne;let ae=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",ie=ne.artifactType==="markdown"?ne.file:void 0,M=ne.status!=="complete";M||js(ne.id);let Z=M?r?.streamingHeight:r?.completeHeight,de=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&M){ve(ne);return}if(ie){let fe=rc(ne.markdown??""),xe=Gr(ie),Pe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!M&&ae==="rendered"&&Pe&&(xe==="html"||xe==="svg")){let Je=ne.id+"\0"+fe;if(g&&y===Je&&g.parentElement===p)return;k(),I(),b(),p.replaceChildren();let Be=n.features?.artifacts?.filePreview,Re=Be?.iframeSandbox??"allow-scripts";!Be?.dangerouslyAllowSameOrigin&&Re.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."),Re=Re.split(/\s+/).filter(Se=>Se&&Se!=="allow-same-origin").join(" "));let et=PE(Be?.loading),be=v("div","persona-artifact-frame"),_e=v("iframe","persona-artifact-iframe");_e.setAttribute("sandbox",Re),_e.setAttribute("data-artifact-id",ne.id);let gt=null;et.enabled&&et.injectReadySignal?(gt=HE(),_e.srcdoc=fe+IE(gt)):_e.srcdoc=fe,be.appendChild(_e),p.appendChild(be),et.enabled&&(m=WE(be,_e,gt,et,ne.id,n)),g=be,y=Je;return}if(b(),!M&&xe==="markdown"&&ae==="rendered"){we(fe);return}pe(fe,{language:ie.language,path:ie.path},ne,de);return}if(ne.artifactType==="markdown"){if(ae==="source"){b(),pe(ne.markdown??"",void 0,ne,de);return}we(ne.markdown??"");return}b(),k(),I(),p.replaceChildren();let Ce=ne.component?o.get(ne.component):void 0;if(Ce){let xe={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Pe=Ce(ne.props??{},xe);if(Pe){p.appendChild(Pe);return}}catch{}}p.appendChild(kE(ne))};return he(e),{el:p,update(ne){he(ne)},destroy(){b()}}}import{Idiomorph as BE}from"idiomorph";var uc=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;BE.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 i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var Hy=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ru={index:-1,draft:""};function Iy(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Ry(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 Wy(){return new Map}function By(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Oy(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Dy(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function _y(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 Ny(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function po(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Jr(e,t){return po(e)-e.scrollTop<=t}function Fy(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:u=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function $y(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 jy(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function su(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 zy(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ca={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},OE=["pre","code","a","script","style"],gc=e=>({type:e?.type??Ca.type,placeholder:e?.placeholder??Ca.placeholder,speed:e?.speed??Ca.speed,duration:e?.duration??Ca.duration,buffer:e?.buffer??Ca.buffer}),qy=[{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"}],wa=new Map;for(let e of qy)wa.set(e.name,e);var DE=e=>{wa.set(e.name,e)},_E=e=>{qy.some(t=>t.name===e)||wa.delete(e)},NE=()=>Array.from(wa.keys()),Vs=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:wa.get(e)??null,fc=(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},FE=(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},$E=(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},iu=/\s/,jE=(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},zE=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(iu.test(s[l])){let d=l;for(;d<s.length&&iu.test(s[d]);)d+=1;i.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=l;for(;u<s.length&&!iu.test(s[u]);)d.appendChild(FE(o,s[u],t,n.value)),n.value+=1,u+=1;i.appendChild(d),l=u}r.replaceChild(i,e)},UE=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?i.appendChild(o.createTextNode(d)):(i.appendChild($E(o,d,t,n.value)),n.value+=1));r.replaceChild(i,e)},xa=(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??OE).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=i.nextNode();for(;d;)jE(d,s)||l.push(d),d=i.nextNode();let u={value:o?.startIndex??0},p=t==="char"?zE:UE;for(let g of l)p(g,n,u);return r.innerHTML},mc=(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},Sa=(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},Uy=new WeakMap,qE=(e,t)=>{if(!e.styles)return;let n=Uy.get(t);if(n||(n=new Set,Uy.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)},au=new WeakMap,VE=(e,t)=>{if(!e.onAttach)return;let n=au.get(t);if(n||(n=new Map,au.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Vy=e=>{let t=au.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},hc=(e,t)=>{qE(e,t),VE(e,t)};function lu(e,t=Jt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Aa=0,dr=null;function cu(e=document){if(Aa++,Aa===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;dr={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,Aa=Math.max(0,Aa-1),Aa===0&&dr)){let n=e.body,o=e.defaultView??window;n.style.overflow=dr.originalOverflow,n.style.position=dr.originalPosition,n.style.top=dr.originalTop,n.style.width=dr.originalWidth,o.scrollTo(0,dr.scrollY),dr=null}}}var Ta={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},wt=e=>(e?.launcher?.mountMode??"floating")==="docked",pr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",Pn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ta.side,width:t?.width??Ta.width,animate:t?.animate??Ta.animate,reveal:t?.reveal??Ta.reveal,maxHeight:t?.maxHeight??Ta.maxHeight}};var du=e=>e==="followUp"?"follow-up":e,pu=(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"}},KE=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'}},Ky=new WeakSet,GE=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,YE=e=>{GE()||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"})})},uu=e=>{var D,k,A;let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:d,chipsConfig:u,session:p,getTextarea:g,eventTarget:y}=e,m=o==="followUp",b=t.behavior,x=()=>{if(p.isStreaming())return;let W={suggestion:{...t},surface:o,source:r,behavior:b},I=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:W,bubbles:!0,composed:!0,cancelable:!0}));if(m&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!I)return;for(let z of d)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let R=g();if(b==="fill"){R.value=t.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}R.value="",p.sendMessage(t.prompt)},T=()=>{let W=v("button",`persona-suggestion persona-suggestion--${s}`);if(W.type="button",W.disabled=i,W.dataset.suggestionId=t.id,W.dataset.emphasis=t.emphasis,W.dataset.behavior=b,s==="chip"&&(u?.fontFamily&&(W.style.fontFamily=KE(u.fontFamily)),u?.fontWeight&&(W.style.fontWeight=u.fontWeight),u?.paddingX&&(W.style.paddingLeft=u.paddingX,W.style.paddingRight=u.paddingX),u?.paddingY&&(W.style.paddingTop=u.paddingY,W.style.paddingBottom=u.paddingY)),t.icon){let R=ce(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),t.iconColor&&(R.style.color=t.iconColor),W.appendChild(R))}let I=v("span","persona-suggestion__copy");if(I.appendChild(ue("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&I.appendChild(ue("span",{className:"persona-suggestion__description",text:t.description})),W.appendChild(I),s!=="chip"){let R=ce("arrow-right",16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),W.appendChild(R))}return W.addEventListener("click",x),W},L=null;for(let W of d)if(W.renderSuggestion&&(L=W.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:T,select:x}),L))break;return L??(L=T()),(D=L.dataset).suggestionId||(D.suggestionId=t.id),(k=L.dataset).behavior||(k.behavior=b),(A=L.dataset).emphasis||(A.emphasis=t.emphasis),L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",i?"true":"false"),L},Ea=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){s();return}let g=getComputedStyle(e).direction==="rtl",y=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),m=4,b=y<=m,x=y>=p-m,T=g?!x:!b,L=g?!b:!x;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",L)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,g,y,m,b,x)=>{e.replaceChildren(),t.length=0,n.length=0;let T=x?.source??"config",L=x?.surface??(T==="config"?"starter":"followUp"),D=L==="followUp",k=x?.variant??"chip",A=x?.behavior??"send",W=x?.overflow??"wrap",I=x?.config??{},R=x?.plugins??[],z=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,q=D?"followUps":"starters";!Ky.has(I)&&I.debug===!0&&k!=="chip"&&I.suggestions?.[q]?.overflow!==void 0&&(Ky.add(I),console.info(`[persona] suggestions.${q}.overflow applies to the "chip" variant only; the "${k}" variant manages its own stacking.`));let Q=he=>he.map(pu).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??A})),$=Q(p??[]);R.forEach(he=>{he.transformSuggestions&&($=Q(he.transformSuggestions({suggestions:$.map(ne=>({...ne})),surface:L,source:T,config:I})))});let J=z===void 0?$:$.slice(0,z);if(!J.length){e.hidden=!0,o=null,s();return}if(!D&&(m??g.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=du(L),e.dataset.variant=k,e.dataset.overflow=W;let pe=document.createDocumentFragment(),we=g.isStreaming();J.forEach((he,ne)=>{let ae=uu({item:he,index:ne,surface:L,source:T,variant:k,streaming:we,config:I,plugins:R,chipsConfig:b,session:g,getTextarea:()=>y,eventTarget:e});pe.appendChild(ae),n.push(ae),[...ae instanceof HTMLButtonElement?[ae]:[],...Array.from(ae.querySelectorAll("button"))].forEach(M=>{t.includes(M)||(M.disabled=we,t.push(M))})}),e.appendChild(pe),i(),l();let ve=JSON.stringify({normalized:J,surface:L,variant:k,source:T});ve!==o&&(o=ve,YE(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:J.map(he=>({...he})),surface:L,source:T,variant:k},bubbles:!0,composed:!0})),D&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:J.map(he=>he.prompt)},bubbles:!0,composed:!0})))}}};var Ln={"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 JE="persona-header-control",XE="persona-header-control--glyph",QE="persona-header-control--sparse",ZE=20,eM={x:[1.4,1.05]},Gy="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",tM="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yc=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=eM[t]??[1,1.5],l=!o;e.classList.toggle(XE,l),e.classList.toggle(QE,l&&s!==1);let d=parseFloat(o??"")||ZE,u=ce(t,`${Math.round(d*s)}px`,"currentColor",i);u?(u.style.display="block",l||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},Xr=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=Gy,size:l,iconSize:d,color:u,backgroundColor:p,borderWidth:g,borderColor:y,borderRadius:m,paddingX:b,paddingY:x,hidden:T,extraClassName:L,attrs:D}=e,k=v("div",i),A=!!(g||y),W=ue("button",{className:Fn(JE,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!m&&"persona-rounded-full",L),attrs:{type:"button","aria-label":t,...D},style:{width:l,height:l,minWidth:l,minHeight:l,display:T?"none":void 0,color:u||pn.actionIconColor,backgroundColor:p,border:A?`${g||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:m,paddingLeft:b,paddingRight:b,paddingTop:x,paddingBottom:x}});return r?yc(W,r,{iconSize:d,iconText:s}):s&&(W.textContent=s),k.appendChild(W),Xt({anchor:W,trigger:k,text:()=>W.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:W,wrapper:k}},Ks=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Gy,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=Xr({ariaLabel:l,tooltip:d,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:p}},Gs=(e,t={})=>{let{wrapperClassName:n=tM,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",d=i.showTooltip??!0,{button:u,wrapper:p}=Xr({ariaLabel:l,tooltip:d,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var pn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},gu={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)"},nM={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)"},ur=e=>{let{config:t,showClose:n=!0}=e,o=ue("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:{minHeight:pn.minHeight,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",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,u=ue("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(!l)if(d){let W=parseFloat(s)||24,I=ce(d,W*.6,"currentColor",1);I?u.replaceChildren(I):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let W=v("img");W.src=t.launcher.iconUrl,W.alt="",W.className="persona-rounded-xl persona-object-cover",W.style.height=s,W.style.width=s,u.replaceChildren(W)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=ue("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:pn.titleColor,...gu}}),y=ue("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:pn.subtitleColor,...nM}});p.append(g,y),l?o.append(p):o.append(u,p);let m=r.clearChat??{},b=m.enabled??!0,x=m.placement??"inline",T=null,L=null;if(b){let I=Gs(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=I.button,L=I.wrapper,x==="top-right"&&(L.style.right="48px"),x==="inline"&&o.appendChild(L)}let D=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:A}=Ks(t,{showClose:n,wrapperClassName:D});return i!=="top-right"&&o.appendChild(A),{header:o,iconHolder:u,headerTitle:g,headerSubtitle:y,closeButton:k,closeButtonWrapper:A,clearChatButton:T,clearChatButtonWrapper:L}},Ys=(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 Yy=e=>{let t=ur({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 oM(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=Xr({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?oc(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=ha(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=Us({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var Jy=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=pn.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,u,p;if(d){let A=eu({label:i.title??"Chat Assistant",menuItems:d.menuItems,onSelect:W=>{let I=z=>{z===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:W}}))},R=d.onSelect(W);R instanceof Promise?R.then(I,()=>{}):I(R)},hover:d.hover,className:""});u=A.element,u.style.color=pn.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=pn.titleColor,Object.assign(p.style,gu),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let W=r.onTitleClick;u.addEventListener("click",I=>{I.target.closest("button")||W()}),u.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),W())})}let A=r?.titleRowHover;A&&(u.style.borderRadius=A.borderRadius??"10px",u.style.padding=A.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=A.background??"",u.style.borderColor=A.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}l.appendChild(u);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:m}=Ks(t,{showClose:n,wrapperClassName:g});o&&y.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||oM(b,r?.trailingActions,r?.onAction??s);let x=i.clearChat??{},T=null,L=null;if(x.enabled??!0){let A=x.placement??"inline",W=Gs(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});T=W.button,L=W.wrapper,A==="top-right"?L.style.right="48px":b.appendChild(L)}b.appendChild(m),l.appendChild(b);let D=v("div");D.style.display="none";let k=v("span");return k.style.display="none",{header:l,iconHolder:D,headerTitle:p,headerSubtitle:k,closeButton:y,closeButtonWrapper:m,clearChatButton:T,clearChatButtonWrapper:L}},fu={default:Yy,minimal:Jy},Xy=e=>fu[e]??fu.default,Ma=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let d=v("span"),u=v("span"),p=v("button");p.style.display="none";let g=v("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:d,headerSubtitle:u,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Xy(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 bc=e=>{let t=v("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let d=t.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let u=d.getComputedStyle(t).lineHeight;if(!u||!u.trim().endsWith("px"))return o;let p=parseFloat(u);return Number.isFinite(p)&&p>0?p:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let i=()=>{let d=t.style.maxHeight;if(d!==s){let p=parseFloat(d);if(Number.isFinite(p)&&p>0)return p}let u=n*r();return s=`${u}px`,t.style.maxHeight=s,u},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,i());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},vc=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,g=t.size??"40px",y=t.backgroundColor,m=t.textColor,b=v("div","persona-send-button-wrapper"),x=ue("button",{className:Fn("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&&!y&&"persona-bg-persona-primary",!n&&!m&&"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?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&y||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}}),T=null,L=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round((parseFloat(g)||24)*.5),W=t.iconStrokeWidth??2,I=m?.trim()||"currentColor";r?(T=ce(r,A,I,W),T?x.appendChild(T):x.textContent=o):x.textContent=o,L=ce(s,A,I,W)}else x.textContent=d;x.setAttribute("aria-label",i),b.appendChild(x),Xt({anchor:x,trigger:b,text:()=>x.getAttribute("aria-label")??"",enabled:p});let D="send";return{button:x,wrapper:b,setMode:A=>{if(A===D)return;D=A;let W=A==="stop"?l:i;if(x.setAttribute("aria-label",W),n){if(T&&L){let I=A==="stop"?L:T;x.replaceChildren(I)}}else x.textContent=A==="stop"?u:d}}},Cc=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 i=e?.sendButton?.size??"40px",l=t.iconName??"mic",d=t.iconSize??i,u=parseFloat(d)||24,p=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,y=v("div","persona-send-button-wrapper"),m=ue("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:g||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=ce(l,u,g||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",y.appendChild(m);let T=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return Xt({anchor:m,trigger:y,text:()=>m.getAttribute("aria-label")??T,enabled:L}),{button:m,wrapper:y}},wc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=v("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=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Bo).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,d=Math.round(l*.6),u=v("div","persona-send-button-wrapper"),p=ue("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:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),g=ce(s,d,"currentColor",1.5);g?p.appendChild(g):p.textContent="\u{1F4CE}",p.addEventListener("click",m=>{m.preventDefault(),r.click()}),u.appendChild(p);let y=t.buttonTooltipText??"Attach file";return Xt({anchor:p,trigger:u,text:()=>p.getAttribute("aria-label")??y}),{button:p,wrapper:u,input:r,previewsContainer:o}},xc=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("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 i=v("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},Sc=()=>ue("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Js=e=>{let{config:t}=e,n=ue("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=Sc(),r=ue("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:i}=bc(t);i();let l=vc(t),d=Cc(t),u=wc(t),p=xc(t);u&&(u.previewsContainer.style.gap="8px",r.append(u.previewsContainer,u.input)),r.append(s);let g=ue("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return u&&y.append(u.wrapper),d&&m.append(d.wrapper),m.append(l.wrapper),g.append(y,m),r.append(g),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:g,leftActions:y,rightActions:m,setSendButtonMode:l.setMode}};var Qy=()=>{let e=ue("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=ce("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=ce("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Ac=e=>{let{config:t}=e,n=ue("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Sc(),r=xc(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=bc(t);s.style.maxHeight="100px",i();let l=vc(t),d=Cc(t),u=wc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=ue("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");u&&g.append(u.wrapper);let y=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&y.append(d.wrapper),y.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),u&&p.append(u.input),p.append(g,s,y),u&&n.append(u.previewsContainer),n.append(o,p,r);let m=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:y,setSendButtonMode:l.setMode}};var rM=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}},sM=(e,t)=>{if(!e)return null;let n=rM(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},iM=(e,t)=>{let n=v("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},aM=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},mu=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(":"))},hu=320,nb=320,lM=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),cM=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),dM=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),pM=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),uM=e=>{if(!e||e.length===0)return null;let t=ue("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ue("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ce(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(ue("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},gM=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ga(o.ref,{readonly:!0,render:t}))}return n},Zy="\uE000",eb="\uE001",fM=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Zy}${r}:${y}${eb}`,i=t.map((y,m)=>y.kind==="text"?y.text:s(m)).join(""),l=n(i);if(!t.every((y,m)=>y.kind==="text"||l.includes(s(m)))){e.replaceChildren(gM(t,o));return}e.innerHTML=l;let u=new RegExp(`${Zy}${r}:(\\d+)${eb}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let y=p.nextNode();y;y=p.nextNode())g.push(y);for(let y of g){let m=y;for(let b=u.exec(m.data);b;b=u.exec(m.data)){let x=t[Number(b[1])],T=m.splitText(b.index);T.data=T.data.slice(b[0].length),x?.kind==="mention"&&T.parentNode?.insertBefore(ga(x.ref,{readonly:!0,render:o}),T),m=T}}},mM=(e,t,n)=>{if(e.length===0)return null;try{let o=v("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,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let u=v("img");u.alt=l.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${hu}px`,u.style.maxHeight=`${nb}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),aM(l.image)?(u.src=l.image,o.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},hM=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!mu(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${hu}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},yM=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!mu(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${hu}px`,r.style.maxHeight=`${nb}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}},bM=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!mu(o.data))return;let r=v("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}},Xs=()=>{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},ob=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Xs};if(t){let r=t(o);if(r!==null)return r}return Xs()},vM=(e,t)=>{let n=v("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=v("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},tb=(e,t,n="div")=>{let o=v(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},ka=(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},rb=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,i=t.showReadAloud??!1;if(!o&&!r&&!s&&!i){let b=v("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}let l=t.visibility??"hover",d=t.align??"right",u=t.layout??"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],y=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let m=(b,x,T)=>{let L=st({icon:b,label:x,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return o&&y.appendChild(m("copy","Copy message","copy")),i&&y.appendChild(m("volume-2","Read aloud","read-aloud")),r&&y.appendChild(m("thumbs-up","Upvote","upvote")),s&&y.appendChild(m("thumbs-down","Downvote","downvote")),y},Pa=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",d=i.avatar,u=i.timestamp,p=d?.show??!1,g=u?.show??!1,y=d?.position??"left",m=u?.position??"below",b=ka(e.role,l),x=v("div",b.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=lM(e),L=e.content?.trim()??"",k=T.length>0&&L===Ws,A=gc(s?.widgetConfig?.features?.streamAnimation),W=s?.widgetConfig?.features?.streamAnimation?.plugins,I=e.role==="assistant"&&A.type!=="none"?Vs(A.type,W):null,R=e.role==="assistant"&&I?.isAnimating?.(e)===!0,z=e.role==="assistant"&&I!==null&&(!!e.streaming||R);z&&I?.bubbleClass&&x.classList.add(I.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),z&&I&&(I.containerClass&&q.classList.add(I.containerClass),q.style.setProperty("--persona-stream-step",`${A.speed}ms`),q.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let Q=z?fc(e.content??"",A.buffer,I,e,!!e.streaming):e.content??"",$=()=>{let Z=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&I?.wrap==="char"?xa(Z,"char",e.id,{skipTags:I.skipTags}):z&&I?.wrap==="word"?xa(Z,"word",e.id,{skipTags:I.skipTags}):Z},J=null;if(k?(J=document.createElement("div"),J.innerHTML=$(),J.style.display="none",q.appendChild(J)):e.contentSegments?.length?fM(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=$(),z&&I?.useCaret&&!k&&L){let Z=mc(),de=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ce=de[de.length-1];if(Ce?.parentNode)Ce.parentNode.insertBefore(Z,Ce.nextSibling);else{let fe=q.lastElementChild;fe?fe.appendChild(Z):q.appendChild(Z)}}if(g&&m==="inline"&&e.createdAt){let Z=tb(e,u,"span");Z.classList.add("persona-timestamp-inline");let de=q.lastElementChild;de?de.appendChild(Z):q.appendChild(Z)}if(T.length>0){let Z=mM(T,!k&&!!L,()=>{k&&J&&(J.style.display="")});Z?x.appendChild(Z):k&&J&&(J.style.display="")}let pe=cM(e);if(pe.length>0){let Z=hM(pe);Z&&x.appendChild(Z)}let we=dM(e);if(we.length>0){let Z=yM(we);Z&&x.appendChild(Z)}let ve=pM(e);if(ve.length>0){let Z=bM(ve);Z&&x.appendChild(Z)}let he=e.contentSegments?.length?null:uM(e.contextMentions);if(he&&x.appendChild(he),x.appendChild(q),g&&m==="below"&&e.createdAt){let Z=tb(e,u);Z.classList.add("persona-mt-1"),x.appendChild(Z)}let ne=e.role==="assistant"?sM(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),de=A.placeholder==="skeleton",Ce=de&&A.buffer==="line"&&Z;if(Z)Ce&&x.appendChild(Sa());else if(de)x.appendChild(Sa());else{let fe=ob("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);fe&&x.appendChild(fe)}}if(ne&&e.stopReason&&!e.streaming&&(L||(q.style.display="none"),x.appendChild(iM(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=rb(e,o,r);x.appendChild(Z)}if(!p||e.role==="system")return x;let ie=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),M=vM(d,e.role);return y==="right"||y==="left"&&e.role==="user"?ie.append(x,M):ie.append(M,x),ie},CM=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Pa(e,t,n,o,r,s)};var wM=40,xM=(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=ce(t.name,wM);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ue("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ue("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},sb=(e,t,n={})=>{let o=ue("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),s=v("p","persona-welcome-subtitle");return{host:ue("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}},Qs=(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)},Ec=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",xM(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},SM="data-persona-welcome-plugin",ib="data-persona-welcome-overlay",Tc="persona-welcome-overlay-active",yu=new WeakMap,bu=(e,t,n)=>{n.setAttribute(SM,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(ib,""),e.classList.contains(Tc)||(yu.set(e,e.scrollTop),e.classList.add(Tc),e.scrollTop=0)},vu=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(ib),e.classList.contains(Tc)&&(e.classList.remove(Tc),e.scrollTop=yu.get(e)??e.scrollTop,yu.delete(e))},ab=()=>{let e=ue("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Mc=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ue("div",{className:ka("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(ue("div",{className:"persona-flex"},r)),e.hidden=!1},AM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,lb=(e,t)=>{if(AM()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let x=e.previousElementSibling,T=e.nextElementSibling,D=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,x?n.top-x.getBoundingClientRect().bottom-r:n.top-D),i=Math.max(0,T?T.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),u=parseFloat(d.paddingTop)||0,p=parseFloat(d.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,m=()=>{y||(y=!0,e.style.overflow=l,t(g))};return g.finished.then(m).catch(m),g};var TM="Hello \u{1F44B}",EM="I can answer questions and help you get things done here.",cb=new WeakSet,zn=(e,t)=>!!e&&e[t]!==void 0,MM=(e,t)=>{!e||e.debug!==!0||!t.length||cb.has(e)||(cb.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},gr=e=>{let t=e?.welcome,n=e?.copy,o=zn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":zn(t,"dismiss")?t.dismiss:"never",s=[];return zn(t,"title")&&zn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),zn(t,"subtitle")&&zn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),zn(t,"variant")&&zn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&zn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&zn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),MM(e,s),{title:zn(t,"title")?t.title:n?.welcomeTitle??TM,subtitle:zn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??EM,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Qr=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var db="16px",Cu="10px",wu="14px",pb=e=>{let t=e?.launcher?.enabled??!0,n=wt(e);if(pr(e)){let p=e?.launcher?.composerBar??{},g=v("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Jt);let y=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Jt),{wrapper:g,panel:y,pillRoot:m}}if(n){let p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!t){let p=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return p.style.width=y,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let r=e?.launcher??{},s=r.position&&Ln[r.position]?Ln[r.position]:Ln["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Jt);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??jn;return l.style.width=u,l.style.maxWidth=u,i.appendChild(l),{wrapper:i,panel:l}},xu=e=>{let t=ue("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":du(e)}});return t.hidden=!0,t},ub=(e,t)=>{let n=xu("starter"),o=sb(e,n,{flatShadow:wt(e)}),r=gr(e);Ec(o,r),Qs(t,o.host,Qr(r,e?.initialMessages));let s=ab();return Mc(s,r.message,e),{welcome:o,greetingHost:s}},kM=(e,t)=>{let n=v("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}=Ks(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:db,iconSize:Cu});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let R=Gs(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:db,iconSize:wu});i=R.button,l=R.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=ue("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=ue("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"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:g}=ub(e,u),{host:y,title:m,subtitle:b}=p,x=p.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),L=xu("followUp"),D=rr(e,!0);D&&(T.style.maxWidth=D,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),u.append(y,g,T,L);let k=ue("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),A=Ac({config:e}),{root:W,textNode:I}=Qy();return n.append(d,r,u,k),l&&n.appendChild(l),{container:n,body:u,messagesWrapper:T,starterSuggestions:x,transcriptSuggestions:L,composerOverlay:k,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:y,welcomeIconHolder:p.iconHolder,greetingHost:g,introTitle:m,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:W,peekTextNode:I}},gb=(e,t=!0)=>{if(pr(e))return kM(e,t);let n=ue("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?Ma(e,o,{showClose:t}):ur({config:e,showClose:t}),i=ue("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=ub(e,i),{host:u,title:p,subtitle:g}=l,y=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=xu("followUp"),x=rr(e,!1);x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.append(u,d,m,b);let T=Js({config:e}),L=e?.layout?.showFooter!==!1;r?Ys(n,s,e):(s.header.style.display="none",Ys(n,s,e)),n.append(i);let D=ue("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 L||(T.footer.style.display="none"),n.append(T.footer),n.append(D),{container:n,body:i,messagesWrapper:m,starterSuggestions:y,transcriptSuggestions:b,composerOverlay:D,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:u,welcomeIconHolder:l.iconHolder,greetingHost:d,introTitle:p,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var Su=(e,t)=>{let n=v("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">
|
|
37
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-
|
|
38
|
-
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
37
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
|
|
38
|
+
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-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
|
|
42
|
-
`):""},
|
|
43
|
-
`);let r=
|
|
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=`
|
|
41
|
+
`,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=wt(s),d=n.querySelector("[data-role='launcher-title']");if(d){let k=i.title??"Chat Assistant";d.textContent=k,d.setAttribute("title",k)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let k=i.subtitle??"Here to help you get answers fast";u.textContent=k,u.setAttribute("title",k)}let p=n.querySelector(".persona-flex-col");p&&(i.textHidden||l?p.style.display="none":p.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(i.agentIconHidden)g.style.display="none";else{let k=i.agentIconSize??"40px";if(g.style.height=k,g.style.width=k,i.agentIconBackgroundColor?(g.style.backgroundColor=i.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",i.agentIconName){let A=parseFloat(k)||24,W=ce(i.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);W?(g.appendChild(W),g.style.display=""):(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}else i.iconUrl?g.style.display="none":(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let k=i.agentIconSize??"40px";y.style.height=k,y.style.width=k,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let k=i.callToActionIconSize??"32px";m.style.height=k,m.style.width=k,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(m.style.color=i.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let A=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,A=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",i.callToActionIconName){let W=parseFloat(k)||24,I=Math.max(W-A,8),R=ce(i.callToActionIconName,I,"currentColor",1.5);R?m.appendChild(R):m.textContent=i.callToActionIconText??"\u2197"}else m.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&Ln[i.position]?Ln[i.position]:Ln["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${x} ${b}`,l||(n.style.zIndex=String(i.zIndex??Jt));let L="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",D="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=i.border??L,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:D,l?(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=i.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}},PM="teaser-dismissed",mb=new Set,fb=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${PM}`},LM=(e,t)=>{if(mb.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},HM=(e,t)=>{if(mb.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},IM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,RM=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||wt(e??{})?null:t},hb=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,d=null,u=!1,p=!1,g=!1,y=!1,m=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},x=()=>{!s||!u||(u=!1,s.hidden=!0)},T=ve=>{b(),g=!0,x(),HM(fb(o),ve&&m())},L=ve=>{!r||g||T(ve==="user"&&u)},D=()=>{d=null,!(!s||g||y)&&(p=!0,u=!0,s.hidden=!1,!(IM()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},k=()=>{!r||!s||g||p||y||LM(fb(o),m())||(b(),d=setTimeout(D,Math.max(0,r.delayMs??0)))},A=()=>{T(m()),t()},W=ve=>{ve.stopPropagation(),T(m())},R=Su(e,()=>{L("user"),t()}),z=()=>{b(),l?.removeEventListener("click",A),i?.removeEventListener("click",W),s?.remove(),s=null,l=null,i=null,u=!1},q=()=>{l=ue("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),i=ue("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",W),s=ue("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,R.element)},Q=()=>{let ve=o.launcher?.position??"bottom-right",he=Ln[ve]??Ln["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",R.element.style.position="";return}n.className=Fn("persona-launcher-surface",he),n.setAttribute("data-teaser",ve),n.style.zIndex=String(o.launcher?.zIndex??Jt),R.element.style.position="static"},$=ve=>{let he=RM(ve);if(r=he,!he){z();return}s||q(),l.textContent=he.text,i.hidden=he.dismissible===!1,i.setAttribute("aria-label",he.dismissLabel??"Dismiss message"),k()},J=ve=>{o=ve,R.update(ve),$(ve),Q()},pe=(ve,he="user")=>{y=ve,ve&&L(he)},we=()=>{z(),R.destroy(),n.remove()};return n.appendChild(R.element),e&&($(e),Q()),{element:n,launcher:R,get teaser(){return s?{element:s,show:D,dismiss:T}:null},setPanelOpen:pe,update:J,destroy:we}};var yb=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=pb(e),s=gb(e,t),i={wrapper:n,panel:o,pillRoot:r},l={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},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},u={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:i,panelElements:s,transcript:l,header:d,composer:u,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{u.footer.replaceWith(y),u.footer=y}}},Au=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Su(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=hb(e,n);return{instance:r,element:r.element}};var WM=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},BM=(e,t,n)=>`${WM(e)}plugin:${t}:${n}`,bb=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=i=>BM(e(),r,i);return{get:i=>{let l=s(i),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let d=s(i),u=o();if(u)try{u.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:i=>{let l=s(i);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var Zs=new Set,OM=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),DM=(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
|
+
`):""},vb=(e,t)=>{let n=Zs.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 l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=ce(n?"chevron-up":"chevron-down",16,"currentColor",2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Tu=(e,t)=>{let n=e.reasoning,o=v("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,i=s&&Zs.has(e.id),l=n.status!=="complete",d=DM(e,r.previewMaxLines??3),u=v("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");u.type="button",s&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",m=t?.reasoning??{},b=String(n.startedAt??Date.now()),x=()=>{let we=v("span","");return we.setAttribute("data-tool-elapsed",b),we.textContent=jl(n),we},T=m.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:jl(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(g.textContent=T,p.appendChild(g)):T instanceof HTMLElement?p.appendChild(T):(g.textContent=y,p.appendChild(g));let L=v("span","persona-text-xs persona-text-persona-primary");L.textContent=fh(n),p.appendChild(L);let D=r.loadingAnimation??"none",k=m.activeTextTemplate,A=m.completeTextTemplate,W=l?k:A,I=T instanceof HTMLElement,R=(we,ve)=>{g.textContent="";let he=zl(we,""),ne=0;for(let ae of he){let ie=ae.styles.length>0?(()=>{let M=v("span",ae.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return g.appendChild(M),M})():g;if(ae.isDuration&&l)ie.appendChild(x());else{let M=ae.isDuration?jl(n):ae.text;ve?ne=ir(ie,M,ne):ie.appendChild(document.createTextNode(M))}}};if(!I&&W)if(L.style.display="none",g.style.display="",l&&D!=="none"){let we=m.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),D==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),R(W,!1)):(g.classList.add(`persona-tool-loading-${D}`),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),D==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),R(W,!0))}else R(W,!1);else if(!I&&l&&D!=="none"){g.style.display="";let we=m.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),D==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`);else{g.classList.add(`persona-tool-loading-${D}`),g.style.setProperty("--persona-tool-anim-duration",`${we}ms`),D==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let ve=g.textContent||y;g.textContent="",ir(g,ve,0)}n.status==="complete"&&(g.style.display="none")}else I||(n.status==="complete"?g.style.display="none":g.style.display="");let z=null;if(s){z=v("div","persona-flex persona-items-center");let ve=ce(i?"chevron-up":"chevron-down",16,"currentColor",2);ve?z.appendChild(ve):z.textContent=i?"Hide":"Show";let he=v("div","persona-flex persona-items-center persona-ml-auto");he.append(z),u.append(p,he)}else u.append(p);let q=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&d){let we=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}});OM(q,we)||(q.textContent=d),q.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(u,q),o;let Q=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=i?"":"none";let $=n.chunks.join(""),J=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=$||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild(J),(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),z){z.innerHTML="";let ve=ce(i?"chevron-up":"chevron-down",16,"currentColor",2);ve?z.appendChild(ve):z.textContent=i?"Hide":"Show"}Q.style.display=i?"":"none",q.style.display=i?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(u,q,Q),o};var ei=new Set,_M=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),NM=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
43
|
+
`);let r=or(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
44
|
+
`):""},Eu=(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)"},FM=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=NM(e,o?.previewMaxLines??3),i=n?mh(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},u=i;return r==="tool-name"?u=n.name?.trim()||i:r==="tool-preview"&&s&&(u=s),l&&d.activeTextTemplate?u=Ep(n,d.activeTextTemplate,u):!l&&d.completeTextTemplate&&(u=Ep(n,d.completeTextTemplate,u)),{summary:u,previewText:s,isActive:l}},Cb=(e,t,n)=>{let o=ei.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(u){u.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=ce(o?"chevron-up":"chevron-down",16,p,2);g?u.appendChild(g):u.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Mu=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=v("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??{},i=s.expandable!==!1,l=i&&ei.has(e.id),{summary:d,previewText:u,isActive:p}=FM(e,t),g=v("button",i?"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",i&&(g.setAttribute("aria-expanded",l?"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 y=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),x=()=>{let $=v("span","");return $.setAttribute("data-tool-elapsed",b),$.textContent=ta(n),$},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:s.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:ta(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(m.textContent=T,y.appendChild(m)):T instanceof HTMLElement?y.appendChild(T):(m.textContent=d,y.appendChild(m));let L=s.loadingAnimation??"none",D=o.activeTextTemplate,k=o.completeTextTemplate,A=p?D:k,W=T instanceof HTMLElement,I=($,J)=>{m.textContent="";let pe=n.name?.trim()||"tool",we=zl($,pe),ve=0;for(let he of we){let ne=he.styles.length>0?(()=>{let ae=v("span",he.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ae),ae})():m;if(he.isDuration&&p)ne.appendChild(x());else{let ae=he.isDuration?ta(n):he.text;J?ve=ir(ne,ae,ve):ne.appendChild(document.createTextNode(ae))}}};if(!W)if(p&&L!=="none"){let $=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${$}ms`),A&&I(A,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${$}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)I(A,!0);else{let J=m.textContent||d;m.textContent="",ir(m,J,0)}}else A&&I(A,!1);let R=null;if(i){R=v("div","persona-flex persona-items-center");let $=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",J=ce(l?"chevron-up":"chevron-down",16,$,2);J?R.appendChild(J):R.textContent=l?"Hide":"Show";let pe=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(R),g.append(y,pe)}else g.append(y);let z=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!l&&p&&s.activePreview&&u){let $=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:u,isActive:p,config:t??{}});_M(z,$)||(z.textContent=u),z.style.display=""}if(!l&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(g,z),r;let q=v("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=l?"":"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 $=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?$.style.color=o.contentTextColor:o.headerTextColor&&($.style.color=o.headerTextColor),$.textContent=n.name,q.appendChild($)}if(n.args!==void 0){let $=v("div","persona-space-y-1"),J=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let pe=v("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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Eu(pe,o),pe.textContent=or(n.args),$.append(J,pe),q.appendChild($)}if(n.chunks&&n.chunks.length){let $=v("div","persona-space-y-1"),J=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let pe=v("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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Eu(pe,o),pe.textContent=n.chunks.join(""),$.append(J,pe),q.appendChild($)}if(n.status==="complete"&&n.result!==void 0){let $=v("div","persona-space-y-1"),J=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let pe=v("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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Eu(pe,o),pe.textContent=or(n.result),$.append(J,pe),q.appendChild($)}if(n.status==="complete"&&typeof n.duration=="number"){let $=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&($.style.color=o.contentTextColor),$.textContent=`Duration: ${n.duration}ms`,q.appendChild($)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),R){R.innerHTML="";let $=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",J=ce(l?"chevron-up":"chevron-down",16,$,2);J?R.appendChild(J):R.textContent=l?"Hide":"Show"}q.style.display=l?"":"none",z.style.display=l?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(g,z,q),r};var Zr=new Map,kc=e=>{let n=(e.startsWith(so)?e.slice(so.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)},wb=e=>e?.approval!==!1?e?.approval:void 0,xb=(e,t)=>{let n=wb(t)?.detailsDisplay??"collapsed";return Zr.get(e)??n==="expanded"},Sb=(e,t,n)=>{let o=wb(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 i=ce(t?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},Ab=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=xb(e,n);Sb(o,s,n),r.style.display=s?"":"none"};var Pc=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=v("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 i=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",u=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",p=ce(d,20,u,2);p&&l.appendChild(p);let g=v("div","persona-flex-1 persona-min-w-0"),y=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(m.style.color=o.titleColor),m.textContent=o?.title??"Approval Required",y.appendChild(m),!r){let R=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");R.setAttribute("data-approval-status",n.status),n.status==="approved"?(R.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",R.style.color="var(--persona-palette-colors-success-700, #15803d)",R.textContent="Approved"):n.status==="denied"?(R.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",R.style.color="var(--persona-palette-colors-error-700, #b91c1c)",R.textContent="Denied"):n.status==="timeout"&&(R.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",R.style.color="var(--persona-palette-colors-warning-700, #b45309)",R.textContent="Timeout"),y.appendChild(R)}g.appendChild(y);let x=n.toolType==="webmcp"||n.toolName.startsWith(so)?Gi(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,D=T||(L?n.description:`The assistant wants to use \u201C${x??kc(n.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=D,g.appendChild(k),n.reason){let R=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");R.setAttribute("data-approval-reason","true"),o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let z=v("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.appendChild(z),R.appendChild(document.createTextNode(n.reason)),g.appendChild(R)}let A=o?.detailsDisplay??"collapsed",W=!!n.description&&!L,I=W||!!n.parameters;if(A!=="hidden"&&I){let R=xb(e.id,t),z=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=v("span");q.setAttribute("data-approval-details-label","true");let Q=v("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),z.append(q,Q),Sb(z,R,t),g.appendChild(z);let $=v("div");if($.setAttribute("data-approval-details","true"),$.style.display=R?"":"none",W){let J=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(J.style.color=o.descriptionColor),J.textContent=n.description,$.appendChild(J)}if(n.parameters){let J=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(J.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(J.style.color=o.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=or(n.parameters),$.appendChild(J)}g.appendChild($)}if(r){let R=v("div","persona-flex persona-gap-2 persona-mt-2");R.setAttribute("data-approval-buttons","true");let z=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let q=ce("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",z.appendChild(q));let Q=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(Q);let $=v("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");$.type="button",$.style.backgroundColor=o?.denyButtonColor??"transparent",$.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",$.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,$.setAttribute("data-approval-action","deny");let J=ce("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",$.appendChild(J));let pe=document.createTextNode(o?.denyLabel??"Deny");$.appendChild(pe),R.append(z,$),g.appendChild(R)}return i.append(l,g),s.appendChild(i),s};function $M(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Tb(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:d=2147483e3,onOpen:u,onDismiss:p}=e,g=e.container??$M(t),y=!1,m=null,b=()=>{if(!y)return;let L=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${L.width}px`),i&&(n.style.maxWidth=`${L.width}px`);let D=n.getBoundingClientRect(),k=l?.()??null,A=k!=null?L.top+k:L.top,W=o==="top-start"||o==="top-end"?A-r-D.height:L.bottom+r,R=o==="bottom-end"||o==="top-end"?L.right-D.width:L.left,z=i?.()??null;if(z!=null){let q=Math.max(L.left,L.right-D.width);R=Math.min(Math.max(L.left+z,L.left),q)}n.style.top=`${W}px`,n.style.left=`${R}px`},x=()=>{y&&(y=!1,m&&(m(),m=null),n.remove())},T=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),g.appendChild(n),b();let L=(t.ownerDocument??document).defaultView??window,D=t.ownerDocument??document,k=()=>{if(!t.isConnected){x(),p?.("anchor-removed");return}b()},A=I=>{let R=typeof I.composedPath=="function"?I.composedPath():[];R.includes(n)||R.includes(t)||(x(),p?.("outside"))},W=L.setTimeout(()=>{D.addEventListener("pointerdown",A,!0)},0);L.addEventListener("scroll",k,!0),L.addEventListener("resize",k),m=()=>{L.clearTimeout(W),D.removeEventListener("pointerdown",A,!0),L.removeEventListener("scroll",k,!0),L.removeEventListener("resize",k)},u?.()};return{get isOpen(){return y},open:T,close:x,toggle:()=>y?x():T(),reposition:b,destroy:x}}function Eb(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var jM=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Mb=(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))},es=(e,t)=>{Mb(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)},zM=e=>e?.approval!==!1?e?.approval:void 0,UM=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Zr.get(e)??n==="expanded"},ku=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},qM=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(so)?Gi(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 i=r??kc(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=i,n.appendChild(d),l){n.append(" from ");let u=document.createElement("strong");u.textContent=l,n.appendChild(u)}return n},VM=e=>{let t=v("div","persona-approval-resolved"),n=ce("ban",15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?kc(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},KM=(e,t,n,o,r,s,i)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",u=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",g=u||p,y=g&&UM(t.id,o),m=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",x=v("button","persona-approval-head");x.type="button",g?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",y?"true":"false"),x.setAttribute("aria-label",y?b:m)):x.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),L=ce("shield-check",16,"currentColor",2);L&&T.appendChild(L),x.appendChild(T);let D=qM(n,o);if(g){let z=v("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let q=ce("chevron-down",14,"currentColor",2);q&&z.appendChild(q),D.append(" "),D.appendChild(z)}x.appendChild(D),l.appendChild(x);let k=v("div","persona-approval-body");if(g){let z=v("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!y,u){let q=v("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,z.appendChild(q)}if(p){let q=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=or(n.parameters),z.appendChild(q)}k.appendChild(z)}if(n.reason){let z=v("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=v("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(q,document.createTextNode(n.reason)),k.appendChild(z)}let A=v("div","persona-approval-actions"),W=null,I=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},R=v("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),o?.denyButtonColor&&(R.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(R.style.color=o.denyButtonTextColor),R.append(o?.denyLabel??"Deny"),i){let z=v("div","persona-approval-split"),q=v("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),I(q),q.append(o?.approveLabel??"Always allow",ku("\u23CE"));let Q=v("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),I(Q);let $=ce("chevron-down",15,"currentColor",2);$&&Q.appendChild($),z.append(q,Q),A.append(z,R),R.append(ku("Esc"));let J=v("div","persona-approval-menu"),pe=v("button","persona-approval-menu-item");pe.type="button",pe.append("Allow once",ku("\u2318\u23CE")),J.appendChild(pe),W=Tb({anchor:z,content:J,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,W),pe.addEventListener("click",()=>{es(e,t.id),r()})}else{let z=v("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),I(z),z.append(o?.approveLabel??"Allow"),A.append(z,R)}return k.appendChild(A),l.appendChild(k),l.addEventListener("click",z=>{let q=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!q)return;let Q=q.getAttribute("data-action");if(Q==="toggle-params"){let $=l.querySelector('[data-role="params"]');if($){let J=$.hidden;$.hidden=!J,x.setAttribute("aria-expanded",J?"true":"false"),x.setAttribute("aria-label",J?b:m),Zr.set(t.id,J)}return}if(Q==="toggle-menu"){W?.toggle();return}if(Q==="always"){es(e,t.id),r({remember:!0});return}if(Q==="allow"){es(e,t.id),r();return}if(Q==="deny"){es(e,t.id),s();return}}),l},kb=()=>{let e=jM();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let d=zM(i);if(l.status!=="pending"){if(es(e,o.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return VM(l)}Mb(e,o.id);let u=d?.enableAlwaysAllow===!0,p=KM(e,o,l,d,r,s,u);if(u){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=y=>{Eb(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),es(e,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])es(e,o);e.latestPendingApprovalId=null}}};var La=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 Ha=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 i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.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 GM=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),YM=new Set(["step_start","execution_start"]),JM=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),XM=new Set(["step_complete","agent_turn_complete"]),QM=new Set(["flow_complete","agent_complete"]),Pb=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Hb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Hn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ts=(e,t)=>{let n=e[t];return Hb(n)?n:void 0};function Pu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Lc(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function ZM(e,t){return typeof t.type=="string"?t.type:e}function ek(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 tk(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 Lb(e){let t=ts(e,"result"),n=[ts(e,"tokens"),ts(e,"totalTokens"),t?ts(t,"tokens"):void 0,ts(e,"usage"),t?ts(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=Hn(o.output)??Hn(o.outputTokens)??Hn(o.completionTokens);if(r!==void 0)return r}return Hn(e.outputTokens)??Hn(e.completionTokens)??(t?Hn(t.outputTokens)??Hn(t.completionTokens):void 0)}function nk(e){let t=ts(e,"result");return Hn(e.executionTime)??Hn(e.executionTimeMs)??Hn(e.execution_time)??Hn(e.duration)??(t?Hn(t.executionTime)??Hn(t.executionTimeMs):void 0)}function ok(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ia=class{constructor(t=ok){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:Lc(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(!Hb(n)){Pb.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=ZM(t,n),r=this.now();if(GM.has(o)){this.startRun(r);return}if(YM.has(o)){this.run||this.startRun(r);return}if(JM.has(o)){if(!tk(o,n))return;let s=ek(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+Pu(i.visibleCharCount),d=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Lc(l,d),outputTokens:l,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(XM.has(o)){if(!this.run)return;let s=this.run,i=Lb(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+Pu(s.visibleCharCount),u=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Lc(d,u),outputTokens:d,durationMs:u,source:l?"usage":"estimate"};return}if(QM.has(o)){if(!this.run)return;let s=this.run,i=Lb(n),l=i??s.exactOutputTokens+Pu(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Lc(l,u),outputTokens:l,durationMs:u,source:d},this.run=null;return}if(Pb.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:nk(n)??o-t.startedAt}};var{setLoader:PW,load:rk}=ro({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var Ib=rk;function Lu(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},d=g=>{let y=g;return s.findIndex(m=>m===y||m.contains(y))},u=g=>{let y=d(g.target);if(y<0)return;let m=y;if(g.key===r)m=Math.min(y+1,s.length-1);else if(g.key===o)m=Math.max(y-1,0);else if(g.key==="Home")m=0;else if(g.key==="End")m=s.length-1;else return;g.preventDefault(),m!==y&&t.onSelect(m)},p=g=>{let y=d(g.target);y>=0&&l(s[y])};return e.addEventListener("keydown",u),e.addEventListener("focusin",p),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(g,y){if(s=g,g.forEach((m,b)=>{m.setAttribute("role","tab");let x=b===y;m.setAttribute("aria-selected",x?"true":"false"),m.tabIndex=x||y<0&&b===0?0:-1}),i){let m=(y>=0?g[y]:void 0)??g[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){e.removeEventListener("keydown",u),e.removeEventListener("focusin",p)}}}function Rb(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),u=S=>({start:S===!1?!1:typeof S=="object"&&S?S.start!==!1:!0,end:S===!1?!1:typeof S=="object"&&S?S.end!==!1:!0}),{start:p,end:g}=u(n?.tabFade),y=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{y?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),$?.closeMenu()};y&&y.addEventListener("click",()=>{m(),t.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let x=v("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");x.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&x.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let L=st({icon:"x",label:i});L.addEventListener("click",()=>{m(),t.onDismiss?.()});let D="rendered",k=lr({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:S=>{D=S==="source"?"source":"rendered",N()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),W=n?.documentToolbarShowCopyLabel===!0,I=n?.documentToolbarShowCopyChevron===!0,R=n?.documentToolbarCopyMenuItems,z=!!(I&&R&&R.length>0),q=null,Q,$=null;if(r&&(W||I)&&!z){if(Q=W?ar({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):st({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let S=ce("chevron-down",14,"currentColor",2);S&&Q.appendChild(S)}}else r&&z?($=Zp({label:"Copy",icon:"copy",iconSize:14,iconOnly:!W,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(R??[]).map(S=>({id:S.id,label:S.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:S=>{Ce(S)}}),q=$.element,Q=$.primaryButton):r?Q=st({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=st({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let J=r?st({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):st({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||J.classList.add("persona-hidden");let pe=r?st({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):st({icon:"x",label:i}),we=st({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&we.classList.add("persona-hidden");let ve=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),he=e.features?.artifacts?.toolbarActions??[],ne=()=>{let S=Se.find(V=>V.id===Ne)??Se[Se.length-1],H=S?.id??null,P=S?.artifactType==="markdown"?S.markdown??"":"",B=S?JSON.stringify({component:S.component,props:S.props},null,2):"",{filename:G,mime:X,content:K}=sc({title:S?.title,markdown:S?.markdown??"",file:S?.file});return{markdown:P,jsonPayload:B,id:H,file:S?.file,suggestedFilename:G,mime:X,content:K}},ae=()=>{let{suggestedFilename:S,mime:H,content:P}=ne();P&&ic({filename:S,mime:H,content:P})},ie=S=>{let{id:H,...P}=ne();return{actionId:S,artifactId:H,...P}},M=async()=>{let S=Se.find(H=>H.id===Ne)??Se[Se.length-1];try{return await navigator.clipboard.writeText(va(S)),!0}catch{return!1}},Z=null,de=()=>{Z?.();let S=Q.querySelector("svg"),H=Number(S?.getAttribute("width"))||16,P=ce("check",H,"currentColor",2);if(!S||!P)return;S.replaceWith(P);let B=Q.querySelector("span");B&&(B.textContent="Copied");let G=setTimeout(()=>Z?.(),2e3);Z=()=>{clearTimeout(G),P.replaceWith(S),B&&(B.textContent="Copy"),Z=null}};Q.addEventListener("click",async()=>{let S=n?.onDocumentToolbarCopyMenuSelect;if(S&&z){try{if(await S(ie("primary"))===!1){await M()&&de();return}de()}catch{}return}await M()&&de()});async function Ce(S){let H=n?.onDocumentToolbarCopyMenuSelect;try{if(H&&await H(ie(S))!==!1)return;if(S==="download"){ae();return}let{markdown:P,jsonPayload:B}=ne();S==="markdown"||S==="md"?await navigator.clipboard.writeText(P):S==="json"||S==="source"?await navigator.clipboard.writeText(B):await navigator.clipboard.writeText(P||B),de()}catch{}}J.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}N()}),pe.addEventListener("click",()=>{m(),t.onDismiss?.()});let fe=v("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)x.replaceChildren(),q?A.append(q,J,pe):A.append(Q,J,pe),A.insertBefore(ve,pe),A.insertBefore(we,pe),x.append(k.element,fe,A);else{let S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");S.append(Q,ve,we,L),x.appendChild(T),x.appendChild(S)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let xe=v("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&&xe.style.setProperty("--persona-artifact-tab-fade-size",d);let Pe=e.features?.artifacts?.renderTabBar,Le=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Je=Lu(xe,{onSelect:S=>t.onSelect(Se[S].id)}),Be=S=>{let H=S.scrollWidth-S.clientWidth,P=H>1,B=Math.abs(S.scrollLeft);S.classList.toggle("persona-artifact-tab-fade-start",p&&P&&B>1),S.classList.toggle("persona-artifact-tab-fade-end",g&&P&&B<H-1)},Re=0,et=()=>{if(Re)return;let S=()=>{Re=0,Be(xe)};Re=typeof requestAnimationFrame=="function"?requestAnimationFrame(S):setTimeout(S,0)};xe.addEventListener("scroll",()=>et(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(xe)).observe(xe);let be=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),_e=()=>{be.scrollLeft=0},gt=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(_e):setTimeout(_e,0)};if(l){for(let S of[xe,Le])S.style.paddingLeft=l,S.style.paddingRight=l;be.style.padding=l}b.appendChild(x),b.appendChild(xe),b.appendChild(Le),b.appendChild(be);let Se=[],Ne=null,it=!1,Kt=!1,zt=!0,Un=!1,Ze=null,tt="",vt=null,Qt=!1,fo=S=>S.artifactType==="markdown"&&!!S.file||r?D:"rendered",It=S=>{r||(S&&!Qt?(x.insertBefore(k.element,T),Qt=!0):!S&&Qt&&(k.element.remove(),Qt=!1))},No=()=>Ne&&Se.find(S=>S.id===Ne)||Se[Se.length-1],rs=()=>{let S=ya(No());if(!S){ve.replaceChildren();return}let H=he.filter(P=>P.visible===void 0||P.visible(S)).map(P=>qs(P,{documentChrome:r,onClick:()=>{let B=ya(No());if(B)try{Promise.resolve(P.onClick(B)).catch(()=>{})}catch{}}}));ve.replaceChildren(...H)},N=()=>{rs();let S=r&&Se.length<=1,H=!!Pe;if(xe.classList.toggle("persona-hidden",S||H),Le.classList.toggle("persona-hidden",S||!H),H&&Pe){let G=Se.map(X=>X.id).join("|")+" "+(Ne??"");if(G!==tt){tt=G;let X=Pe({records:Se,selectedId:Ne,onSelect:t.onSelect});Le.firstElementChild!==X&&Le.replaceChildren(X)}}else{Je.beforeRender(),xe.replaceChildren();let G=[],X=-1;for(let[K,V]of Se.entries()){let le=v("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");le.type="button";let ct=V.artifactType==="markdown"?V.file:void 0,ot=ct?lo(ct.path):V.title||V.id.slice(0,8),Ct=ct?.path||V.title||ot;le.textContent=ot,le.title=Ct,le.setAttribute("aria-label",Ct),V.id===Ne&&(le.classList.add("persona-bg-persona-container","persona-border-persona-border"),X=K),le.addEventListener("click",()=>t.onSelect(V.id)),xe.appendChild(le),G.push(le)}if(Je.render(G,X),X>=0&&Ne!==Ze){Ze=Ne;let K=G[X];typeof K.scrollIntoView=="function"&&K.scrollIntoView({block:"nearest",inline:"nearest"})}Be(xe)}let P=Ne&&Se.find(G=>G.id===Ne)||Se[Se.length-1];if(!P){be.replaceChildren(),vt?.destroy(),vt=null,It(!1);return}let B=P.artifactType==="markdown"?P.file:void 0;if(It(!!B&&Gr(B)!=="other"),r){let G=B?sr(B):P.artifactType==="markdown"?"MD":P.component??"Component",X=(P.title||"Document").trim(),K=B?lo(B.path):X.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";fe.textContent=`${K} \xB7 ${G}`}else T.textContent=B?lo(B.path):s;vt?(vt.el.parentElement!==be&&be.replaceChildren(vt.el),vt.update(P)):(vt=pc(P,{config:e,resolveViewMode:fo}),be.replaceChildren(vt.el)),be.classList.toggle("persona-artifact-content-flush",!!be.querySelector(".persona-code-pre"))},ee=()=>{let S=Se.length>0;if(b.classList.toggle("persona-hidden",!S),y){let B=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;S&&B&&it?(y.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},w=()=>{Un=!1,N(),ee()};return{element:b,backdrop:y,update(S){let H=S.selectedId??S.artifacts[S.artifacts.length-1]?.id??null,P=H!==Ne;Se=S.artifacts,Ne=H,Se.length>0&&(it=!0),Un=!0,zt&&w(),P&&_e()},setMobileOpen(S){it=S,!S&&y?(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ee()},setExpanded(S){S!==Kt&&(Kt=S,gt());let H=ce(S?"minimize":"maximize",16,"currentColor",2);H&&we.replaceChildren(H);let P=S?"Collapse artifacts panel":"Expand artifacts panel";we.setAttribute("aria-label",P),we.title=P},setExpandToggleVisible(S){we.classList.toggle("persona-hidden",!S)},setCopyButtonVisible(S){r||Q.classList.toggle("persona-hidden",!S)},setRefreshButtonVisible(S){J.classList.toggle("persona-hidden",!S)},setCustomActions(S){he=S,rs()},setTabFade(S){let H=u(S);H.start===p&&H.end===g||(p=H.start,g=H.end,Be(xe))},setRenderTabBar(S){S!==Pe&&(Pe=S,tt="",N())},setVisible(S){S!==zt&&(zt=S,S&&Un&&w())},destroy(){vt?.destroy(),vt=null}}}function un(e){return e?.features?.artifacts?.enabled===!0}function Wb(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"),!un(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 sk(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 Bb=["panel","seamless","detached"];function Hu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Bb.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Iu(e){return!e||!un(e)?!1:Hu(e)==="detached"}function Ra(e,t){if(!un(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"),sk(e),Wb(e,t);return}let n=t.features?.artifacts?.layout,o=Hu(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 i=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of i){let u=l?.trim();u?e.style.setProperty(d,u):e.style.removeProperty(d)}Wb(e,t)}function Wa(e,t){for(let l of Bb)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!un(t))return;let n=t.features?.artifacts?.layout,o=Hu(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 i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function Ob(e,t){return!t||!un(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var ik=new Set(["__proto__","prototype","constructor"]),ak=new Set(["collapsed","card","panel","inline"]),Db=new Set(["markdown","component"]),lk=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ns=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ic=e=>!ik.has(e),Ru=e=>typeof e=="string"&&ak.has(e),os=e=>Object.keys(e).length>0;function uo(e,t,n,o){e.push({path:t,code:n,message:o})}var ck="Ignored because this key is not part of the persisted preference schema.",Hc="Ignored an unsupported value.",dk="Expected collapsed, panel, or inline.",pk='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',_b={kind:"mode",message:Hc},ti={kind:"string",message:"Expected a CSS length string."},Oo={kind:"boolean"},uk={paneWidth:ti,paneMaxWidth:ti,paneMinWidth:ti,expandedPanelWidth:ti,resizableMinWidth:ti,resizableMaxWidth:ti,expandLauncherPanelWhenOpen:Oo,resizable:Oo},gk={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Oo,showReasoning:Oo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Hc},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Hc},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Hc},expandable:Oo,grouped:Oo}},reasoningDisplay:{kind:"object",children:{expandable:Oo,activePreview:Oo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:_b,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:_b,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Db,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Db}}},filePreview:{kind:"object",children:{enabled:Oo}},layout:{kind:"object",children:uk}}}}};function Nb(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:uo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:uo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:uo(o,n,"invalid_value",t.message);case"mode":return Ru(e)?kn(e):uo(o,n,"invalid_value",t.message);case"modeMap":{if(!ns(e))return uo(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let d=r?i:Fr(i);Ic(i)&&(r?r.has(i):lk.test(d))?Ru(l)?s[d]=kn(l):uo(o,`${n}.${i}`,"invalid_value",dk):uo(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":pk)}return os(s)?s:void 0}case"object":{if(t.bareMode&&Ru(e))return kn(e);if(!ns(e))return uo(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Ic(l)||!r.includes(l))&&uo(o,s(l),"unknown_key",ck);let i={};for(let l of r){let d=t.children[l],u=Nb(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&uo(o,s(l),"deprecated_key",d.deprecated),u===void 0)continue;let p=d.alias??l,g=i[p];i[p]=ns(g)&&ns(u)?{...g,...u}:u}return os(i)?i:void 0}}}function Fb(e){let t=[];return{preferences:(e===null?void 0:Nb(e,gk,"",t))??{},issues:t}}function ni(e){if(Array.isArray(e))return e.map(ni);if(!ns(e))return e;let t={};for(let[n,o]of Object.entries(e))Ic(n)&&o!==void 0&&(t[n]=ni(o));return t}function $b(e,t){let n=ni(e);for(let[o,r]of Object.entries(t)){if(!Ic(o)||r===void 0)continue;let s=n[o];n[o]=ns(s)&&ns(r)?$b(s,r):ni(r)}return n}function fk(e){let t={},n;for(let r of e){let s=Fb(r).preferences;n=jb(n,s.artifacts?.display),t=$b(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function mk(e,t){if(t===void 0)return e===void 0?void 0:ni(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}:{},...os(r)?{byMediaType:r}:{}};return os(s)?s:void 0}function jb(e,t){if(t===void 0)return e===void 0?void 0:ni(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=mk(n.files,t.files),i={...o?{default:o}:{},...os(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return os(i)?i:void 0}function zb(e={},t){let n=fk(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 i=jb(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}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 Rc(e){let t=e.preferences;return!t||!os(t)?e:{...e,features:zb(e.features??{},[t])}}function hk(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 yk(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 bk(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function vk(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Wu(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 Ub(e,t,n,o,r,s,i=200){let l=hk(r,200),d=vk(t,n,o,i);d=Math.max(l,d);let u=yk(s);return u!==null&&(d=Math.min(d,u)),bk(e,l,d)}var qb={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"}},Bu=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=qb[i]??qb.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),u=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let x=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${t.id}-${i}-${b.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,x.appendChild(T);let L=b.type??"text",D;L==="textarea"?(D=document.createElement("textarea"),D.rows=3):(D=document.createElement("input"),D.type=L),D.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",D.id=`${t.id}-${i}-${b.name}`,D.name=b.name,D.placeholder=b.placeholder??"",b.required&&(D.required=!0),x.appendChild(D),p.appendChild(x)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("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");m.type="submit",m.textContent=l.submitLabel??"Submit",g.appendChild(y),g.appendChild(m),p.appendChild(g),s.replaceChildren(d,p),p.addEventListener("submit",async b=>{b.preventDefault();let x=n.formEndpoint??"/form",T=new FormData(p),L={};T.forEach((D,k)=>{L[k]=D}),L.type=i,m.disabled=!0,y.textContent="Submitting\u2026";try{let D=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!D.ok)throw new Error(`Form submission failed (${D.status})`);let k=await D.json();y.textContent=k.message??"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(D){y.textContent=D instanceof Error?D.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ou=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,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Wc=new Ou;var Vb=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ck=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Kb=(e,t,n)=>{if(!Vb(e)||!Vb(t)||Ck.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]=Kb(e[r],t[r],s)}return o};function Bc(e,t){let n=Kb(e,t,"");return fa(n)}var Gb=()=>{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(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var wk=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},xk=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},Oc=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=wk(e),n=xk(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}},Du=e=>typeof e=="string"?e:e==null?"":String(e),oi={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Du(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Du(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:Du(n.text)}}},Yb=e=>Array.isArray(e)?e.map(t=>String(t)):[],Dc=e=>{let t=new Set(Yb(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Yb(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&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 l=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",d)},g=u(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!g)continue;if(g.handled){let y=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:y,resubmit:g.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Sk=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}},Ak=e=>e.map(t=>({...t,streaming:!1})),Tk=e=>e.map(t=>({...t,status:"complete"})),_u=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Sk(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?Ak(n.messages):void 0,artifacts:n.artifacts?Tk(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ek=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},Jb=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return Ek(e)},Mk=async(e,t)=>{let n=await Jb(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Jb(`${e}\0${t}`)}`}};var Xb=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,d=0,u=null,p=null,g=new Set,y=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},m=()=>{let I=y();if(!I)return u;try{return I.getItem(o)}catch{return i=!0,u}},b=(I,R)=>{if(l||I===u)return;let z=u;u=I,d+=1;let q={previousToken:z,token:I,source:R,revision:d};for(let Q of g)Q(q)},x=I=>{l||I.key!==null&&I.key!==o||b(I.key===null?null:I.newValue??null,"external")},T=(async()=>{let I=await Mk(e,t);o=I.storageKey,r=I.leaseKey,s=I.lockName,u=m(),!n&&typeof window<"u"&&window.addEventListener("storage",x)})(),L=I=>new Promise(R=>setTimeout(R,I)),D=()=>{let I=y();if(!I)return null;try{let R=I.getItem(r);if(!R)return null;let z=JSON.parse(R);return typeof z?.expiresAt=="number"&&typeof z?.ownerNonce=="string"?z:null}catch{return null}},k=I=>{let R=y();if(R)try{D()?.ownerNonce===I&&R.removeItem(r)}catch{}},A=I=>new Promise(R=>{let z=setTimeout(q,I);function q(){clearTimeout(z),window.removeEventListener("storage",Q),R()}function Q($){($.key===null||$.key===r)&&q()}window.addEventListener("storage",Q)}),W=async I=>{let R=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,z=Date.now()+15e3;for(;Date.now()<z;){let q=y();if(!q)break;let Q=Date.now(),$=D();if($&&$.expiresAt>Q&&$.ownerNonce!==R){await A(Math.min($.expiresAt-Q,500));continue}try{q.setItem(r,JSON.stringify({ownerNonce:R,expiresAt:Q+1e4}))}catch{i=!0;break}if(await L(20+Math.random()*40),D()?.ownerNonce!==R){await A(500);continue}p=R;try{return await I()}finally{p=null,k(R)}}return I()};return{ready:T,async get(){return await T,b(m(),"external"),u},async set(I){await T;let R=y();if(R)try{R.setItem(o,I)}catch{i=!0}b(I,"local")},async clear(){await T;let I=y();if(I)try{I.removeItem(o)}catch{i=!0}b(null,"local")},revision(){return d},subscribe(I){return g.add(I),()=>{g.delete(I)}},async withFirstInitLock(I){await T;let R=globalThis.navigator?.locks;return R?.request?R.request(s,()=>I()):y()?W(I):I()},matches(I,R,z){return I===e&&R===t&&z===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",x),p&&k(p)}}};var{setLoader:eB,load:kk}=ro({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var Nu=kk;var Fu=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},Do=e=>Object.freeze({...e}),Qb=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Zb=e=>e?Do(e):null;function ev(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,d=[],u=()=>{for(let A of d.splice(0))try{A()}catch(W){Fu("renderHistoryView cleanup",W)}},p=(A,W)=>{for(let I of t){let R=I[A];if(R)try{let z=R(W);if(z)return z}catch(z){Fu(A,z)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),y={header:A=>i?p("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:Do(A.identityStatus),pendingAction:Zb(A.pendingAction),copy:Do(A.copy),actions:Object.freeze({close:x.close,startNewConversation:x.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>i?p("renderHistoryConversation",Object.freeze({...g(),conversation:Qb(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>i?p("renderHistoryState",Object.freeze({...g(),state:Do(A.state),identityStatus:Do(A.identityStatus),copy:Do(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},m=t.flatMap(A=>(A.railSections??[]).map(W=>({...W,placement:W.placement??"above-conversations",items:[],render:I=>W.render(Object.freeze({collapsed:I,presentation:e.getPresentation(),actions:x}))}))),b=e.createView({slots:y,renderDom:!1,onModelChange:()=>k(),railSections:m}),x=Object.freeze({...b.operations,close:e.close}),T=()=>(i=!0,b.setDomRenderEnabled(!0),b.element),L=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(Qb)),activeConversationId:A.activeConversationId,state:Do(A.state),pendingAction:Zb(A.pendingAction),identityStatus:Do(A.identityStatus),nextCursor:A.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:Do(b.copy),actions:x,defaultRenderer:T,requestRender:()=>k(),onCleanup:W=>{d.push(W)}}),D=()=>{i=!1;let A=null;for(let I of t)if(I.renderHistoryView){try{A=I.renderHistoryView(L(b.getModel()))}catch(R){Fu("renderHistoryView",R),A=null}if(A)break}let W=!A||A.contains(b.element);return i=W,b.setDomRenderEnabled(W),A??b.element};function k(){if(!(!s||o||r)){r=!0;try{u();let A=D();if(A===l)return;let W=l;l=A,e.onElementChanged(A,W)}finally{r=!1}}}return s=!0,k(),{view:b,get element(){return l??b.element},requestRender:k,dispose:()=>{o=!0,u()}}}var Pk=null;function tv(){return Pk}var Lk=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),Hk=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),$u=e=>Hk.get(e)??"Conversation history is unavailable right now.";function Ik(e){if(e instanceof Xn)return e;if(e instanceof Oe){let t=Lk.get(e.code)??"unavailable";return new Xn(t,$u(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new Xn("unavailable",$u("unavailable"))}function nv(e){let t=()=>e.getClient?.()??e.client,n=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new Xn("unsupported_scope",$u("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(u){throw Ik(u)}},i=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let u=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),p=Sh(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:sa([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>i(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var Rk=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],ov={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function ju(e){if(!e)return ov;let t={...ov};for(let n of Rk){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var Wk="button:not([disabled])";function _c(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=ue("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=ue("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=ue("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},ue("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),ue("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),ue("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,i));for(let u of[s,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let d=ue("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(u=>{let p=!1,g=m=>{p||(p=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),u(m))};function y(m){if(m.key==="Escape"){m.preventDefault(),m.stopPropagation(),g(!1);return}if(m.key!=="Tab")return;let b=Array.from(l.querySelectorAll(Wk));if(b.length===0)return;let x=b[0],T=b[b.length-1],L=document.activeElement;m.shiftKey&&(L===x||!l.contains(L))?(m.preventDefault(),T.focus()):!m.shiftKey&&L===T&&(m.preventDefault(),x.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",m=>{m.target===d&&g(!1)}),s.addEventListener("click",()=>g(!1)),i.addEventListener("click",()=>g(!0)),e.host.appendChild(d),s.focus()})}import{parse as Bk,STR as Ok,OBJ as Dk}from"partial-json";function _k(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Nk(e,t){if(!_k(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 zu(){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=Bk(n,Ok|Dk),s=Nk(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Fk(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Uu(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=co.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function $k(){let e=zu();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rv(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 Nc(e){let t=rv(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 qu(e){let t=rv(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 jk=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Vu(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:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:u=jk}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let g=null,y=document.createElement("div");y.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,m.appendChild(b);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,m.appendChild(x),y.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let I=1;I<=5;I++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${I} star${I>1?"s":""}: ${u[I-1]}`),R.title=u[I-1],R.dataset.rating=String(I),R.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
|
-
`,_.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=`
|
|
48
|
+
`,R.addEventListener("click",()=>{g=I,L.forEach((z,q)=>{let Q=q<I;z.classList.toggle("selected",Q),z.setAttribute("aria-checked",q===I-1?"true":"false")})}),L.push(R),T.appendChild(R)}y.appendChild(T);let D=null;if(d){let I=document.createElement("div");I.className="persona-feedback-comment-container",D=document.createElement("textarea"),D.className="persona-feedback-comment",D.placeholder=s,D.rows=3,D.setAttribute("aria-label","Additional comments"),I.appendChild(D),y.appendChild(I)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),p.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=i,W.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let I=D?.value.trim()||void 0;await t(g,I),p.remove()}catch(I){W.disabled=!1,W.textContent=i,console.error("[CSAT Feedback] Failed to submit:",I)}}),k.appendChild(A),k.appendChild(W),y.appendChild(k),p.appendChild(y),p}function Ku(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:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:p="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 y=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,b.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,b.appendChild(T),m.appendChild(b);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let D=document.createElement("div");D.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=u;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=p,D.appendChild(k),D.appendChild(A);let W=document.createElement("div");W.className="persona-feedback-numbers";let I=[];for(let $=0;$<=10;$++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${$} out of 10`),J.textContent=String($),J.dataset.rating=String($),$<=6?J.classList.add("persona-feedback-detractor"):$<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{y=$,I.forEach((pe,we)=>{pe.classList.toggle("selected",we===$),pe.setAttribute("aria-checked",we===$?"true":"false")})}),I.push(J),W.appendChild(J)}L.appendChild(D),L.appendChild(W),m.appendChild(L);let R=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),$.appendChild(R),m.appendChild($)}let z=document.createElement("div");z.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=l,q.addEventListener("click",()=>{n?.(),g.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=i,Q.addEventListener("click",async()=>{if(y===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let $=R?.value.trim()||void 0;await t(y,$),g.remove()}catch($){Q.disabled=!1,Q.textContent=i,console.error("[NPS Feedback] Failed to submit:",$)}}),z.appendChild(q),z.appendChild(Q),m.appendChild(z),g.appendChild(m),g}var ri="persona-chat-history",qk=30*1e3,Vk=641,Kk={"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 Gk(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=Kk[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 Fc(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 Yk(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 Jk(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Gu=e=>!e||typeof e!="object"?{}:{...e},sv=e=>e.map(t=>({...t,streaming:!1})),iv=(e,t,n)=>{let o=e?.markdown?Ls(e.markdown):null,r=Vi(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 i=s.text??"",l=s.message.rawContent??null;if(t){let p=t.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});p!==null&&(i=p.text,p.persist||(s.message.__skipPersist=!0),p.resubmit&&!s.streaming&&n&&n())}let d=Lo()!==null,u;if(e?.postprocessMessage){let p=e.postprocessMessage({...s,text:i,raw:l??s.text??""});u=r?r(p):p}else if(o){let p=s.streaming?Bm(i):i,g=o(p);u=r&&d?r(g):g}else u=Ho(i);return u}};function av(e){let t=v("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,i=ce(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var Xk=(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},Qk=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:Xk(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Yu=(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=fa(t),r=()=>{Qh({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=Rc(o);let i=Wc.getForInstance(o.plugins),l=gy(e),d=[],u=!1,p=bb(()=>o),{plugin:g,teardown:y}=kb();o.components&&co.registerAll(o.components);let m=Gb(),x=o.persistState===!1?null:o.storageAdapter??_u(),T={},L=null,D,k=new Promise(a=>{D=a}),A=!1,W=a=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(a);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:h}=c;return h&&(A=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return a};if(x?.load)try{let a=x.load();if(a&&typeof a.then=="function")L=a.then(c=>W(c??{messages:[],metadata:{}}));else{let f=W(a??{messages:[],metadata:{}});f.metadata&&(T=Gu(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=W({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}L||D();let I=()=>T,R=a=>{T=a({...T})??{},pd()},z=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Oc],q=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[oi.message,oi.messageAndClick],Q=Dc({parsers:z,handlers:q,getSessionMetadata:I,updateSessionMetadata:R,emit:m.emit,documentRef:typeof document<"u"?document:null});Q.syncFromMetadata();let $=o.launcher?.enabled??!0,J=o.launcher?.autoExpand??!1,pe=o.autoFocusInput??!1,we=J,ve=$,he=o.layout?.header?.layout,ne=!1,ae=()=>pr(o),ie=()=>$||ae(),M=ae()?!1:$?J:!0,Z=!1,de=null,Ce=()=>{Z=!0,de&&clearTimeout(de),de=setTimeout(()=>{Z&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},fe=iv(o,Q,Ce),xe=o.features?.showReasoning??!0,Pe=o.features?.showToolCalls??!0,Le=o.features?.showEventStreamToggle??!1,Je=o.features?.scrollToBottom??{},Be=o.features?.scrollBehavior??{},Re=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",be=`${Re()}event-stream`,_e=Le?new Ha(be):null,gt=o.features?.eventStream?.maxEvents??2e3,Se=Le?new La(gt,_e):null,Ne=Le?new Ia:null,it=null,Kt=!1,zt=null,Un=0,Ze=!1,tt=null,vt=()=>{},Qt=()=>{},fo=()=>{},It=()=>{},No=()=>{},rs=()=>Kt||Ze&&tt==="panel";_e?.open().then(()=>Se?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let N={onCopy:a=>{m.emit("message:copy",a),O?.isClientTokenMode()&&O.submitMessageFeedback(a.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{m.emit("message:feedback",a),O?.isClientTokenMode()&&O.submitMessageFeedback(a.messageId,a.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(a)}},ee=o.statusIndicator??{},w=a=>a==="idle"?ee.idleText??_t.idle:a==="connecting"?ee.connectingText??_t.connecting:a==="connected"?ee.connectedText??_t.connected:a==="error"?ee.errorText??_t.error:a==="paused"?ee.pausedText??_t.paused:a==="resuming"?ee.resumingText??_t.resuming:_t[a];function S(a,c,f,h){if(h==="idle"&&f.idleLink){a.textContent="";let C=document.createElement("a");C.href=f.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=c,C.style.color="inherit",C.style.textDecoration="none",a.appendChild(C)}else a.textContent=c}let H=yb({config:o,showClose:ie()}),{wrapper:P,panel:B,pillRoot:G}=H.shell,X=H.panelElements,{container:K,body:V,messagesWrapper:le,starterSuggestions:ct,transcriptSuggestions:ot,suggestions:Ct,textarea:me,sendButton:ye,sendButtonWrapper:Zt,composerForm:ze,statusText:nn,welcomeHost:gn,welcomeIconHolder:zv,greetingHost:vn,introTitle:Uv,introSubtitle:qv,closeButton:We,iconHolder:xt,headerTitle:Fo,headerSubtitle:mr,header:Te,footer:Fe,actionsRow:Vv,rightActions:Kv}=X,ss=X.leftActions,ag=X.setSendButtonMode,oe=X.micButton,mo=X.micButtonWrapper,ft=X.attachmentButton,In=X.attachmentButtonWrapper,Mt=X.attachmentInput,qn=X.attachmentPreviewsContainer;K.classList.add("persona-relative"),V.classList.add("persona-relative");let Gv=12,si=()=>Je.label??"",Yv=()=>Je.iconName??"arrow-down",Jv=()=>Je.enabled!==!1,Cn=()=>Be.mode??"anchor-top",$o=()=>Cn()==="follow"||Cn()==="anchor-top"&&mi,ii=()=>Be.anchorTopOffset??16,Xv=()=>Be.restorePosition??"bottom",lg=()=>Be.pauseOnInteraction===!0,cg=()=>Be.showActivityWhilePinned!==!1,dg=()=>Be.announce===!0,Jc=()=>Be.scrollbar??"on-scroll",Rt=v("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 ai=v("span","persona-flex persona-items-center"),Xc=v("span",""),hr=v("span","");hr.setAttribute("data-persona-scroll-to-bottom-count",""),hr.style.display="none",Rt.append(ai,Xc,hr),K.appendChild(Rt);let Rn=v("div","persona-stream-anchor-spacer");Rn.setAttribute("aria-hidden","true"),Rn.setAttribute("data-persona-anchor-spacer",""),Rn.style.flexShrink="0",Rn.style.pointerEvents="none",Rn.style.height="0px",Rn.style.display="none",V.appendChild(Rn);let ho=v("div","persona-sr-only");ho.setAttribute("aria-live","polite"),ho.setAttribute("aria-atomic","true"),ho.setAttribute("role","status"),ho.setAttribute("data-persona-live-region",""),Object.assign(ho.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"}),K.appendChild(ho);let li=null,Oa=null,pg=a=>{!dg()||!a||(Oa=a,li===null&&(li=setTimeout(()=>{li=null,Oa&&dg()&&(ho.textContent=Oa),Oa=null},400)))},yr=()=>{let c=Fe.style.display==="none"?0:Fe.offsetHeight;Rt.style.bottom=`${c+Gv}px`};yr();let ug=()=>{let a=!!si();Rt.setAttribute("aria-label",si()||"Jump to latest"),Rt.title=si(),Rt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),ai.innerHTML="";let c=ce(Yv(),"14px","currentColor",2);c?(ai.appendChild(c),ai.style.display=""):ai.style.display="none",Xc.textContent=si(),Xc.style.display=a?"":"none"};ug();let mt=null,on=null,gg=null,fg=i.find(a=>a.renderHeader);if(fg?.renderHeader){let a=fg.renderHeader({config:o,defaultRenderer:()=>{let c=ur({config:o,showClose:ie()});return Ys(K,c,o),c.header},onClose:()=>at(!1,"user")});if(a){let c=Te;c&&(c.replaceWith(a),Te=a,H.header.element=a)}}let mg=()=>{it&&(V.style.display="none",Fe.parentNode?.insertBefore(it.element,Fe),it.update())},Qc=()=>{if(!Se)return;if(Kt=!0,it?mg():Ib().then(c=>{it||!Kt||!Se||(it=c.createEventStreamView({buffer:Se,getFullHistory:()=>Se.getAllFromStore(),onClose:()=>is(),config:o,plugins:i,getThroughput:()=>Ne?.getMetric()??{status:"idle"}}),mg())}).catch(()=>{is()}),Ge){Ge.style.boxShadow=`inset 0 0 0 1.5px ${pn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&Ge.classList.add(f))}let a=()=>{if(!Kt)return;let c=Date.now();c-Un>=200&&(it?.update(),Un=c),zt=requestAnimationFrame(a)};Un=0,zt=requestAnimationFrame(a),Ft(),m.emit("eventStream:opened",{timestamp:Date.now()})},is=()=>{if(Kt){if(Kt=!1,it&&it.element.remove(),V.style.display="",Ge){Ge.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(c=>c&&Ge.classList.remove(c))}zt!==null&&(cancelAnimationFrame(zt),zt=null),Ft(),m.emit("eventStream:closed",{timestamp:Date.now()})}},Ge=null;if(Le){let a=o.features?.eventStream?.classNames,c="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"+(a?.toggleButton?" "+a.toggleButton:"");Ge=v("button",c),Ge.style.width="28px",Ge.style.height="28px",Ge.style.color=pn.actionIconColor,Ge.type="button",Ge.setAttribute("aria-label","Event Stream"),Ge.title="Event Stream";let f=ce("activity","18px","currentColor",1.5);f&&Ge.appendChild(f);let h=X.clearChatButtonWrapper,C=X.closeButtonWrapper,E=h||C;E&&E.parentNode===Te?Te.insertBefore(Ge,E):Te.appendChild(Ge),Ge.addEventListener("click",()=>{Kt?is():Qc()})}let hg=a=>{let c=o.attachments;if(!c?.enabled)return;let f=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let C=a.querySelector("[data-persona-composer-form]");C?.parentNode?C.parentNode.insertBefore(f,C):a.insertBefore(f,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let C=v("input");C.type="file",C.setAttribute("data-persona-composer-attachment-input",""),C.accept=(c.allowedTypes??Bo).join(","),C.multiple=(c.maxFiles??4)>1,C.style.display="none",C.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),a.appendChild(C)}},Zc=i.find(a=>a.renderComposer),ci=!1,yg=a=>{if(!Zc?.renderComposer)return null;let c=o.composer,f=u?O.isStreaming():!1;return Zc.renderComposer({config:o,defaultRenderer:a,requestRender:()=>Iw(),storage:p(Zc.id),onSubmit:h=>{if(!O||O.isStreaming())return;let C=h.trim(),E=mt?.hasAttachments()??!1;if(!C&&!E)return;Qf();let j;E&&(j=[],j.push(...mt.getContentParts()),C&&j.push(Wo(C))),O.sendMessage(C,{contentParts:j}),E&&mt.clearAttachments()},streaming:f,disabled:f,openAttachmentPicker:()=>{Mt?.click()},models:c?.models,selectedModelId:c?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{gg?.()}:void 0})},bg=yg(()=>Js({config:o}).footer);bg&&(H.replaceComposer(bg),Fe=H.composer.footer,ci=!0);let vg=a=>{let c=(...te)=>{for(let se of te){let ge=a.querySelector(se);if(ge)return ge}return null},f=a.querySelector("[data-persona-composer-form]"),h=a.querySelector("[data-persona-composer-input]"),C=a.querySelector("[data-persona-composer-submit]"),E=a.querySelector("[data-persona-composer-mic]"),j=a.querySelector("[data-persona-composer-status]");f&&(ze=f),h&&(me=h),C&&(ye=C),E&&(oe=E,mo=E.parentElement),j&&(nn=j);let F=c("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let Y=c("[data-persona-composer-attachment-button]",".persona-attachment-button");Y&&(ft=Y,In=Y.parentElement),Mt=c("[data-persona-composer-attachment-input]",'input[type="file"]'),qn=c("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let U=c("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");U&&(Vv=U),ss=c(".persona-widget-composer__left-actions")};hg(Fe),vg(Fe);let di=rr(o,ae());di&&(le.style.maxWidth=di,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",vn.style.maxWidth=di,vn.style.marginLeft="auto",vn.style.marginRight="auto",vn.style.width="100%",ct.style.maxWidth=di,ot.style.maxWidth=di,ot.style.marginLeft="auto",ot.style.marginRight="auto",ot.style.width="100%");let Cg=()=>{let a=rr(o,ae());if(!(!a||ae()))for(let c of[ze,Ct,qn,nn])c&&(c.style.maxWidth=a,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Cg();let wg=()=>{!o.attachments?.enabled||!Mt||!qn||(mt?mt.remountPreviews(qn):(mt=_s.fromConfig(o.attachments),mt.setPreviewsContainer(qn)),Mt.addEventListener("change",a=>{let c=a.target;mt?.handleFileSelect(c.files),c.value=""}),K.querySelector(".persona-attachment-drop-overlay")||K.appendChild(av(o.attachments.dropOverlay)))};wg();let Qv=()=>on?.prefetch(),xg=()=>{if(!(!o.contextMentions?.enabled||!me)&&(on=ny({config:o,textarea:me,anchor:ze??me,getMessages:()=>O.getMessages(),liveRegionHost:K}),on)){let a=me;a.parentElement?.insertBefore(on.contextRow,a);let c=on.affordanceButtons;for(let f=c.length-1;f>=0;f--){let h=c[f];ss?ss.insertBefore(h,ss.firstChild):ze?.appendChild(h)}}};xg(),(()=>{let a=o.layout?.slots??{},c=h=>{switch(h){case"body-top":return V.querySelector("[data-persona-intro-card]");case"messages":return le;case"footer-top":return Ct;case"composer":return ze;case"footer-bottom":return nn;default:return null}},f=(h,C)=>{switch(h){case"header-left":case"header-center":case"header-right":if(h==="header-left")Te.insertBefore(C,Te.firstChild);else if(h==="header-right")Te.appendChild(C);else{let E=Te.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(C,E.nextSibling):Te.appendChild(C)}break;case"body-top":{let E=V.querySelector("[data-persona-intro-card]");E?E.replaceWith(C):V.insertBefore(C,V.firstChild);break}case"body-bottom":V.appendChild(C);break;case"footer-top":Ct.replaceWith(C);break;case"footer-bottom":nn.replaceWith(C);break;default:break}};for(let[h,C]of Object.entries(a))if(C)try{let E=C({config:o,defaultContent:()=>c(h)});E&&f(h,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${h}":`,E)}})();let Sg=a=>{let f=a.target.closest('button[data-expand-header="true"]');if(!f)return;let h=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-bubble-type");if(E==="reasoning")Zs.has(C)?Zs.delete(C):Zs.add(C),vb(C,h);else if(E==="tool")ei.has(C)?ei.delete(C):ei.add(C),Cb(C,h,o);else if(E==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",Y=Zr.get(C)??F;Zr.set(C,!Y),Ab(C,h,o)}xn.delete(C)};le.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Sg(a))}),le.addEventListener("keydown",a=>{let c=a.target;(a.key==="Enter"||a.key===" ")&&c.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Sg(a))}),le.addEventListener("copy",a=>{let{clipboardData:c}=a;if(!c)return;let f=le.getRootNode(),h=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!h||h.isCollapsed)return;let C=h.toString(),E=Hy(C);!E||E===C||(c.setData("text/plain",E),a.preventDefault())});let ed=new Map,Ag=null,Tg="idle",Zv={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},eC=(a,c)=>{let{icon:f,label:h}=Zv[c];a.setAttribute("aria-label",h),a.title=h,a.setAttribute("aria-pressed",c==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",c!=="idle"),a.classList.toggle("persona-message-action-loading",c==="loading");let C=ce(f,14,"currentColor",2);C&&(a.innerHTML="",a.appendChild(C))},Eg=()=>{le.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let h=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;eC(c,h&&h===Ag?Tg:"idle")})};le.addEventListener("click",a=>{let f=a.target.closest(".persona-message-action-btn[data-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.closest("[data-actions-for]");if(!h)return;let C=h.getAttribute("data-actions-for");if(!C)return;let E=f.getAttribute("data-action");if(E==="copy"){let F=O.getMessages().find(Y=>Y.id===C);if(F&&N.onCopy){let Y=F.content||"";navigator.clipboard.writeText(Y).then(()=>{f.classList.add("persona-message-action-success");let U=ce("check",14,"currentColor",2);U&&(f.innerHTML="",f.appendChild(U)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let te=ce("copy",14,"currentColor",2);te&&(f.innerHTML="",f.appendChild(te))},2e3)}).catch(U=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",U)}),N.onCopy(F)}}else if(E==="read-aloud")O.toggleReadAloud(C);else if(E==="upvote"||E==="downvote"){let F=(ed.get(C)??null)===E,Y=E==="upvote"?"thumbs-up":"thumbs-down";if(F){ed.delete(C),f.classList.remove("persona-message-action-active");let U=ce(Y,14,"currentColor",2);U&&(f.innerHTML="",f.appendChild(U))}else{let U=E==="upvote"?"downvote":"upvote",te=h.querySelector(`[data-action="${U}"]`);if(te){te.classList.remove("persona-message-action-active");let qt=ce(U==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qt&&(te.innerHTML="",te.appendChild(qt))}ed.set(C,E),f.classList.add("persona-message-action-active");let se=ce(Y,14,"currentColor",2);se&&(se.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(se)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Ye=O.getMessages().find(bt=>bt.id===C);Ye&&N.onFeedback&&N.onFeedback({type:E,messageId:Ye.id,message:Ye})}}}),le.addEventListener("click",a=>{let f=a.target.closest("button[data-approval-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.closest(".persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-approval-action");if(!E)return;let j=E==="approve"?"approved":"denied",Y=O.getMessages().find(te=>te.id===C);if(!Y?.approval)return;let U=h.querySelector("[data-approval-buttons]");U&&U.querySelectorAll("button").forEach(se=>{se.disabled=!0,se.style.opacity="0.5",se.style.cursor="not-allowed"}),Y.approval.toolType==="webmcp"?O.resolveWebMcpApproval(C,j):O.resolveApproval(Y.approval,j)});let De=null,pi=null,br=()=>{},ui="none",Da=null,Vn={artifacts:[],selectedId:null},yo=!1,Kn=!1,gi=!1,as=!1,Mg=()=>as||Vn.artifacts.some(a=>Io(o.features?.artifacts,a)==="panel"),_a=()=>Vn.artifacts.length>0&&!yo&&Mg(),rt={current:null},td=(a,c)=>{let f=O.getArtifactById(c),h=f?.markdown,C=f?.title||"artifact",E=f?.file,j=f?.artifactType??"markdown";if(!h){let U=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(U){let se=O.getMessages().find(ge=>ge.id===U);if(se?.rawContent)try{let ge=JSON.parse(se.rawContent);h=ge?.props?.markdown,C=ge?.props?.title||C,ge?.props?.file&&typeof ge.props.file=="object"&&(E=ge.props.file),!f&&typeof ge?.props?.artifactType=="string"&&(j=ge.props.artifactType)}catch{}}}return{markdown:h,title:C,file:E,artifactType:j}};le.addEventListener("click",a=>{let f=a.target.closest("[data-download-artifact]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-download-artifact");if(!h||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:h})===!0)return;let{markdown:E,title:j,file:F}=td(f,h);E&&ic(sc({title:j,markdown:E,file:F}))}),le.addEventListener("click",a=>{let f=a.target.closest("[data-artifact-custom-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-artifact-custom-action");if(!h)return;let C=f.closest("[data-artifact-inline]"),E=C?null:f.closest("[data-open-artifact]"),j=C?C.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,Y=(C?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(bt=>bt.id===h);if(!Y)return;let{markdown:U,title:te,file:se,artifactType:ge}=td(f,j??""),Ye={artifactId:j,title:te,artifactType:ge,markdown:U,file:se};try{Promise.resolve(Y.onClick(Ye)).catch(()=>{})}catch{}}),le.addEventListener("click",a=>{let f=a.target.closest("[data-copy-artifact]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-copy-artifact");if(!h)return;let C=O.getArtifactById(h),E="";if(C)E=va(C);else{let{markdown:j,file:F,artifactType:Y}=td(f,h);Y==="markdown"&&(E=va({id:h,artifactType:"markdown",status:"complete",markdown:j??"",...F?{file:F}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let j=ce("check",16,"currentColor",2);j&&(f.replaceChildren(j),setTimeout(()=>{let F=ce("copy",16,"currentColor",2);F&&f.replaceChildren(F)},1500))}).catch(()=>{})}),le.addEventListener("click",a=>{let f=a.target.closest("[data-expand-artifact-inline]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-expand-artifact-inline");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(yo=!1,as=!0,Kn=!0,gi=!0,O.selectArtifact(h),bo())}),le.addEventListener("click",a=>{let c=a.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let h=f.getAttribute("data-open-artifact");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(a.preventDefault(),a.stopPropagation(),yo=!1,as=!0,O.selectArtifact(h),bo())}),le.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let c=a.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),c.click())});let ls=X.composerOverlay,cs=(a,c,f)=>{let h=c.trim();if(!h||!rt.current)return;let C=a.getAttribute("data-tool-call-id")??"",E=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:E,source:f.source},bubbles:!0,composed:!0})),jr(ls,C);let j=rt.current.getMessages().find(F=>F.toolCall?.id===C);j?.agentMetadata?.awaitingLocalTool?rt.current.resolveAskUserQuestion(j,f.structured??h):rt.current.sendMessage(h)},vr=a=>{let c=rt.current;if(!c)return;let f=a.getAttribute("data-tool-call-id")??"",h=c.getMessages().find(C=>C.toolCall?.id===f);h&&c.persistAskUserQuestionProgress(h,{answers:_l(a,h),currentIndex:$n(a)})},kg=a=>Object.entries(a).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),nd=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=$n(a),f=Is(a);if(c>=f-1)return;let h=rt.current?.getMessages().find(C=>C.toolCall?.id===a.getAttribute("data-tool-call-id"));h&&(Nl(a,h,o,c+1),vr(a))};ls.addEventListener("click",a=>{let f=a.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let C=f.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),C==="dismiss"){let E=h.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),jr(ls,E);let j=rt.current?.getMessages().find(F=>F.toolCall?.id===E);j?.agentMetadata?.awaitingLocalTool&&(rt.current?.markAskUserQuestionResolved(j),rt.current?.resolveAskUserQuestion(j,"(dismissed)"));return}if(C==="pick"){let E=f.getAttribute("data-option-label");if(!E)return;let j=h.getAttribute("data-multi-select")==="true",F=er(h);if(F&&j){let Y=$r(h)[$n(h)],U=new Set(Array.isArray(Y)?Y:[]);U.has(E)?U.delete(E):U.add(E),tr(h,Array.from(U)),vr(h);return}if(F){tr(h,E),vr(h),nd(h);return}if(j){let Y=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Y?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Y);let U=h.querySelector('[data-ask-user-action="submit-multi"]');U&&(U.disabled=xp(h).length===0);return}cs(h,E,{source:"pick",values:[E]});return}if(C==="submit-multi"){let E=xp(h);if(E.length===0)return;cs(h,E.join(", "),{source:"multi",values:E});return}if(C==="open-free-text"){let E=h.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(C==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(C==="submit-free-text"){let j=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!j.trim())return;if(er(h)){tr(h,j.trim()),vr(h),nd(h);return}cs(h,j,{source:"free-text"});return}if(C==="next"||C==="back"){if(!rt.current)return;let E=h.getAttribute("data-tool-call-id")??"",j=rt.current.getMessages().find(se=>se.toolCall?.id===E);if(!j)return;let Y=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(Y){let se=$r(h)[$n(h)];(typeof se!="string"||se!==Y)&&tr(h,Y)}let U=C==="next"?1:-1,te=$n(h)+U;Nl(h,j,o,te),vr(h);return}if(C==="submit-all"){if(!rt.current)return;let E=h.getAttribute("data-tool-call-id")??"",j=rt.current.getMessages().find(se=>se.toolCall?.id===E);if(!j)return;let Y=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";Y&&tr(h,Y);let U=_l(h,j);rt.current.persistAskUserQuestionProgress(j,{answers:U,currentIndex:$n(h)});let te=kg(U);cs(h,te||"(submitted)",{source:"submit-all",structured:U});return}if(C==="skip"){if(!rt.current)return;let E=h.getAttribute("data-tool-call-id")??"",j=rt.current.getMessages().find(ge=>ge.toolCall?.id===E);if(!j)return;let F=er(h),Y=$n(h),U=Is(h),te=Y>=U-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),jr(ls,E),j.agentMetadata?.awaitingLocalTool&&(rt.current.markAskUserQuestionResolved(j),rt.current.resolveAskUserQuestion(j,"(dismissed)"));return}tr(h,"");let se=h.querySelector('[data-ask-free-text-input="true"]');if(se&&(se.value=""),te){let ge=_l(h,j),Ye=kg(ge);cs(h,Ye||"(skipped)",{source:"submit-all",structured:ge});return}Nl(h,j,o,Y+1),vr(h);return}}),ls.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let f=a.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;a.preventDefault();let C=f.value;if(C.trim()){if(er(h)){tr(h,C.trim()),vr(h),nd(h);return}cs(h,C,{source:"free-text"})}});let Pg=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let c=a.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=ls.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let h=Number(a.key),E=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[h-1];E&&(a.preventDefault(),E.click())};document.addEventListener("keydown",Pg);let Qn=null,ht=null,fi=null,Na=null,od=()=>{},Lg=!1,Fa="",$a="";function rd(){Na?.(),Na=null}let tC=()=>{let a=Mi&&Cs?.isConnected?Cs:null,c=a?a.getBoundingClientRect().width:0;return c<=0?200:c+360},Hg=()=>{if(!Qn||!ht)return;let a=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||f){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let h=Qn.firstElementChild;if(!h||h===ht)return;let C=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${C}px`,ht.style.zIndex="5";let E=Wu(Qn,c),j=h.offsetWidth+E/2-C/2;ht.style.left=`${Math.max(0,j)}px`},ja=()=>{},nC=()=>{let a=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||a.innerWidth>f?!1:$||wt(o)},za=()=>!un(o)||!_a()||e.classList.contains("persona-artifact-narrow-host")||nC()||(e.ownerDocument.defaultView??window).innerWidth<Vk?"none":Iu(o)?"detached":"welded",bo=()=>{if(!De||!un(o))return;Ra(e,o),Wa(e,o),ja();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=B.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=a);let f=_a();De.setVisible(f),De.update(Vn),yo?(De.setMobileOpen(!1),De.element.classList.add("persona-hidden"),De.backdrop?.classList.add("persona-hidden"),Kn=!1,gi=!1):Vn.artifacts.length>0&&Mg()?(De.element.classList.remove("persona-hidden"),De.setMobileOpen(!0)):(De.setMobileOpen(!1),De.element.classList.add("persona-hidden"),De.backdrop?.classList.add("persona-hidden"),Kn=!1,gi=!1);let h=o.features?.artifacts?.layout?.showExpandToggle===!0;if(De.setExpandToggleVisible(h),De.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),De.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),De.setCustomActions(o.features?.artifacts?.toolbarActions??[]),De.setTabFade(o.features?.artifacts?.layout?.tabFade),De.setRenderTabBar(o.features?.artifacts?.renderTabBar),!h&&!gi&&(Kn=!1),Kn!==Lg){let E=De.element;Kn?(Fa=E.style.width,$a=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(Fa&&(E.style.width=Fa),$a&&(E.style.maxWidth=$a),Fa="",$a=""),Lg=Kn}e.classList.toggle("persona-artifact-expanded",Kn),De.setExpanded(Kn);let C=za();C!==ui&&(ui=C,br()),od()};if(un(o)){B.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(K),De=Rb(o,{onSelect:f=>rt.current?.selectArtifact(f),onDismiss:()=>{yo=!0,bo()},onToggleExpand:()=>{let f=!Kn,h=Vn.selectedId??Vn.artifacts[Vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:h,expanded:f})!==!0&&(Kn=f,f||(gi=!1),bo())}}),De.element.classList.add("persona-hidden"),Qn=c,c.appendChild(a),c.appendChild(De.element),De.backdrop&&B.appendChild(De.backdrop),B.appendChild(c),od=()=>{if(!Qn||!De)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){fi?.(),fi=null,rd(),ht&&(ht.remove(),ht=null),De.element.style.removeProperty("width"),De.element.style.removeProperty("maxWidth");return}if(!ht){let h=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");h.setAttribute("role","separator"),h.setAttribute("aria-orientation","vertical"),h.setAttribute("aria-label","Resize artifacts panel"),h.tabIndex=0;let C=e.ownerDocument,E=C.defaultView??window,j=F=>{if(!De||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;F.preventDefault(),rd();let Y=F.clientX,U=De.element.getBoundingClientRect().width,te=o.features?.artifacts?.layout,se=Ye=>{let bt=Qn.getBoundingClientRect().width,qt=e.classList.contains("persona-artifact-welded-split"),yn=Wu(Qn,E),Tt=qt?0:h.getBoundingClientRect().width||6,kt=U-(Ye.clientX-Y),_=Ub(kt,bt,yn,Tt,te?.resizableMinWidth,te?.resizableMaxWidth,tC());De.element.style.width=`${_}px`,De.element.style.maxWidth="none",Hg()},ge=()=>{C.removeEventListener("pointermove",se),C.removeEventListener("pointerup",ge),C.removeEventListener("pointercancel",ge),Na=null;try{h.releasePointerCapture(F.pointerId)}catch{}};Na=ge,C.addEventListener("pointermove",se),C.addEventListener("pointerup",ge),C.addEventListener("pointercancel",ge);try{h.setPointerCapture(F.pointerId)}catch{}};h.addEventListener("pointerdown",j),ht=h,Qn.insertBefore(h,De.element),fi=()=>{h.removeEventListener("pointerdown",j)}}if(ht){let h=_a();ht.classList.toggle("persona-hidden",!h),Hg()}},ja=()=>{if(!$||!De||(o.launcher?.sidebarMode??!1)||wt(o)&&Pn(o).reveal==="emerge")return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=E||!Ob(o,$))return;let j=o.launcher?.width??o.launcherWidth??jn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_a()?(B.style.width=F,B.style.maxWidth=F):(B.style.width=j,B.style.maxWidth=j)},typeof ResizeObserver<"u"&&(pi=new ResizeObserver(()=>{bo()}),pi.observe(B))}else B.appendChild(K);ae()&&G&&(X.peekBanner&&G.appendChild(X.peekBanner),G.appendChild(Fe)),e.appendChild(P),G&&e.appendChild(G);let sd=()=>{if(ae()){B.style.width="100%",B.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},cn=P.dataset.state==="expanded",$i=Lt.expandedSize??"anchored";if(!(cn&&$i!=="fullscreen")){K.style.background="",K.style.border="",K.style.borderRadius="",K.style.overflow="",K.style.boxShadow="";return}let ji=o.theme?.components?.panel,wm=Kr(o),Pl=(_r,Hl)=>_r==null||_r===""?Hl:dn(wm,_r)??_r,Ot="1px solid var(--persona-border)",up="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Ll="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";K.style.background="var(--persona-surface, #ffffff)",K.style.border=Pl(ji?.border,Ot),K.style.borderRadius=Pl(ji?.borderRadius,Ll),K.style.boxShadow=Pl(ji?.shadow,up),K.style.overflow="hidden";return}let a=wt(o),c=o.launcher?.sidebarMode??!1,f=a||c||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,C=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,j=Kr(o),F=(Lt,cn)=>Lt==null||Lt===""?cn:dn(j,Lt)??Lt,Y=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,te=o.launcher?.mobileBreakpoint??640,se=Y.innerWidth<=te,ge=U&&se&&$,Ye=a&&U&&se,bt=o.launcher?.position??"bottom-left",qt=bt==="bottom-left"||bt==="top-left",yn=o.launcher?.zIndex??Jt,Tt="var(--persona-panel-border, 1px solid var(--persona-border))",kt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=C&&!ge&&!Ye;ke?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let He=ke?Tt:c||ge?"none":Tt,Ae=ke?kt:ge?"none":c?qt?"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))":h?"none":kt;a&&!ge&&!ke&&(Ae="none",He="none");let Et=ke?_:c||ge?"0":_,dt=F(E?.border,He),Vt=F(E?.shadow,Ae),lt=F(E?.borderRadius,Et),an=za(),Gt=an==="detached",$t=an==="welded";e.classList.toggle("persona-artifact-detached-split",Gt),e.classList.toggle("persona-artifact-welded-split",$t);let Ie="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)))))",Ee=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&un(o)&&Iu(o)&&h&&!a;e.classList.toggle("persona-artifact-chat-flush",Ee);let Wt=Gt||Ee?"none":Vt,pt=Gt?Tt:$t?"none":dt,qe=Gt?_:lt;Ee&&(pt="none",qe="0");let Bt=E?.borderRadius!=null&&E.borderRadius!=="",Pt=Ee&&!Bt?"0":lt,en=V.scrollTop;e.style.cssText="",P.style.cssText="",B.style.cssText="",K.style.cssText="",V.style.cssText="",ci||(Fe.style.cssText=""),Kt&&(V.style.display="none"),(f||h)&&(e.style.minWidth="0");let Nn=()=>{if(en<=0)return;(V.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(V.scrollTop===en)return;let cn=V.scrollHeight-V.clientHeight;cn<=0||(V.scrollTop=Math.min(en,cn))})};if(ge){P.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"),P.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 Xs=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: ${yn} !important;
|
|
59
59
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
60
|
-
`,
|
|
60
|
+
`,B.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 Xs=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
|
+
`,K.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 Xs=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
|
+
`,V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",Fe.style.flexShrink="0",ne=!0,Nn();return}let tn=o?.launcher?.width??o?.launcherWidth??jn;if(!c&&!a)h&&f?(B.style.width="100%",B.style.maxWidth="100%"):(B.style.width=tn,B.style.maxWidth=tn);else if(a)if(Pn(o).reveal==="emerge"&&!C){let cn=Pn(o).width;B.style.width=cn,B.style.maxWidth=cn}else B.style.width="100%",B.style.maxWidth="100%";if(ja(),B.style.boxShadow=Wt,B.style.borderRadius=Pt,Gt?B.style.border="none":$t&&(B.style.border=dt),K.style.border=pt,K.style.borderRadius=qe,K.style.boxShadow=Gt&&!Ee?Ie:"",Ee&&(K.style.background="transparent",V.style.background="transparent",Fe.style.background="transparent",Fe.style.borderTop="none"),$t){let Lt=o.features?.artifacts?.layout;Da=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||lt}else Da=null;if(a&&!ge&&!ke&&!Gt&&!$t&&E?.border===void 0&&(K.style.border="none",Pn(o).side==="right"?K.style.borderLeft="1px solid var(--persona-border)":K.style.borderRight="1px solid var(--persona-border)"),a&&!ge&&$t&&E?.border===void 0&&(Pn(o).side==="right"?B.style.borderLeft="1px solid var(--persona-border)":B.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",h&&(e.style.width="100%"),P.style.display="flex",P.style.flexDirection="column",P.style.flex="1 1 0%",P.style.minHeight="0",P.style.maxHeight="100%",P.style.height="100%",h&&(P.style.overflow="hidden"),B.style.display="flex",B.style.flexDirection="column",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.maxHeight="100%",B.style.height="100%",Gt||(B.style.overflow="hidden"),K.style.display="flex",K.style.flexDirection="column",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.maxHeight="100%",K.style.overflow="hidden",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.overflowY="auto",Fe.style.flexShrink="0"),h&&(ke||Gt||Ee)&&!a&&(Ee||(P.style.padding="var(--persona-panel-inset)"),P.style.background="var(--persona-panel-canvas-bg)"),P.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"),!c&&!h&&!a&&(Ln[bt]??Ln["bottom-right"]).split(" ").forEach(cn=>P.classList.add(cn)),c){let Lt=o.launcher?.sidebarWidth??"420px";C?P.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: ${Lt} !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: ${yn} !important;
|
|
96
|
+
${qt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
97
|
+
`:P.style.cssText=`
|
|
98
98
|
position: fixed !important;
|
|
99
99
|
top: 0 !important;
|
|
100
100
|
bottom: 0 !important;
|
|
101
|
-
width: ${
|
|
101
|
+
width: ${Lt} !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: ${yn} !important;
|
|
109
|
+
${qt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
110
|
+
`,B.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 Xs=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
118
118
|
min-height: 0 !important;
|
|
119
119
|
margin: 0 !important;
|
|
120
120
|
padding: 0 !important;
|
|
121
|
-
box-shadow: ${
|
|
122
|
-
border-radius: ${
|
|
123
|
-
${
|
|
124
|
-
`,
|
|
121
|
+
box-shadow: ${Wt} !important;
|
|
122
|
+
border-radius: ${Pt} !important;
|
|
123
|
+
${Gt?"border: none !important;":$t?`border: ${dt} !important;`:""}
|
|
124
|
+
`,B.style.setProperty("width","100%","important"),B.style.setProperty("max-width","100%","important"),K.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 Xs=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: ${qe} !important;
|
|
134
|
+
border: ${pt} !important;
|
|
135
|
+
${Gt&&!Ee?`box-shadow: ${Ie} !important;`:""}
|
|
136
|
+
${Ee?"background: transparent !important;":""}
|
|
137
|
+
`,ci||(Fe.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(!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:
|
|
144
|
-
`)}}];function
|
|
145
|
-
${s.map(
|
|
141
|
+
${Ee?"background: transparent !important;":""}
|
|
142
|
+
`)}if(!h&&!a){let Lt="max-height: -moz-available !important; max-height: stretch !important;",cn=c?"":"padding-top: 1.25em !important;",$i=c?"":`z-index: ${o.launcher?.zIndex??Jt} !important;`;P.style.cssText+=Lt+cn+$i}Nn()},id=()=>{e.style.setProperty("--persona-content-max-width",rr(o,ae()))},Ig=()=>{if(ae())return;let a=wt(o),c=o.launcher?.sidebarMode??!1;if(a||c||(o.launcher?.fullHeight??!1)||!$)return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=E)return;let j=h.innerHeight,F=64,Y=o.launcher?.heightOffset??0,U=Math.max(200,j-F),te=Math.min(640,U);B.style.height=`${Math.max(200,te-Y)}px`};sd(),$s(e,o),Ra(e,o),Wa(e,o),id(),br=()=>{sd(),Ig(),$s(e,o),Ra(e,o),Wa(e,o),id(),Da?e.style.setProperty("--persona-artifact-welded-outer-radius",Da):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Qt(),vt()};let Me=[];Me.push(()=>{d.forEach(a=>a()),l.destroy()}),Me.push(()=>{document.removeEventListener("keydown",Pg)}),Me.push(()=>{li!==null&&clearTimeout(li)});let Zn=null,eo=null;Me.push(()=>{Zn?.(),Zn=null,eo?.(),eo=null}),pi&&Me.push(()=>{pi?.disconnect(),pi=null}),Me.push(()=>{fi?.(),fi=null,rd(),ht&&(ht.remove(),ht=null),De?.element.style.removeProperty("width"),De?.element.style.removeProperty("maxWidth"),De?.destroy()}),Le&&Me.push(()=>{zt!==null&&(cancelAnimationFrame(zt),zt=null),it?.destroy(),it=null,Se?.destroy(),Se=null,_e=null});let Cr=null,Rg=()=>{Cr&&(Cr(),Cr=null),o.colorScheme==="auto"&&(Cr=ma(()=>{$s(e,o)}))};Rg(),Me.push(()=>{Cr&&(Cr(),Cr=null)}),Me.push(y);let Ua=o.features?.streamAnimation;if(Ua?.type&&Ua.type!=="none"){let a=Vs(Ua.type,Ua.plugins);a&&(hc(a,e),Me.push(()=>Vy(e)))}let vo=Ea(Ct),Wg=Ea(ct),Bg=Ea(ot),wr=[vo,Wg,Bg];Me.push(()=>{wr.forEach(a=>a.destroy())});let xr=null,O,Sr=null,Og=!1,Dg=0,_g=null,Ng=a=>a.reduce((c,f)=>f.role==="user"?c+1:c,0),Fg=a=>{for(let c=a.length-1;c>=0;c--)if(Rs(a[c]))return a[c].id??null;return null},$g=!1,oC=()=>{$g||o.debug!==!0||($g=!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".'))},jg=!1,zg=!1,Ug=(a,c)=>{jg||o.debug!==!0||!c.enabled||c.expose||Og||zg&&(O.isStreaming()||a.some(Rs)||(jg=!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.")))},ds=a=>{if(!O)return;let c=a??O.getMessages(),f=U=>{U.render([],O,me,c)},h=U=>{wr.forEach(te=>{te!==U&&f(te)})};Sr&&(Ng(c)>Dg||Fg(c)!==_g)&&(Sr=null);let C=nr(o);Ug(c,C);let E=C.enabled?Tp(c):null,j=Sr??E,F=Sr?"host":"agent";if(j){let U=o.suggestions?.followUps,te=U?.placement??(U?"auto":"composer"),ge=(te==="auto"?ae()?"composer":"after-message":te)==="after-message"?Bg:vo;h(ge),ge.render(j,O,me,c,o.suggestionChipsConfig,{source:F,surface:"followUp",variant:U?.variant??"chip",behavior:U?.behavior??"send",overflow:U?.overflow??"wrap",maxItems:U?.maxItems??4,config:o,plugins:i});return}if(c.some(U=>U.role==="user")){wr.forEach(f);return}let Y=o.suggestions?.starters;if(Y){let U=Qr(gr(o),c),te=Y.placement??"auto",se=te==="auto"?U?"welcome":"composer":te;if(se==="welcome"&&!U){oC(),wr.forEach(f);return}let ge=se==="welcome"?Wg:vo;h(ge),ge.render(Y.items??o.suggestionChips,O,me,c,o.suggestionChipsConfig,{surface:"starter",variant:Y.variant??"card",behavior:Y.behavior??"send",overflow:Y.overflow??"wrap",maxItems:Y.maxItems??4,config:o,plugins:i});return}h(vo),vo.render(o.suggestionChips,O,me,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:i})},qg=()=>{Sr&&(Sr=null,ds())},rC=a=>{let c=Array.isArray(a)?[...a]:[];if(!c.length){qg();return}let f=O?O.getMessages():[];Sr=c,Og=!0,Dg=Ng(f),_g=Fg(f),ds(f)},wn=!1,xn=Wy(),ps=new Map,Ar=new Map,jo=new Map,ad=0,sC=Lo()!==null,Sn=Ny(),An=0,zo=null,fn=!1,qa=!1,Uo=0,Nt=null,Tr=null,ld=!1,us=!1,Er=null,mi=!0,Va=!1,gs=null,Ka=!1,Mr=()=>{Ka=!0,cC()},cd=null,iC=4,Co=24,aC=80,lC=1e3,wo=null,Vg=()=>{e.setAttribute("data-persona-scrollbar",Jc()),Jc()!=="on-scroll"&&(wo!==null&&clearTimeout(wo),wo=null,V.removeAttribute("data-persona-scrollbar-visible"))},cC=()=>{Jc()==="on-scroll"&&(V.setAttribute("data-persona-scrollbar-visible",""),wo!==null&&clearTimeout(wo),wo=setTimeout(()=>{wo=null,Jr(V,Co)&&V.removeAttribute("data-persona-scrollbar-visible")},lC))};Vg(),Me.push(()=>{wo!==null&&clearTimeout(wo)});let dd=new Map,$e={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Kg=o.voiceRecognition?.autoResume??!1,xo=a=>{m.emit("voice:state",{active:$e.active,source:a,timestamp:Date.now()})},Gn=()=>{R(a=>({...a,voiceState:{active:$e.active,timestamp:Date.now(),manuallyDeactivated:$e.manuallyDeactivated}}))},dC=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Gu(T.voiceState),c=!!a.active,f=Number(a.timestamp??0);$e.manuallyDeactivated=!!a.manuallyDeactivated,c&&Date.now()-f<qk&&setTimeout(()=>{$e.active||($e.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{$e.active=O.isVoiceActive(),xo("restore"),O.isVoiceActive()&&Ts()}):Tl("restore"))},1e3)},pC=()=>O?sv(O.getMessages()).filter(a=>!a.__skipPersist):[],Ga=null,Gg=(a,c)=>{typeof console<"u"&&console.error(a,c)},Ya=(a,c)=>{let f=()=>{try{let j=a();return!j||typeof j.then!="function"?null:Promise.resolve(j).catch(F=>{Gg(c,F)})}catch(j){return Gg(c,j),null}},h=Ga,C=h?h.then(()=>f()??void 0):f();if(!C)return;let E=C.finally(()=>{Ga===E&&(Ga=null)});Ga=E};function pd(a){if(!x?.save)return;let f={messages:a?sv(a):O?pC():[],metadata:T,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};Ya(()=>x.save(f),"[AgentWidget] Failed to persist state:")}let fs=null,Yg=()=>P.querySelector("#persona-scroll-container")||V,ms=()=>{fs!==null&&(cancelAnimationFrame(fs),fs=null),fn=!1},Jg=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),qa=!1,ms()},uC=()=>wn&&gd()&&(Cn()!=="anchor-top"||cg()),ud=()=>{let a=si()||"Jump to latest",c=uC();Rt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Uo>0?(hr.textContent=String(Uo),hr.style.display="",Rt.setAttribute("aria-label",`${a} (${Uo} new)`)):(hr.textContent="",hr.style.display="none",Rt.setAttribute("aria-label",c?`${a} (response streaming below)`:a))},Xg=()=>{Uo!==0&&(Uo=0,ud())},gC=()=>{let a=Nt?.spacerHeight??0;return a<=0?Jr(V,Co):Za(a)-V.scrollTop-V.clientHeight<=Co},gd=()=>$o()?!Sn.isFollowing():!gC(),fd=()=>!!O&&O.getMessages().length>0,Ft=()=>{if(!Jv()||rs()){Rt.parentNode&&Rt.remove(),Rt.style.display="none";return}Rt.parentNode!==K&&K.appendChild(Rt),yr();let c=po(V)>0&&gd()&&fd();c?ud():Xg(),Rt.style.display=c?"":"none"},hi=()=>{Sn.pause()&&(Jg(),Ft())},mn=()=>{Sn.resume(),Xg(),Ft()},qo=(a=!1)=>{$o()&&fd()&&Sn.isFollowing()&&(!a&&!wn||(zo!==null&&(cancelAnimationFrame(zo),zo=null),qa=!0,zo=requestAnimationFrame(()=>{zo=null,qa=!1,Sn.isFollowing()&&fC(Yg(),a?220:140)})))},Qg=(a,c,f,h=()=>!0)=>{let C=a.scrollTop,E=c(),j=E-C;if(ms(),Math.abs(j)<1){fn=!0,a.scrollTop=E,An=a.scrollTop,fn=!1;return}let F=performance.now();fn=!0;let Y=te=>1-Math.pow(1-te,3),U=te=>{if(!h()){ms();return}let se=c();se!==E&&(E=se,j=E-C);let ge=te-F,Ye=Math.min(ge/f,1),bt=Y(Ye),qt=C+j*bt;a.scrollTop=qt,An=a.scrollTop,Ye<1?fs=requestAnimationFrame(U):(a.scrollTop=E,An=a.scrollTop,fs=null,fn=!1)};fs=requestAnimationFrame(U)},fC=(a,c=500)=>{let f=po(a)-a.scrollTop;if(Math.abs(f)<1){An=a.scrollTop;return}if(Math.abs(f)>=aC){ms(),fn=!0,a.scrollTop=po(a),An=a.scrollTop,fn=!1;return}Qg(a,()=>po(a),c,()=>Sn.isFollowing())},Ja=()=>{if(!fd()){Ft();return}let a=Yg();fn=!0,a.scrollTop=po(a),An=a.scrollTop,fn=!1,Ft()},kr=a=>{let c=0,f=a;for(;f&&f!==V;)c+=f.offsetTop,f=f.offsetParent;return c},mC=()=>{let a=V.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??V.ownerDocument.getSelection()},Xa=()=>jy(mC(),V),md=()=>{if(Xv()!=="last-user-turn")return!1;let a=O?.getMessages()??[];if(a.length<2)return!1;let c=[...a].reverse().find(E=>E.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=V.querySelector(`[data-message-id="${f}"]`);if(!h)return!1;let C=Math.min(Math.max(0,kr(h)-ii()),po(V));return fn=!0,V.scrollTop=C,An=V.scrollTop,fn=!1,Cn()==="follow"&&!Jr(V,Co)&&Sn.pause(),Ft(),!0},Qa=a=>{let c=Math.max(0,Math.round(a));Rn.style.height=`${c}px`,Rn.style.display=c>0?"":"none",Nt&&(Nt.spacerHeight=Math.max(0,a))},Za=a=>{let c=parseFloat(getComputedStyle(V).paddingBottom)||0,f=0;for(let C of Array.from(V.children)){if(C===Rn||C.offsetHeight===0)continue;let E=kr(C)+C.offsetHeight;E>f&&(f=E)}let h=V.scrollHeight-a;return f>0?Math.min(f+c,h):h},hC=()=>{if(!Nt||Nt.spacerHeight<=0)return;let a=Za(Nt.spacerHeight),c=Math.max(0,Math.round(V.scrollTop)+V.clientHeight-a+Co);c<Nt.spacerHeight&&(Qa(c),Ft())},Yn=()=>{Tr!==null&&(cancelAnimationFrame(Tr),Tr=null),ms(),Nt=null,Rn.style.height="0px",Rn.style.display="none"},Zg=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),hd=a=>V.querySelector(`[data-message-id="${Zg(a)}"]`),ef=a=>{Tr!==null&&cancelAnimationFrame(Tr),Tr=requestAnimationFrame(()=>{Tr=null;let c=Zg(a),f=V.querySelector(`[data-message-id="${c}"]`);if(!f)return;let h=kr(f),C=Nt?.spacerHeight??0,E=Za(C),{targetScrollTop:j,spacerHeight:F}=su({anchorOffsetTop:h,topOffset:ii(),viewportHeight:V.clientHeight,contentHeight:E,slack:Co});Nt={initialSpacerHeight:F,contentHeightAtAnchor:E,spacerHeight:F},Qa(F),Qg(V,()=>f.isConnected?Math.max(0,kr(f)-ii()):j,220)})},So=()=>{if(Cn()!=="anchor-top"||!Nt||!gs)return;let a=hd(gs);if(!a)return;ms();let c=Nt.spacerHeight,f=Za(c),{targetScrollTop:h,spacerHeight:C}=su({anchorOffsetTop:kr(a),topOffset:ii(),viewportHeight:V.clientHeight,contentHeight:f,slack:Co});Nt={initialSpacerHeight:C,contentHeightAtAnchor:f,spacerHeight:C},Qa(C),fn=!0,V.scrollTop=h,An=V.scrollTop,fn=!1,Ft()},yC=()=>{if($o()){if(!Sn.isFollowing()||Jr(V,1))return;qo(!wn);return}if(Nt&&Nt.initialSpacerHeight>0){let a=V.scrollHeight-Nt.spacerHeight,c=zy({initialSpacerHeight:Nt.initialSpacerHeight,contentHeightAtAnchor:Nt.contentHeightAtAnchor,currentContentHeight:a});c!==Nt.spacerHeight&&Qa(c)}Ft()},bC=a=>{let c=Cn();c==="follow"?(mn(),qo(!0)):c==="anchor-top"&&(mi=!1,Va=!0,Ka=!1,gs=a,ef(a))},vC=()=>{if(Cn()==="anchor-top"){if(Va){mi=!1;return}mi=!0,Yn(),mn(),qo(!0)}},CC=96,wC=a=>{if(Er===null)return!0;let c=hd(Er),f=hd(a);if(!c||!f)return!0;let h=kr(f)-kr(c);return ii()+h>V.clientHeight-CC},xC=a=>{if(Cn()!=="anchor-top"||!Va||Ka||Xa())return;let c=Er===null;for(let f of a){if(!c){f.id===Er&&(c=!0);continue}if(_y(f)){if(f.id===gs||!wC(f.id))return;gs=f.id,ef(f.id);return}}},SC=a=>{let c=new Map;a.forEach(f=>{let h=dd.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!h&&f.role==="assistant"&&(m.emit("assistant:message",f),!us&&(Cn()!=="anchor-top"||cg())&&gd()&&(Uo+=1,ud(),Ft(),pg(Uo===1?"1 new message below.":`${Uo} new messages below.`))),f.role==="assistant"&&h?.streaming&&f.streaming===!1&&m.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(h?f.approval.status!=="pending"&&m.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):m.emit("approval:requested",{approval:f.approval,message:f}))}),dd.clear(),c.forEach((f,h)=>{dd.set(h,f)})},el=(a,c)=>{let f=c==="user"?"user":"assistant",h=o.layout?.messages?.[f],C=h?.width??"content",E=h?.maxWidth??(C==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${c}`,`persona-message-width-${C}`),a.classList.toggle("persona-justify-end",c==="user"),a.setAttribute("data-message-role",c),a.setAttribute("data-message-width",C),a.style.setProperty("--persona-message-row-max-width",E)},Pr=(a,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${a}`,f.setAttribute("data-wrapper-id",a),el(f,c),f},AC=(a,c,f)=>{let h=document.createElement("div"),E=(()=>{let _=i.find(ke=>ke.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),j=(_,ke)=>ke==null?!1:typeof ke=="string"?(_.textContent=ke,!0):(_.appendChild(ke),!0),F=new Set,Y=new Map,U=new Set,te=i.some(_=>_.renderAskUserQuestion),se=[],ge=[],Ye=o.enableComponentStreaming!==!1,bt=o.approval!==!1,qt=[];if(c.forEach(_=>{F.add(_.id),Y.set(_.id,_.role);let ke=te&&Qo(_),He=bt&&_.variant==="approval"&&!!_.approval,Ae=!ke&&_.role==="assistant"&&!_.variant&&Ye&&Nc(_);!He&&jo.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),jo.delete(_.id)),!Ae&&Ar.has(_.id)&&(a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),Ar.delete(_.id));let Et=Qo(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=Ry(_,ad)+Et,Vt=ke||He||Ae?null:By(xn,_.id,dt);if(Vt){h.appendChild(Vt.cloneNode(!0)),Qo(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Qi(_,o,X.composerOverlay));return}let lt=null,an=i.find(Ie=>!!(_.variant==="reasoning"&&Ie.renderReasoning||_.variant==="tool"&&Ie.renderToolCall||!_.variant&&Ie.renderMessage)),Gt=o.layout?.messages;if(Qo(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){ps.delete(_.id),a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(Rs(_)&&nr(o).enabled)return;if(Qo(_)&&o.features?.askUserQuestion?.enabled!==!1){let Ie=i.find(ln=>typeof ln.renderAskUserQuestion=="function");if(Ie&&rt.current){let ln=ps.get(_.id),jt=ln!==dt,Ee=null;if(jt){let{payload:qe,complete:Bt}=Zo(_),Pt=_.id,en=()=>rt.current?.getMessages().find(Nn=>Nn.id===Pt);Ee=Ie.renderAskUserQuestion({message:_,payload:qe,complete:Bt,resolve:Nn=>{let Ve=en();Ve&&rt.current?.resolveAskUserQuestion(Ve,Nn)},dismiss:()=>{let Nn=en();Nn?.agentMetadata?.awaitingLocalTool&&(rt.current?.markAskUserQuestionResolved(Nn),rt.current?.resolveAskUserQuestion(Nn,"(dismissed)"))},config:o})}let Wt=ln!=null;if(jt&&Ee===null&&!Wt){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Qi(_,o,X.composerOverlay));return}let pt=Pr(_.id,_.role);pt.setAttribute("data-ask-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),h.appendChild(pt),se.push({messageId:_.id,fingerprint:dt,bubble:Ee});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(U.add(_.toolCall.id),Qi(_,o,X.composerOverlay));return}}else if(He){let Ie=i.find(Wt=>typeof Wt.renderApproval=="function")??g,jt=jo.get(_.id)!==dt,Ee=null;if(jt&&Ie?.renderApproval){let Wt=_.id,pt=(qe,Bt)=>{let Pt=rt.current?.getMessages().find(en=>en.id===Wt);Pt?.approval&&(Pt.approval.toolType==="webmcp"?rt.current?.resolveWebMcpApproval(Pt.id,qe):rt.current?.resolveApproval(Pt.approval,qe,Bt))};Ee=Ie.renderApproval({message:_,defaultRenderer:()=>Pc(_,o),config:o,approve:qe=>pt("approved",qe),deny:qe=>pt("denied",qe)})}if(jt&&Ee===null)a.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),jo.delete(_.id),lt=Pc(_,o);else{let Wt=Pr(_.id,_.role);Wt.setAttribute("data-approval-plugin-stub","true"),Wt.setAttribute("data-preserve-runtime","true"),h.appendChild(Wt),qt.push({messageId:_.id,fingerprint:dt,bubble:Ee});return}}else if(an)if(_.variant==="reasoning"&&_.reasoning&&an.renderReasoning){if(!xe)return;lt=an.renderReasoning({message:_,defaultRenderer:()=>Tu(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&an.renderToolCall){if(!Pe)return;lt=an.renderToolCall({message:_,defaultRenderer:()=>Mu(_,o),config:o})}else an.renderMessage&&(lt=an.renderMessage({message:_,defaultRenderer:()=>{let Ie=Pa(_,f,Gt,o.messageActions,N,{loadingIndicatorRenderer:E,widgetConfig:o});return _.role!=="user"&&Bu(Ie,_,o,O),Ie},config:o}));if(!lt&&Ae){let Ie=qu(_);if(Ie){let ln=Ar.get(_.id),jt=ln!==dt,Ee=o.wrapComponentDirectiveInBubble!==!1&&co.getOptions(Ie.component)?.bubbleChrome!==!1,Wt=null;if(jt){let pt=Uu(Ie,{config:o,message:_,transform:f});if(pt&&Ie.component==="PersonaArtifactInline"){let qe=pt.hasAttribute("data-artifact-inline")?pt:pt.querySelector("[data-artifact-inline]"),Bt=qe?.getAttribute("data-artifact-inline")??"",Pt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Bt):Bt,en=Bt?a.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${Pt}"]`)??null:null;qe&&en&&en!==qe&&ky(en)&&(qe===pt?pt=en:qe.replaceWith(en))}if(pt)if(Ee){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-${_.id}`,qe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let Bt=document.createElement("div");Bt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Bt.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),qe.appendChild(Bt)}qe.appendChild(pt),Wt=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-${_.id}`,qe.setAttribute("data-message-id",_.id),qe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let Bt=document.createElement("div");Bt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Bt.innerHTML=f({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),qe.appendChild(Bt)}qe.appendChild(pt),Wt=qe}}if(Wt||ln!=null){let pt=Pr(_.id,_.role);pt.setAttribute("data-component-directive-stub","true"),pt.setAttribute("data-preserve-runtime","true"),h.appendChild(pt),ge.push({messageId:_.id,fingerprint:dt,bubble:Wt});return}}}if(!lt)if(_.variant==="reasoning"&&_.reasoning){if(!xe)return;lt=Tu(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!Pe)return;lt=Mu(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;lt=Pc(_,o)}else{let Ie=o.layout?.messages;Ie?.renderUserMessage&&_.role==="user"?lt=Ie.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Ie?.renderAssistantMessage&&_.role==="assistant"?lt=Ie.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):lt=Pa(_,f,Ie,o.messageActions,N,{loadingIndicatorRenderer:E,widgetConfig:o}),_.role!=="user"&<&&Bu(lt,_,o,O)}let $t=Pr(_.id,_.role);$t.appendChild(lt),Oy(xn,_.id,dt,$t),h.appendChild($t)}),X.composerOverlay&&X.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(ke=>{let He=ke.getAttribute("data-persona-ask-sheet-for");He&&!U.has(He)&&jr(X.composerOverlay,He)}),o.features?.toolCallDisplay?.grouped){let _=[],ke=[],He=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Ae=>{if(Ae.variant==="tool"&&Ae.toolCall&&Pe){ke.push(Ae);return}Ae.variant==="reasoning"&&!xe||((ke.length>1||He&&ke.length>0)&&_.push(ke),ke=[])}),(ke.length>1||He&&ke.length>0)&&_.push(ke),_.forEach(Ae=>{let Et=Ae.map(Ie=>Array.from(h.children).find(ln=>ln instanceof HTMLElement&&ln.getAttribute("data-wrapper-id")===Ie.id)).filter(Ie=>!!Ie);if(Et.length<(He?1:2))return;let dt=Pr(`tool-group-${Ae[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Vt=document.createElement("div");Vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Vt.setAttribute("data-persona-tool-group","true");let lt=document.createElement("div");lt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",lt.id=`tool-group-summary-${Ae[0].id}`;let an=`Called ${Ae.length} ${Ae.length===1?"tool":"tools"}`,Gt=o.toolCall?.renderGroupedSummary?.({messages:Ae,toolCalls:Ae.map(Ie=>Ie.toolCall).filter(Ie=>!!Ie),defaultSummary:an,config:o});j(lt,Gt)||(lt.textContent=an);let $t=document.createElement("div");$t.className="persona-tool-group-stack persona-flex persona-flex-col",$t.id=`tool-group-stack-${Ae[0].id}`,$t.setAttribute("data-persona-tool-group-stack","true"),Vt.appendChild(lt),He||Vt.appendChild($t),dt.appendChild(Vt),Et[0].before(dt),Et.forEach((Ie,ln)=>{if(He){Ie.remove();return}Ie.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"),ln<Et.length-1&&jt.setAttribute("data-persona-tool-group-connector","true"),jt.appendChild(Ie),$t.appendChild(jt)})})}Dy(xn,F);let yn=c.some(_=>_.role==="assistant"&&_.streaming),Tt=c[c.length-1],kt=Tt?.role==="assistant"&&!Tt.streaming&&Tt.variant!=="approval";if(wn&&c.some(_=>_.role==="user")&&!yn&&!kt){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:Xs},ke=i.find(Ae=>Ae.renderLoadingIndicator),He=null;if(ke?.renderLoadingIndicator&&(He=ke.renderLoadingIndicator(_)),He===null&&o.loadingIndicator?.render&&(He=o.loadingIndicator.render(_)),He===null&&(He=Xs()),He){let Ae=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Ae.className=Et?ka("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ae.setAttribute("data-typing-indicator","true"),Et&&(Ae.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Ae.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ae.appendChild(He);let Vt=Pr("typing-indicator","assistant");Vt.appendChild(Ae),h.appendChild(Vt)}}if(!wn&&c.length>0){let _=c[c.length-1],ke={config:o,lastMessage:_,messageCount:c.length},He=i.find(Et=>Et.renderIdleIndicator),Ae=null;if(He?.renderIdleIndicator&&(Ae=He.renderIdleIndicator(ke)),Ae===null&&o.loadingIndicator?.renderIdle&&(Ae=o.loadingIndicator.renderIdle(ke)),Ae){let Et=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;Et.className=dt?["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(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Ae);let Vt=Pr("idle-indicator","assistant");Vt.appendChild(Et),h.appendChild(Vt)}}if(Nm(h),uc(a,h),mp(a),se.length>0)for(let{messageId:_,fingerprint:ke,bubble:He}of se){let Ae=a.querySelector(`#wrapper-${_}`);Ae&&(el(Ae,Y.get(_)??"assistant"),He!==null&&(Ae.replaceChildren(He),Ae.setAttribute("data-bubble-fp",ke),ps.set(_,ke)))}if(ps.size>0)for(let _ of ps.keys())F.has(_)||ps.delete(_);if(ge.length>0)for(let{messageId:_,fingerprint:ke,bubble:He}of ge){let Ae=a.querySelector(`#wrapper-${_}`);Ae&&(el(Ae,Y.get(_)??"assistant"),He!==null&&(Ae.replaceChildren(He),Ae.setAttribute("data-bubble-fp",ke),Ar.set(_,ke)))}if(Ar.size>0)for(let _ of Ar.keys())F.has(_)||Ar.delete(_);if(qt.length>0)for(let{messageId:_,fingerprint:ke,bubble:He}of qt){let Ae=a.querySelector(`#wrapper-${_}`);Ae&&(el(Ae,Y.get(_)??"assistant"),He!==null&&(Ae.replaceChildren(He),Ae.setAttribute("data-bubble-fp",ke),jo.set(_,ke)))}if(jo.size>0)for(let _ of jo.keys())F.has(_)||jo.delete(_)},yi=(a,c,f)=>{AC(a,c,f),Eg()},bi=null,TC=()=>{if(bi)return;let a=f=>{let h=f.composedPath();h.includes(P)||G&&h.includes(G)||at(!1,"user")};bi=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},tf=()=>{if(!bi)return;(e.ownerDocument??document).removeEventListener("pointerdown",bi,!0),bi=null};Me.push(()=>tf());let vi=null,EC=()=>{if(vi)return;let a=f=>{f.key==="Escape"&&(f.isComposing||at(!1,"user"))};vi=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},nf=()=>{if(!vi)return;(e.ownerDocument??document).removeEventListener("keydown",vi,!0),vi=null};Me.push(()=>nf());let Ci=!1,of=new Set,MC=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},hs=()=>{if(!ae())return;let a=X.peekBanner,c=X.peekTextNode;if(!a||!c)return;if(M){a.classList.remove("persona-pill-peek--visible");return}let f=O?.getMessages()??[],h;for(let Tt=f.length-1;Tt>=0;Tt--){let kt=f[Tt];if(kt.role==="assistant"&&kt.content){h=kt;break}}if(!h){a.classList.remove("persona-pill-peek--visible");return}let C=h.content,E=!!h.streaming,j=MC(),F=gc(j),Y=F.type!=="none"?Vs(F.type,j?.plugins):null,U=Y?.isAnimating?.(h)===!0,te=Y!==null&&(E||U);te&&Y&&!of.has(Y.name)&&(hc(Y,e),of.add(Y.name));let se=te&&Y?.containerClass?Y.containerClass:null,ge=c.dataset.personaPeekStreamClass??null;ge&&ge!==se&&(c.classList.remove(ge),delete c.dataset.personaPeekStreamClass),se&&ge!==se&&(c.classList.add(se),c.dataset.personaPeekStreamClass=se),te?(c.style.setProperty("--persona-stream-step",`${F.speed}ms`),c.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Ye=te?fc(C,F.buffer,Y,h,E):C;if(te&&F.placeholder==="skeleton"&&E&&(!Ye||!Ye.trim())){let Tt=document.createElement("div"),kt=Sa();kt.classList.add("persona-pill-peek__skeleton"),Tt.appendChild(kt),uc(c,Tt)}else{let Tt=Math.max(0,Ye.length-100),kt=Ye.length>100?Ye.slice(-100):Ye,_=Ho(kt);if(!te||!Y){let ke=Ye.length>100?`\u2026${kt}`:kt;c.textContent!==ke&&(c.textContent=ke)}else{let ke=_;(Y.wrap==="char"||Y.wrap==="word")&&(ke=xa(_,Y.wrap,`peek-${h.id}`,{skipTags:Y.skipTags,startIndex:Tt}));let He=document.createElement("div");if(He.innerHTML=ke,Y.useCaret&&kt.length>0){let Ae=mc(),Et=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=Et[Et.length-1];dt?.parentNode?dt.parentNode.insertBefore(Ae,dt.nextSibling):He.appendChild(Ae)}uc(c,He),Y.onAfterRender?.({container:c,bubble:a,messageId:h.id,message:h,speed:F.speed,duration:F.duration})}}let yn=wn||Ci;a.classList.toggle("persona-pill-peek--visible",yn)};if(ae()){let a=X.peekBanner;if(a){let h=C=>{C.preventDefault(),C.stopPropagation(),at(!0,"user")};a.addEventListener("pointerdown",h),Me.push(()=>{a.removeEventListener("pointerdown",h)})}let c=()=>{Ci||(Ci=!0,hs())},f=()=>{Ci&&(Ci=!1,hs())};B.addEventListener("pointerenter",c),B.addEventListener("pointerleave",f),Me.push(()=>{B.removeEventListener("pointerenter",c),B.removeEventListener("pointerleave",f)}),G&&(G.addEventListener("pointerenter",c),G.addEventListener("pointerleave",f),Me.push(()=>{G.removeEventListener("pointerenter",c),G.removeEventListener("pointerleave",f)}))}let kC=a=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",h=c.bottomOffset??"16px",C=c.collapsedMaxWidth,E=c.expandedMaxWidth??"880px",j=c.expandedTopOffset??"5vh",F=c.modalMaxWidth??"880px",Y=c.modalMaxHeight??"min(90vh, 800px)",U="calc(100vw - 32px)",te="var(--persona-pill-area-height, 80px)",se=P.style;if(se.left="",se.right="",se.top="",se.bottom="",se.transform="",se.width="",se.maxWidth="",se.height="",se.maxHeight="",G){let ge=G.style;ge.bottom=h,ge.width=C??""}if(a&&f!=="fullscreen"){if(f==="modal"){se.top="50%",se.left="50%",se.transform="translate(-50%, -50%)",se.bottom="auto",se.right="auto",se.width=F,se.maxWidth=U,se.maxHeight=Y,se.height=Y;return}se.left="50%",se.transform="translateX(-50%)",se.bottom=`calc(${h} + ${te})`,se.top=j,se.width=E,se.maxWidth=U}},wi=()=>{if(!ie())return;if(ae()){let U=(o.launcher?.composerBar??{}).expandedSize??"anchored",te=M?"expanded":"collapsed";P.dataset.state=te,P.dataset.expandedSize=U,G&&(G.dataset.state=te,G.dataset.expandedSize=U),P.style.removeProperty("display"),P.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),kC(M),K.style.display=M?"flex":"none",br(),M?(TC(),EC()):(tf(),nf()),hs();return}let a=wt(o),c=e.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,h=o.launcher?.mobileFullscreen??!0,C=c.innerWidth<=f,E=h&&C&&$,j=Pn(o).reveal;M?(P.style.removeProperty("display"),P.style.display=a?"flex":"",P.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-95","persona-opacity-0"),B.classList.add("persona-scale-100","persona-opacity-100"),St?(St.setPanelOpen(!0),St.element.style.display="none"):sn&&(sn.style.display="none")):(a?a&&(j==="overlay"||j==="push")&&!E?(P.style.removeProperty("display"),P.style.display="flex",P.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(P.style.setProperty("display","none","important"),P.classList.remove("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(P.style.display="",P.classList.add("persona-pointer-events-none","persona-opacity-0"),B.classList.remove("persona-scale-100","persona-opacity-100"),B.classList.add("persona-scale-95","persona-opacity-0")),St?(St.setPanelOpen(!1),St.element.style.display=a?"none":""):sn&&(sn.style.display=a?"none":""))},at=(a,c="user")=>{if(!ie()||M===a)return;let f=M;M=a,wi();let h=(()=>{let E=o.launcher?.sidebarMode??!1,j=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,Y=o.launcher?.mobileBreakpoint??640,U=j.innerWidth<=Y,te=wt(o)&&F&&U,se=ae()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||F&&U&&$||te||se})();if(M&&h){if(!Zn){let E=e.getRootNode(),j=E instanceof ShadowRoot?E.host:e.closest(".persona-host");j&&(Zn=lu(j,o.launcher?.zIndex??Jt))}eo||(eo=cu(e.ownerDocument))}else M||(Zn?.(),Zn=null,eo?.(),eo=null);M&&(Ni(),md()||(Cn()==="follow"?qo(!0):Ja()));let C={open:M,source:c,timestamp:Date.now()};M&&!f?m.emit("widget:opened",C):!M&&f&&m.emit("widget:closed",C),m.emit("widget:state",{open:M,launcherEnabled:$,voiceActive:$e.active,streaming:O.isStreaming()})},xi=a=>{ag(a?"stop":"send"),oe&&(oe.disabled=a),wr.forEach(c=>{c.elements.forEach(f=>{f.toggleAttribute("data-disabled",a),f instanceof HTMLButtonElement||f.setAttribute("aria-disabled",a?"true":"false")}),c.buttons.forEach(f=>{f.disabled=a})}),Cd.forEach(c=>{c.toggleAttribute("data-disabled",a),c instanceof HTMLButtonElement?c.disabled=a:c.setAttribute("aria-disabled",a?"true":"false"),c.querySelectorAll("button").forEach(f=>{f.disabled=a})}),Fe.dataset.personaComposerStreaming=a?"true":"false",Fe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(c=>{(c instanceof HTMLButtonElement||c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)&&(c.disabled=a)})},Lr=()=>{$e.active||me&&me.focus()};m.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Lr(),200)});let Hr=null,Si=!1,yd=!gn.hidden,Vo=null,rf=!L,sf=null,af,lf=null,ys=null,bd=!1,Ai=a=>{let c=gr(o),f=`${c.variant}|${c.dismiss}|${c.title}|${c.subtitle}`;(f!==sf||c.icon!==af)&&(sf=f,af=c.icon,Ec({host:gn,iconHolder:zv,title:Uv,subtitle:qv,starterSuggestions:ct},c));let h=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;h!==lf&&(lf=h,Mc(vn,c.message,o));let C=a??(O?O.getMessages():o.initialMessages),E=Si,j=!E&&Qr(c,C),F=j!==yd;if(yd=j,ys){Vo?.cancel(),Vo=null,E!==bd&&(bd=E,E?vu(V,gn,null):bu(V,gn,ys)),Qs(V,gn,!E);return}if(F&&!j&&!E&&c.dismiss==="on-first-message"&&rf){Vo=lb(gn,U=>{Vo===U&&(Vo=null),!yd&&!ys&&(Qs(V,gn,!1),So()),U?.cancel()});return}if(Vo){if(!j&&!E)return;Vo.cancel(),Vo=null}let Y=!gn.hidden;Qs(V,gn,j),!j&&Y&&So()},vd=[],Cd=[],wd=!1,cf=null,df,pf=()=>{Cd.length=0;let a=vd.splice(0,vd.length);for(let c of a)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};Me.push(pf);let PC=(a,c)=>{let f=pu(a,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let h=o.suggestions?.starters,C=uu({item:{...f,behavior:f.behavior??h?.behavior??"send"},index:c,surface:"starter",source:"config",variant:h?.variant??"card",streaming:u?O.isStreaming():!1,config:o,plugins:i,chipsConfig:o.suggestionChipsConfig,session:O,getTextarea:()=>me,eventTarget:gn});return Cd.push(C),C},xd=()=>{if(wd)return;wd=!0;let a=gr(o);cf=`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,df=a.icon;try{pf(),vu(V,gn,ys),ys=null,bd=!1;let c=O?O.getMessages():o.initialMessages,f=Qr(a,c),h=0,C=null;for(let E of i)if(E.renderWelcome&&(C=E.renderWelcome({config:a,variant:a.variant,visible:f,defaultRenderer:()=>gn,sendMessage:j=>{if(!O||O.isStreaming())return;let F=j.trim();F&&O.sendMessage(F)},requestRender:()=>xd(),renderStarter:j=>PC(j,h++),storage:p(E.id),onCleanup:j=>{vd.push(j)}}),C))break;C&&C!==gn&&(ys=C,bu(V,gn,C))}finally{wd=!1}Ai()},LC=()=>{let a=gr(o);`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===cf&&a.icon===df||xd()},Sd=()=>{Ai(),ci||(me.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!O?.isStreaming()&&(ye.textContent=o.copy?.sendButtonLabel??"Send")),me.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',me.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},HC=!!o.setStoredConversationId,Ti=a=>R(c=>{let f={...c};return delete f[a],f}),tl=a=>{let c=T[a];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>tl("sessionId"),setStoredSessionId:a=>{R(c=>({...c,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ti("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>tl("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{R(c=>({...c,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ti("conversationId"))});let uf=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,gf=a=>Xb(a,Re(),o.persistState===!1),ff=uf(),Ao=ff?gf(ff):null,Ir={...Ao?{visitorStore:Ao}:{},historyBootstrapReady:k,getStoredMessageCursor:()=>tl("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){Ti("historyMessageCursor");return}R(c=>({...c,historyMessageCursor:a}))},getPendingDisplayProjections:()=>{let a=T.pendingDisplayProjections;if(!a||typeof a!="object")return null;let c=a;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:a=>{if(!a){Ti("pendingDisplayProjections");return}R(c=>({...c,pendingDisplayProjections:a}))},...HC?{}:{getStoredConversationRevision:()=>tl("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){Ti("conversationRevision");return}R(c=>({...c,conversationRevision:a}))}}},IC=()=>{let a=uf();if(a&&Ao?.matches(a,Re(),o.persistState===!1)||!a&&!Ao)return;Ao?.destroy(),Ao=a?gf(a):null;let c={...Ir};Ao?c.visitorStore=Ao:delete c.visitorStore,Ir=c,O.setHistoryInternals(Ir)},Rr=null,RC=()=>{Rr==null&&(Rr=setInterval(()=>{let a=le.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Rr),Rr=null;return}let c=Date.now();a.forEach(f=>{let h=Number(f.getAttribute("data-tool-elapsed"));h&&(f.textContent=$l(c-h))})},100))},Ad=(a,c)=>{if(Object.is(a,c))return!0;if(a===null||c===null||typeof a!="object"||typeof c!="object")return!1;if(Array.isArray(a)||Array.isArray(c))return!Array.isArray(a)||!Array.isArray(c)||a.length!==c.length?!1:a.every((j,F)=>Ad(j,c[F]));let f=a,h=c,C=Object.keys(f),E=Object.keys(h);return C.length===E.length&&C.every(j=>Object.prototype.hasOwnProperty.call(h,j)&&Ad(f[j],h[j]))},mf=a=>{let{content:c,rawContent:f,llmContent:h,...C}=a;return C},Td=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Nc(a),WC=(a,c,f)=>{if(a.length!==c.length)return!1;let h=a[f.index],C=c[f.index];return!h||!C||h.id!==f.id||C.id!==f.id?!1:(!Object.is(h.content,C.content)||!Object.is(h.rawContent,C.rawContent)||!Object.is(h.llmContent,C.llmContent))&&Td(h)&&Td(C)&&Ad(mf(h),mf(C))},Ed=null,bs=null,Wr=null,To=null,nl=a=>{Ed=a;let c,f;bs=null;for(let C=a.length-1;C>=0;C-=1){let E=a[C];if(!c&&E.role==="user"&&(c=E),!f&&E.role==="assistant"&&(f=E),!bs&&Td(E)&&(bs={index:C,id:E.id}),c&&f&&bs)break}yi(le,a,fe),tu(le,Vn.artifacts,{suppressTransition:wn}),RC(),Ai(a),ds(a),qo(!wn),SC(a),a.length===0&&(Yn(),mi=!0,Va=!1,gs=null,Ka=!1),!ld||us?(ld=!0,Er=c?.id??null,cd=f?.id??null):c&&c.id!==Er?(Er=c.id,bC(c.id)):f&&f.id!==cd&&vC(),f&&(cd=f.id),xC(a);let h=$e.lastUserMessageId;c&&c.id!==h&&($e.lastUserMessageId=c.id,m.emit("user:message",c)),$e.lastUserMessageWasVoice=!!c?.viaVoice,pd(a),hs()},Md=()=>{To!==null&&(cancelAnimationFrame(To),To=null);let a=Wr;Wr=null,a&&nl(a)},hf=()=>{To!==null&&cancelAnimationFrame(To),To=null,Wr=null},BC=a=>{let c=Wr??Ed;if(wn&&c&&bs&&WC(c,a,bs)){Wr=a,To===null&&(To=requestAnimationFrame(()=>{To=null;let f=Wr;Wr=null,f&&nl(f)}));return}if(a.length===0){hf(),nl(a);return}Md(),nl(a)};O=new da(o,{onMessagesChanged(a){BC(a)},onStatusChanged(a){let c=o.statusIndicator??{};S(nn,(h=>h==="idle"?c.idleText??_t.idle:h==="connecting"?c.connectingText??_t.connecting:h==="connected"?c.connectedText??_t.connected:h==="error"?c.errorText??_t.error:h==="paused"?c.pausedText??_t.paused:h==="resuming"?c.resumingText??_t.resuming:_t[h])(a),c,a),No()},onStreamingChanged(a){a||(O?.getMessages().length===0?hf():Md()),wn=a,xi(a),No(),O&&yi(le,O.getMessages(),fe),a||(qo(!0),hC(),zg=!0,O&&Ug(O.getMessages(),nr(o))),Ft(),pg(a?"Responding\u2026":"Response complete."),hs()},onVoiceStatusChanged(a){if(m.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Po(),Ts();break;case"processing":Po(),Mw();break;case"speaking":Po(),kw();break;default:a==="idle"&&O.isBargeInActive()?(Po(),Ts(),oe?.setAttribute("aria-label","End voice session")):($e.active=!1,Po(),xo("system"),Gn());break}},onArtifactsState(a){Vn=a,a.artifacts.length===0&&(as=!1),tu(le,a.artifacts,{suppressTransition:wn}),bo(),pd()},onHistoryStateChanged(a){fo(a)},onHistoryNotice(a){It(a)},onReconnect(a){let{executionId:c,lastEventId:f}=a.handle;a.phase==="paused"?m.emit("stream:paused",{executionId:c,after:f}):a.phase==="resuming"?m.emit("stream:resuming",{executionId:c,after:f,attempt:a.attempt??1}):m.emit("stream:resumed",{executionId:c,after:f})}},Ir),rt.current=O,Me.push(()=>O.cancel()),Me.push(()=>{O.destroy(),Ao?.destroy()});let kd=null;if(O.onReadAloudChange((a,c)=>{Ag=a,Tg=c,Eg();let f=a??kd;a&&(kd=a);let h=f?O.getMessages().find(C=>C.id===f)??null:null;m.emit("message:read-aloud",{messageId:f,message:h,state:c,timestamp:Date.now()}),c==="idle"&&(kd=null)}),u=!0,ld=!0,o.voiceRecognition?.provider?.type==="runtype")try{O.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let OC=720,DC=250,Ue=ju(o.features?.history?.copy),Tn=null,Pd=!1,Xe=null,ol=null,rl="conversation",Ld=null,rn=null,to=null,sl=O.getHistoryState(),Hd=null,il=0,Id=null,al=null,ll=null,Rd=`persona-history-${Math.random().toString(36).slice(2,8)}`,Wd=()=>o.features?.history?.enabled===!0,no=()=>Wd()&&!!Tn&&!Pd,yf=()=>{let a=O.getStatus();return wn||a==="paused"||a==="resuming"},Bd=()=>{let a=o.features?.history?.scope;if(a)return a;let c=o.getIdentityProof?"verified-user":"browser",f=Tn?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},vs=()=>ol?.scope??Bd(),bf=()=>O.getClientSession()?.targetId??null,vf=a=>`${a.state}:${"reason"in a?a.reason:""}`,_C=a=>{let c=vf(a);c!==Hd&&(Hd=c,m.emit("history:identityStatusChanged",{status:a,timestamp:Date.now()}))},cl=a=>{a&&(ho.textContent="",ho.textContent=a)},Cf=null,wf=null,NC=()=>{if(!Wd())return null;let a=tv();if(a)return a();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Cf!==c&&(Cf=c,wf=c()),wf):O.isClientTokenMode()?nv({client:O.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>O.bindActivatedSession(f),getClient:()=>O.getClient()}):null},xf=()=>{al?.(),al=null,ll?.(),ll=null,Pd=!1,Tn=NC();let a={...Ir};Tn?a.historyProvider=Tn:delete a.historyProvider,Ir=a,O.setHistoryInternals(Ir),Tn&&(al=Tn.subscribeAvailability?.(c=>{Pd=!c,c||hn({restoreFocus:!1}),Go()})??null,ll=Tn.subscribeIdentityStatus(c=>_C(c)),Hd=vf(Tn.getIdentityStatus()))},Od=()=>{let a=o.features?.history?.presentation??"panel";if(a==="panel"||a==="auto"&&!(!$||wt(o)))return"panel";let c=Qn??K;return(c.getBoundingClientRect().width||c.clientWidth)>=OC?"rail":"panel"},Wn=(a,c)=>{c?(a.setAttribute("aria-hidden","true"),a.setAttribute("inert","")):(a.removeAttribute("aria-hidden"),a.removeAttribute("inert"))},dl="data-persona-history-suppressed",En=null,Ko=null,Br=null,Ei=null,Dd=null,Sf="",Af=()=>Te===Dd?Sf:o.layout?.showHeader===!1?"none":"",FC=()=>tt==="panel"&&!!Br&&Ei===Br.element&&o.layout?.showHeader!==!1&&Af()!=="none",$C=()=>{for(let a of Array.from(Te.children))a!==En&&a.setAttribute(dl,"")},jC=()=>{for(let a of Array.from(K.querySelectorAll(`[${dl}]`)))a.removeAttribute(dl)},zC=()=>{let a=Br;if(!a)return;if(Array.from(Te.children).some(h=>h!==En&&!h.hasAttribute(dl))){Ko&&Ko!==Te&&(Ko.style.removeProperty("min-height"),Ko=null);let h=Te.offsetHeight;h>0&&(Te.style.minHeight=`${h}px`,Ko=Te)}En||(En=v("div","persona-history-header-host")),a.setHeaderPlacement("external");let f=a.getHeaderElement();f.parentNode!==En&&En.replaceChildren(f),En.parentNode!==Te&&Te.appendChild(En),$C()},Tf=()=>{Ko&&(Ko.style.removeProperty("min-height"),Ko=null),En&&(Br?.setHeaderPlacement("inline"),En.remove(),En=null,jC())},pl=null,_d=()=>{if(pl){if(V.style.display="none",Wn(V,!0),Fe.hidden=!0,Wn(Fe,!0),FC()){zC(),Te.style.display=Af(),Wn(Te,!1);return}Tf(),Te.style.display="none",Wn(Te,!0)}};vt=_d;let UC=a=>{let c=V.style.display,f=Fe.hidden,h=Fe,C=Te,E=Te.style.display;Dd=C,Sf=E,pl=()=>{pl=null,Tf(),Dd=null,V.style.display=c,Wn(V,!1),h.hidden=f,Wn(h,!1),Fe!==h&&(Fe.hidden=!1,Wn(Fe,!1)),C.style.display=E,Wn(C,!1),Te!==C&&(Te.style.display=o.layout?.showHeader===!1?"none":"",Wn(Te,!1))},Fe.parentNode?.insertBefore(a,Fe),_d()},Mi=null,Cs=null,ki=null,Ef=()=>[Te,X.closeButtonWrapper,X.clearChatButtonWrapper,V,Fe],qC=52,ul=()=>o.features?.history?.rail?.collapsible!==!1,ws=()=>o.features?.history?.rail?.side==="right"?"right":"left",Nd=200,Fd=400,$d=a=>Math.min(Fd,Math.max(Nd,Math.round(a))),VC=()=>o.features?.history?.rail?.resizable===!0,Pi,KC=()=>{if(Pi===void 0&&(Pi=null,o.persistState!==!1))try{let a=Number(window.localStorage.getItem(`${Re()}rail-width`));a&&(Pi=a)}catch{}return Pi},Li=()=>$d(KC()??o.features?.history?.rail?.width??260),GC=a=>{if(Pi=a,o.persistState!==!1)try{window.localStorage.setItem(`${Re()}rail-width`,String(a))}catch{}},gl=()=>ul()&&o.features?.history?.rail?.collapsedBehavior==="overlay",Ut=!1,Mf=a=>{let c=v("img");return c.src=a,c.alt="",c.setAttribute("aria-hidden","true"),c},YC=()=>{let a=o.features?.history?.rail?.brand;if(!a)return;let c=!1,f;return h=>{if(a.render)try{return a.render({collapsed:h})??null}catch(C){return c||(c=!0,console.warn("[persona] history rail brand threw",C)),null}return f===void 0&&(a.iconUrl?f=Mf(a.iconUrl):f=a.icon?ce(a.icon,20):null),f?f.cloneNode(!0):null}},JC=()=>o.features?.history?.rail?.sections?.map(a=>{let c=!1,f=h=>{c||(c=!0,console.warn("[persona] history rail section threw",a.id,h))};return{id:a.id,title:a.title,placement:a.placement??"above-conversations",items:a.items.map(h=>{let C;return{id:h.id,label:h.label,badge:h.badge,iconNode:()=>{if(C!==void 0)return C;try{h.renderIcon?C=h.renderIcon()??null:h.iconUrl?C=Mf(h.iconUrl):C=h.icon?ce(h.icon,20):null}catch(E){f(E),C=null}return C},onSelect:()=>{try{h.onSelect()}catch(E){f(E)}}}})}})??[],XC=a=>{let c=JC();for(let f of a)c.some(h=>h.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},Hi=null,kf=()=>`${Re()}rail-collapsed`,jd=()=>{if(Hi===null&&(Hi=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let a=window.localStorage.getItem(kf());a&&(Hi=a==="1")}catch{}return Hi},zd=a=>{if(Hi=a,o.persistState!==!1)try{window.localStorage.setItem(kf(),a?"1":"0")}catch{}},Ii=()=>tt==="rail"&&ul()&&!gl()&&jd(),Ud=()=>{},Pf=()=>{if(gl()){Ud();return}zd(!jd()),Xe?.view.setCollapsed(Ii()),Qt(),So()},qd=()=>{let a=o.features?.history?.rail?.collapseShortcut;return!a||!nc(a)?null:{combo:a,hint:oc(a),aria:ha(a)}},Lf=()=>{d.forEach(c=>c()),d=[];let a=qd();a&&d.push(l.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Ze&&tt==="rail"&&ul()||Ri(),run:()=>gl()?Ud():Pf()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of i)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};Lf();let QC=300,fl="var(--persona-history-overlay-margin,8px)",Bn=null,Eo=null,Mo=null,xs=null,Or=!1,Vd=0,Hf=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Ri=()=>no()&&gl()&&(tt??Od())==="rail",ZC=()=>Ze&&!Ut,Wi=()=>{xs!==null&&clearTimeout(xs),xs=null},ew=()=>{Nu().catch(()=>{})},If=()=>{Wi(),Ut&&(xs=setTimeout(()=>{xs=null,!(Or||!Ut)&&(Mo?.contains(document.activeElement)||hn({restoreFocus:!1}))},QC))},tw=(a,c)=>{let f=Mo?.getBoundingClientRect();if(!f)return!1;let h=Bn?.getBoundingClientRect(),C=h?Math.min(h.top,f.top):f.top;return a>=f.left&&a<=f.right&&c>=C&&c<=f.bottom||!!h&&a>=h.left&&a<=h.right&&c>=h.top&&c<=h.bottom},Kd=a=>{Ut&&(Or=tw(a.clientX,a.clientY),Or?Wi():xs===null&&If())},Rf=a=>{Ze||!Ri()||(Ut=!0,Bi({invoker:Bn,keyboard:a?.keyboard===!0}).then(()=>{Ze?!Or&&document.activeElement!==Bn&&hn():Ut=!1}))},Wf=()=>{let a=Ei?.querySelector('[data-persona-history-focus="collapse"]');a&&(a.setAttribute("aria-label",Ut?Ue.expandLabel:Ue.collapseLabel),a.setAttribute("aria-expanded",Ut?"false":"true"))},Bf=()=>{zd(!1);let a=Xe;if(!Ut||!a){Bi({invoker:Bn});return}let c=document.activeElement===Bn;Ut=!1,Jd(),a.element.remove(),Xd(a.element),Wf(),c&&hl(),So(),Go()},nw=()=>{zd(!0),hn()};Ud=()=>{!Ze||Ut?Bf():nw()};let ow=()=>{let a=qd(),c=Xr({ariaLabel:Ue.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":Rd,...a?{"aria-keyshortcuts":a.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Or=!0,Wi(),!(Hf()||Date.now()<Vd)&&Rf()}),f.addEventListener("mouseleave",()=>{Or=!1,Vd=0,If()}),f.addEventListener("focus",()=>{Ze||ew()}),f.addEventListener("click",h=>{no()&&(h.detail!==0&&Hf()&&!Ze?Rf():Bf())}),Bn=f,Eo=c.wrapper},Gd=()=>{if(Eo&&!Eo.isConnected&&(Eo=null,Bn=null),!Ri()){Eo?.remove(),Eo=null,Bn=null;return}Bn||ow();let a=Eo,c=Bn;if(!a||!c)return;let f=ws()!=="right"?Te.firstChild:null;(f??Te.lastChild)!==a&&Te.insertBefore(a,f),a.style.display=ZC()?"none":"",c.setAttribute("aria-label",Ue.expandLabel),c.setAttribute("aria-expanded",Ze?"true":"false"),Mo&&Qt()},Of=a=>{if(!Ut)return;let c=a.target;c instanceof Node&&(Mo?.contains(c)||Eo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||hn({restoreFocus:!1}))};document.addEventListener("pointerdown",Of,!0),Me.push(()=>{document.removeEventListener("pointerdown",Of,!0),document.removeEventListener("pointermove",Kd),Ss?.(),Wi()});let Yd=null,Ss=null,Df=16,_f=a=>{GC($d(a)),Qt(),So()},rw=()=>{let a=v("div","persona-rail-resizer");return a.tabIndex=0,a.setAttribute("role","separator"),a.setAttribute("aria-orientation","vertical"),a.setAttribute("aria-valuemin",String(Nd)),a.setAttribute("aria-valuemax",String(Fd)),a.addEventListener("pointerdown",c=>{let f=Cs;if(!f||c.button!==0)return;c.preventDefault(),Ss?.();let h=c.clientX,C=f.getBoundingClientRect().width||Li(),E=ws()==="right"?-1:1,j=C,F=e.ownerDocument;f.style.transition="none";let Y=te=>{j=$d(C+E*(te.clientX-h)),f.style.flex=`0 0 ${j}px`,a.setAttribute("aria-valuenow",String(j))},U=()=>{Ss=null,F.removeEventListener("pointermove",Y),F.removeEventListener("pointerup",U),F.removeEventListener("pointercancel",U),f.style.removeProperty("transition");try{a.releasePointerCapture(c.pointerId)}catch{}_f(j)};Ss=U,F.addEventListener("pointermove",Y),F.addEventListener("pointerup",U),F.addEventListener("pointercancel",U);try{a.setPointerCapture(c.pointerId)}catch{}}),a.addEventListener("keydown",c=>{let f=ws()==="right"?-Df:Df,h=Li(),C=c.key==="ArrowRight"?h+f:c.key==="ArrowLeft"?h-f:c.key==="Home"?Nd:c.key==="End"?Fd:null;C!==null&&(c.preventDefault(),_f(C))}),a},sw=(a,c)=>{if(!VC()||Ii()){Ss?.(),Yd?.remove();return}let f=Yd??rw();Yd=f,f.setAttribute("aria-label",Ue.resizeLabel),f.setAttribute("aria-valuenow",String(Li())),f.nextElementSibling!==c&&a.insertBefore(f,c)};Qt=()=>{Xe?.view.setRailSide(ws());let a=ws()==="right",c=Mo;if(c){let F=Bn?Bn.getBoundingClientRect().bottom-K.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(F))}px + ${fl})`,c.style.width=`${Li()}px`,c.style.left=a?"":fl,c.style.right=a?fl:""}let f=Cs,h=Mi,C=ki;if(!f||!h||!C)return;f.style.flex=`0 0 ${Ii()?qC:Li()}px`;let E="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=a?"":E,f.style.borderLeft=a?E:"";let j=a?C:f;h.firstElementChild!==j&&h.append(j,a?f:C),sw(h,a?f:C)};let iw=a=>{let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let h=v("div","persona-history-rail-host");h.style.cssText="display:flex;min-height:0;overflow:hidden",K.insertBefore(c,Te.parentNode===K?Te:V);for(let C of Ef())C?.parentNode===K&&f.appendChild(C);c.append(h,f),h.appendChild(a),Mi=c,Cs=h,ki=f,Qt()},aw=a=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${fl};display:flex;overflow:hidden;z-index:${Ns-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,K.style.position="relative",K.appendChild(c),c.appendChild(a),document.addEventListener("pointermove",Kd),Mo=c,Qt(),Wf()},Jd=()=>{pl?.(),Mo&&(Or&&(Vd=Date.now()+150),document.removeEventListener("pointermove",Kd),Mo.remove(),Mo=null);let a=Mi;if(a){Ss?.();for(let c of Ef())c&&a.contains(c)&&K.insertBefore(c,a);a.remove(),Mi=null,Cs=null,ki=null}},Nf=a=>{Ei=a,a.id=Rd,a.style.flex="1 1 auto",a.style.minHeight="0"},Xd=a=>{Nf(a),tt!=="rail"?UC(a):Ut?aw(a):iw(a)},ml=()=>{if(Gd(),Jf(),!Ze||!Xe)return;let a=Od();if(a===tt)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Xe.element.contains(c)||En?.contains(c)===!0)?c:null;Jd(),Xe.element.remove(),Xe.view.setHeaderPlacement("inline"),tt=a,Xe.view.setPresentation(a),Xe.view.setCollapsed(Ii()),Xe.requestRender(),Xe.element.isConnected||Xd(Xe.element),f?.isConnected?f.focus():hl(),Ft(),So(),Go()},Ff=(a,c)=>En?.querySelector(c)??a.querySelector(c),hl=()=>{let a=Xe?.element??Ei;if(!a)return;let c=Ff(a,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=Ff(a,".persona-history-title")??a;f.tabIndex=-1,f.focus()},Bi=async a=>{if(!no()||Ze)return;let c=Tn;if(!c)return;if(!Ut&&Ri()&&jd()){Gd();return}yl();let f=++il;rl=a?.returnSurface??"conversation",Ld=a?.invoker??rn;let h;try{h=await Nu()}catch{cl(Ue.openHistoryLabel);return}if(f!==il||Ze)return;ol={scope:Bd()},tt=Od(),Ze=!0;let C=tt==="panel"&&o.layout?.showHeader!==!1&&Te.style.display!=="none"?"external":"inline",E=o.features?.history?.rowAvatar,j=qd(),F=j?{hint:j.hint,aria:j.aria}:null,Y={provider:c,context:ol,targetId:bf(),presentation:tt,collapsible:ul(),collapsed:Ii(),railSide:ws(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:YC(),onToggleCollapse:Pf,...F?{collapseShortcut:F}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:E===!1?!1:typeof E=="string"?E:o.launcher?.iconUrl,activeConversationId:O.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:U=>Zd(U,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:U=>Dr(U),attachTooltip:Xt,onStartNew:()=>ep({focusComposer:!0}),onClose:()=>hn(),onRequestDeleteConversation:U=>Yf(U),onRequestClearHistory:()=>gw(),...c.resetDevice?{onRequestResetIdentity:()=>fw()}:{}};Xe=ev({plugins:i,config:o,getPresentation:()=>tt??"panel",getReturnSurface:()=>rl,close:()=>hn(),createView:({slots:U,renderDom:te,onModelChange:se,railSections:ge})=>(Br=h.createHistoryView({...Y,railSections:XC(ge),slots:U,renderDom:te,onModelChange:se,onAnnounce:cl}),Br),onElementChanged:(U,te)=>{if(!te?.isConnected)return Xd(U);Nf(U),te.replaceWith(U),_d()}}),Xe.view.setNewConversationRequired(sl.recovery==="new_conversation_required"),a?.focus!==!1&&(tt!=="rail"||a?.keyboard===!0)&&hl(),Ft(),So(),Go(),m.emit("history:opened",{presentation:tt,returnSurface:rl,timestamp:Date.now()})},yl=()=>{},hn=a=>{if(!Ze)return;il+=1;let c=rl,f=Ld,h=Xe,C=a?.restoreFocus!==!1;Ze=!1;let E=!1,j=null,F=()=>{if(!E){if(E=!0,yl=()=>{},j!==null&&clearTimeout(j),Ut=!1,Wi(),Jd(),h?.dispose(),h?.view.destroy(),h?.element.remove(),Xe===h&&(Xe=null,Br=null,Ei=null,tt=null,ol=null,Ld=null),Ft(),So(),Go(),C){let U=f??rn;U?.isConnected?U.focus():Lr()}m.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},Y=h&&h.element===h.view.element?h.view.playExit():null;if(!Y){F();return}yl=F,j=setTimeout(F,DC),Y.then(F)},$f=a=>{if(!(a.key!=="Escape"||!Ze||!Xe)){if(tt==="rail"){let c=a.target;if(!(c instanceof Node)||!(Xe.element.contains(c)||Ut&&Eo?.contains(c)===!0))return}a.preventDefault(),a.stopPropagation(),hn()}};K.addEventListener("keydown",$f),Me.push(()=>K.removeEventListener("keydown",$f));let bl=null,jf=!1,Oi=()=>{if(!Fo)return;let a=o.layout?.header?.titleSource==="conversation",c=a&&bl?.trim()||null;Fo.textContent=c??o.launcher?.title??"Chat Assistant";let f=Fo.closest(".persona-combo-btn");if(!f)return;let h=!a||O.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",h?"false":"true"),f.setAttribute("aria-haspopup",h?"true":"false"),h||f.setAttribute("aria-expanded","false"),f.style.cursor=h?"pointer":"default";let C=f.querySelector("svg");C&&(C.style.display=h?"":"none")},lw=a=>{a!==bl&&(bl=a,Oi())},Dr=a=>{jf=a?.starred===!0,lw(a&&a.title.trim()||null),Oi()};Oi(),K.addEventListener("persona:title-menu-builtin",a=>{let c=a.detail?.actionId,f=O.getActiveConversationId();f&&(c==="delete"?Yf(f):c==="star"&&O.canUpdateConversations()&&tp(f,{starred:!jf}).catch(()=>{}))});let vl=0,cw=250,Cl=null,wl=()=>{Cl&&clearTimeout(Cl),Cl=null};Me.push(wl);let zf=()=>{wl();let a=Hr;a&&(Si=!0,a.hidden=!1,le.style.display="none",Ai())},xl=()=>{vl+=1,wl(),Hr&&(Hr.remove(),Hr=null,Si=!1,le.style.removeProperty("display"),Wn(Fe,!1),Ai())},dw=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;le.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Qd=(a,c)=>ue("div",{className:Fn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:a}}),Uf=()=>ue("div",{className:"persona-conversation-loading-body"},Qd("58%",!1),Qd("72%",!0),Qd("44%",!1)),qf=a=>{Hr?.remove(),Hr=a,a.hidden=!Si,V.insertBefore(a,le),wl(),Si||(Cl=setTimeout(zf,cw)),Wn(Fe,!0)},pw=()=>{let a={config:o,streaming:!1,location:"conversation-open",defaultRenderer:Uf},c=null,f=i.find(h=>h.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(a)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(a)),qf(ue("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":Ue.openConversationLoadingLabel}},c??Uf()))},uw=a=>{let c=()=>{Zd(a,{focusComposer:!0}).catch(()=>{})},f=no()?()=>{xl(),Bi()}:void 0,h=(F,Y)=>{let U=ue("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:F});return U.addEventListener("click",Y),U},C=()=>ue("div",{className:"persona-conversation-loading-error-body"},ue("p",{className:"persona-conversation-loading-error-title",text:Ue.openConversationErrorTitle}),ue("div",{className:"persona-conversation-loading-error-actions"},h(Ue.openConversationRetryLabel,c),f?h(Ue.openConversationBackLabel,f):null)),E=Object.freeze({conversationId:a,config:o,copy:Object.freeze({title:Ue.openConversationErrorTitle,retryLabel:Ue.openConversationRetryLabel,backLabel:Ue.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:C}),j=null;for(let F of i)if(F.renderHistoryOpenError){try{j=F.renderHistoryOpenError(E)}catch(Y){console.warn("[persona] renderHistoryOpenError threw",Y),j=null}if(j)break}qf(ue("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},j??C())),zf()};m.on("history:closed",()=>{Hr&&Wn(Fe,!0)});let Zd=async(a,{focusComposer:c=!1}={})=>{let f=vs(),h=!!Xe;Xe?.view.setActiveConversationId(a),xl();let C=vl;pw(),Ze&&(tt==="panel"||Ut)&&hn({restoreFocus:!1}),us=!0;try{await O.openConversation(a,{scope:f})}catch(E){throw C===vl&&uw(a),E}finally{us=!1}C===vl&&(xl(),xn.clear(),Yn(),mn(),md()||Ja(),dw(),ko(),h||Dr(null),m.emit("history:conversationOpened",{conversationId:a,title:bl,scope:f,timestamp:Date.now()}),c&&Lr())},ep=async({focusComposer:a=!1}={})=>{xl(),await O.startNewConversation({scope:vs()}),Dr(null),xn.clear(),Yn(),mn(),Ja(),ko();let c=O.getActiveConversationId();Xe?.view.setActiveConversationId(c),m.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Ze&&(tt==="panel"||Ut)&&hn({restoreFocus:!1}),a&&Lr()},tp=async(a,c)=>{let f=await O.updateConversation(a,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Xe?.view.applyConversationSummary(f),!Xe&&a===O.getActiveConversationId()&&Dr(f),f},Vf=async a=>{let c=vs(),f=O.getActiveConversationId()===a;await O.deleteConversation(a,{scope:c}),Xe?.view.removeConversationSummary(a),f&&(Dr(null),xn.clear(),Yn(),mn(),ko()),m.emit("history:conversationDeleted",{conversationId:a,scope:c,wasActive:f,timestamp:Date.now()})},Kf=async a=>{let c=a?.scope??vs(),f=a?.allTargets?null:a?.targetId??bf(),h=await O.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Dr(null),xn.clear(),Yn(),mn(),ko(),m.emit("history:cleared",{deleted:h.deleted,scope:c,targetId:f,timestamp:Date.now()}),h},Gf=async()=>{if(!Tn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let a=!1;try{a=(await O.resetHistoryDevice()).remoteRevocationConfirmed}finally{Dr(null),O.clearArtifacts(),xn.clear(),Ed=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),T={},Q.syncFromMetadata(),x?.clear&&Ya(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),Yn(),mn(),ko(),hn({restoreFocus:!1}),Lr(),M||St?.launcher.element.focus()}return cl(a?Ue.identityResetNotice:Ue.identityResetUnconfirmedNotice),m.emit("history:identityReset",{remoteRevocationConfirmed:a,timestamp:Date.now()}),{remoteRevocationConfirmed:a}},np=()=>Qn?B:K,Yf=async a=>await _c({host:np(),title:Ue.deleteConversationConfirmTitle,description:Ue.deleteConversationConfirm,confirmLabel:Ue.deleteConversationConfirmLabel,cancelLabel:Ue.confirmCancelLabel})?(await Vf(a),"deleted"):"cancelled",gw=async()=>{let a=vs()==="verified-user";return await _c({host:np(),title:Ue.clearHistoryConfirmTitle,description:a?Ue.clearHistoryVerifiedConfirm:Ue.clearHistoryConfirm,confirmLabel:Ue.clearHistoryConfirmLabel,cancelLabel:Ue.confirmCancelLabel})?(await Kf(),"cleared"):"cancelled"},fw=async()=>{if(!await _c({host:np(),title:Ue.resetIdentityConfirmTitle,description:Ue.resetIdentityConfirm,confirmLabel:Ue.resetIdentityConfirmLabel,cancelLabel:Ue.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Gf();return{outcome:"reset",remoteRevocationConfirmed:c}},On=v("button","persona-history-earlier");On.type="button",On.textContent=Ue.showEarlierMessagesLabel,On.setAttribute("data-persona-history-earlier",""),Object.assign(On.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let ko=()=>{if(!(no()&&!!sl.nextMessageCursor&&!!O.getActiveConversationId())){On.remove();return}On.textContent=Ue.showEarlierMessagesLabel,On.parentNode!==V&&V.insertBefore(On,V.firstChild)};On.addEventListener("click",()=>{let a=O.getActiveConversationId(),c=sl.nextMessageCursor;if(!a||!c||On.disabled)return;On.disabled=!0;let f=V.scrollHeight,h=V.scrollTop;O.loadOlderMessages(a,c,{scope:vs()}).then(()=>{V.scrollTop=h+(V.scrollHeight-f),So()}).catch(()=>{}).finally(()=>{On.disabled=!1,ko()})});let mw=()=>{let a=Xr({ariaLabel:Ue.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return a.button.addEventListener("click",c=>{if(!(!no()||yf())){if(Ze){hn();return}Bi({invoker:a.button,keyboard:c.detail===0})}}),a},Jf=()=>{if(!no()){to?.remove(),rn=null,to=null;return}if(to&&!to.isConnected&&(rn=null,to=null),!rn&&Te){let h=mw();rn=h.button,to=h.wrapper;let C=X.clearChatButtonWrapper||X.closeButtonWrapper;C?.parentNode&&Te.contains(C)?C.parentNode.insertBefore(to,C):Te.appendChild(to)}if(!rn||!to)return;let a=Ri()||Ze&&tt==="rail";if(to.style.display=a?"none":"",a){document.activeElement===rn&&hl();return}let c=yf();rn.disabled=c,rn.setAttribute("aria-disabled",c?"true":"false");let f=c?Ue.openHistoryBusyLabel:Ue.openHistoryLabel;rn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(rn.removeAttribute("aria-expanded"),rn.removeAttribute("aria-controls")):(rn.setAttribute("aria-expanded",Ze?"true":"false"),rn.setAttribute("aria-controls",Rd))},Sl=!1,hw=()=>{let a=X.clearChatButton;if(a){if(no()){Sl||(Id=a.getAttribute("aria-label")??"",Sl=!0),a.setAttribute("aria-label",Ue.newConversationLabel),a.removeAttribute("title");return}Sl&&(Sl=!1,Id&&a.setAttribute("aria-label",Id))}},Go=()=>{Ue=ju(o.features?.history?.copy),Jf(),Gd(),hw(),ko()};No=Go,fo=a=>{sl=a,Xe?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),xi(a.sendBlocked||wn),ko()},It=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(xn.clear(),Yn(),mn()),cl(a.message),Xe?.view.refresh()},xf(),Go(),Me.push(()=>{al?.(),ll?.(),il+=1,yl(),Xe?.dispose(),Xe?.view.destroy(),Xe=null}),o.clientToken&&O.initClientSession().then(()=>{if(no())return O.reconcileBootConversation({scope:Bd()})}).then(()=>{ko()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Se||o.onSSEEvent)&&O.setSSEEventCallback((a,c)=>{o.onSSEEvent?.(a,c),Ne?.processEvent(a,c),Se?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(c)})});let Xf=()=>{o.resume&&typeof o.reconnectStream=="function"&&O.resumeFromHandle(o.resume)};L?L.then(a=>{if(a){if(a.metadata&&(T=Gu(a.metadata),Q.syncFromMetadata()),a.messages?.length){us=!0;try{O.hydrateMessages(a.messages)}finally{us=!1}}a.artifacts?.length&&O.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{rf=!0,D(),Xf()}):Xf();let Qf=()=>{!ae()||M||!(o.launcher?.composerBar?.expandOnSubmit??!0)||at(!0,"auto")},yw=(a,c)=>a?c?{refs:[...a.refs,...c.refs],finalize:async()=>{let[f,h]=await Promise.allSettled([a.finalize(),c.finalize()]),C=[];return f.status==="fulfilled"?C.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),h.status==="fulfilled"?C.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),Qk(C)}}:a:c,bw=()=>{let c=me.getInlineMessageFields?.();return c&&c.contentSegments.some(h=>h.kind==="mention")?c.contentSegments:void 0},Di=!1,vw=async a=>{let c=me.value.trim(),f=mt?.hasAttachments()??!1,h=c?await(on?.takeInlineCommand(c)??Promise.resolve(null)):null;if(h?.kind==="action"){me.value="",me.style.height="auto",_i(),on?.clear();return}let C=on?.collectForSubmit()??null,E=h?.kind==="server"?h.mentions:null,j=yw(C,E),F=h?.kind==="prompt"?h.sendText:c,Y=!!C&&C.refs.length>0;if(!F&&!f&&!Y&&!E)return;Qf();let U;f&&(U=[],U.push(...mt.getContentParts()),F&&U.push(Wo(F)));let te=h?.kind==="prompt"?void 0:bw();me.value="",me.style.height="auto",_i(),O.sendMessage(F,{contentParts:U,mentions:j??void 0,contentSegments:te,viaVoice:a?.viaVoice}),f&&mt.clearAttachments(),C&&on?.clear()},op=async a=>{if(!Di){Di=!0;try{await vw(a)}finally{Di=!1}}},Al=a=>{if(a.preventDefault(),O.isStreaming()){O.cancel(),Ne?.reset(),it?.update();return}Di||op()},Cw=()=>o.features?.composerHistory!==!1,rp={...ru},sp=!1,_i=()=>{rp={...ru}},ww=()=>O.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),xw=a=>{if(!me)return;sp=!0,me.value=a,me.dispatchEvent(new Event("input",{bubbles:!0})),sp=!1;let c=me.value.length;me.setSelectionRange(c,c)},Sw=a=>{sp||(a.isComposing||on?.handleInput(a.inputType??void 0),_i())},Aw=a=>{if(me&&!(!a.isComposing&&on?.handleKeydown(a))){if(Cw()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let c=me.selectionStart===0&&me.selectionEnd===0,f=Iy({direction:a.key==="ArrowUp"?"up":"down",history:ww(),currentValue:me.value,atStart:c,state:rp});if(rp=f.state,f.handled){a.preventDefault(),f.value!==void 0&&xw(f.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(O.isStreaming()){a.preventDefault();return}if(Di){a.preventDefault();return}_i(),a.preventDefault(),ye.click()}}},Zf=a=>{a.key!=="Escape"||a.isComposing||O.isStreaming()&&a.composedPath().includes(K)&&(O.cancel(),Ne?.reset(),it?.update(),_i(),a.preventDefault(),a.stopImmediatePropagation())},Tw=async a=>{if(o.attachments?.enabled!==!0||!mt)return;let c=Gk(a.clipboardData);c.length!==0&&(a.preventDefault(),await mt.handleFiles(c))},Dn=null,oo=!1,As=null,yt=null,em=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Tl=(a="user")=>{if(oo||O.isStreaming())return;let c=em();if(!c)return;Dn=new c;let h=(o.voiceRecognition??{}).pauseDuration??2e3;Dn.continuous=!0,Dn.interimResults=!0,Dn.lang="en-US";let C=me.value;Dn.onresult=E=>{let j="",F="";for(let U=0;U<E.results.length;U++){let te=E.results[U],se=te[0].transcript;te.isFinal?j+=se+" ":F=se}let Y=C+j+F;me.value=Y,As&&clearTimeout(As),(j||F)&&(As=window.setTimeout(()=>{me.value.trim()&&Dn&&oo&&(Yo(),op({viaVoice:!0}))},h))},Dn.onerror=E=>{E.error!=="no-speech"&&Yo()},Dn.onend=()=>{if(oo){let E=me.value.trim();E&&E!==C.trim()&&op({viaVoice:!0}),Yo()}};try{if(Dn.start(),oo=!0,$e.active=!0,a!=="system"&&($e.manuallyDeactivated=!1),xo(a),Gn(),oe){let E=o.voiceRecognition??{};yt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let j=E.recordingBackgroundColor,F=E.recordingIconColor,Y=E.recordingBorderColor;if(oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=j??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let U=oe.querySelector("svg");U&&U.setAttribute("stroke",F)}Y&&(oe.style.borderColor=Y),oe.setAttribute("aria-label","Stop voice recognition")}}catch{Yo("system")}},Yo=(a="user")=>{if(oo){if(oo=!1,As&&(clearTimeout(As),As=null),Dn){try{Dn.stop()}catch{}Dn=null}if($e.active=!1,xo(a),Gn(),oe){if(oe.classList.remove("persona-voice-recording"),yt){oe.style.backgroundColor=yt.backgroundColor,oe.style.color=yt.color,oe.style.borderColor=yt.borderColor;let c=oe.querySelector("svg");c&&c.setAttribute("stroke",yt.color||"currentColor"),yt=null}oe.setAttribute("aria-label","Start voice recognition")}}},Ew=(a,c)=>{let f=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),h=a?.provider?.type==="runtype",C=a?.provider?.type==="custom";if(!(f||h||C))return null;let j=v("div","persona-send-button-wrapper"),F=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let Y=a?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",Y);let U=a?.iconName??"mic",te=c?.size??"40px",se=a?.iconSize??te,ge=parseFloat(se)||24,Ye=a?.backgroundColor??c?.backgroundColor,bt=a?.iconColor??c?.textColor;F.style.width=se,F.style.height=se,F.style.minWidth=se,F.style.minHeight=se,F.style.fontSize="18px",F.style.lineHeight="1",bt?F.style.color=bt:F.style.color="var(--persona-text, #111827)";let yn=ce(U,ge,bt||"currentColor",1.5);yn?F.appendChild(yn):F.textContent="\u{1F3A4}",Ye?F.style.backgroundColor=Ye:F.style.backgroundColor="",a?.borderWidth&&(F.style.borderWidth=a.borderWidth,F.style.borderStyle="solid"),a?.borderColor&&(F.style.borderColor=a.borderColor),a?.paddingX&&(F.style.paddingLeft=a.paddingX,F.style.paddingRight=a.paddingX),a?.paddingY&&(F.style.paddingTop=a.paddingY,F.style.paddingBottom=a.paddingY),j.appendChild(F);let Tt=a?.showTooltip??!1;return Xt({anchor:F,trigger:j,text:()=>F.getAttribute("aria-label")??Y,enabled:Tt}),{micButton:F,micButtonWrapper:j}},ip=()=>{if(!oe||yt)return;let a=o.voiceRecognition??{};yt={backgroundColor:oe.style.backgroundColor,color:oe.style.color,borderColor:oe.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},ap=(a,c)=>{if(!oe)return;let f=oe.querySelector("svg");f&&f.remove();let h=yt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),C=ce(a,h,c,1.5);C&&oe.appendChild(C)},El=()=>{oe&&oe.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ts=()=>{if(!oe)return;ip();let a=o.voiceRecognition??{},c=a.recordingBackgroundColor,f=a.recordingIconColor,h=a.recordingBorderColor;if(El(),oe.classList.add("persona-voice-recording"),oe.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",oe.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let C=oe.querySelector("svg");C&&C.setAttribute("stroke",f)}h&&(oe.style.borderColor=h),oe.setAttribute("aria-label","Stop voice recognition")},Mw=()=>{if(!oe)return;ip();let a=o.voiceRecognition??{},c=O.getVoiceInterruptionMode(),f=a.processingIconName??"loader",h=a.processingIconColor??yt?.color??"",C=a.processingBackgroundColor??yt?.backgroundColor??"",E=a.processingBorderColor??yt?.borderColor??"";El(),oe.classList.add("persona-voice-processing"),oe.style.backgroundColor=C,oe.style.borderColor=E;let j=h||"currentColor";oe.style.color=j,ap(f,j),oe.setAttribute("aria-label","Processing voice input"),c==="none"&&(oe.style.cursor="default")},kw=()=>{if(!oe)return;ip();let a=o.voiceRecognition??{},c=O.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",h=a.speakingIconName??f,C=a.speakingIconColor??(c==="barge-in"?a.recordingIconColor??yt?.color??"":yt?.color??""),E=a.speakingBackgroundColor??(c==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":yt?.backgroundColor??""),j=a.speakingBorderColor??(c==="barge-in"?a.recordingBorderColor??"":yt?.borderColor??"");El(),oe.classList.add("persona-voice-speaking"),oe.style.backgroundColor=E,oe.style.borderColor=j;let F=C||"currentColor";oe.style.color=F,ap(h,F);let Y=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";oe.setAttribute("aria-label",Y),c==="none"&&(oe.style.cursor="default"),c==="barge-in"&&oe.classList.add("persona-voice-recording")},Po=()=>{oe&&(El(),yt&&(oe.style.backgroundColor=yt.backgroundColor??"",oe.style.color=yt.color??"",oe.style.borderColor=yt.borderColor??"",ap(yt.iconName,yt.color||"currentColor"),yt=null),oe.style.cursor="",oe.setAttribute("aria-label","Start voice recognition"))},Es=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=O.getVoiceStatus(),c=O.getVoiceInterruptionMode();if(c==="none"&&(a==="processing"||a==="speaking"))return;if(c==="cancel"&&(a==="processing"||a==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{$e.active=!1,$e.manuallyDeactivated=!0,Gn(),xo("user"),Po()});return}O.toggleVoice().then(()=>{$e.active=O.isVoiceActive(),$e.manuallyDeactivated=!O.isVoiceActive(),Gn(),xo("user"),O.isVoiceActive()?Ts():Po()});return}if(oo){let a=me.value.trim();$e.manuallyDeactivated=!0,Gn(),Yo("user"),a&&(me.value="",me.style.height="auto",O.sendMessage(a))}else $e.manuallyDeactivated=!1,Gn(),Tl("user")};gg=Es,oe&&(oe.addEventListener("click",Es),Me.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Po()):Yo("system"),oe&&oe.removeEventListener("click",Es)}));let Pw=m.on("assistant:complete",()=>{Kg&&($e.active||$e.manuallyDeactivated||Kg==="assistant"&&!$e.lastUserMessageWasVoice||setTimeout(()=>{!$e.active&&!$e.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{$e.active=O.isVoiceActive(),xo("auto"),O.isVoiceActive()&&Ts()}):Tl("auto"))},600))});Me.push(Pw);let Lw=m.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});Me.push(Lw);let tm=()=>{at(!M,"user")},St=null,sn=null;if($&&!ae()){let{instance:a,element:c}=Au({config:o,plugins:i,onToggle:tm});St=a,a||(sn=c)}St?e.appendChild(St.element):sn&&e.appendChild(sn),wi(),ds(),Sd(),xd(),xi(O.isStreaming()),md()||(Cn()==="follow"?qo(!0):Ja()),dC(),pe&&(!$||ae()?setTimeout(()=>Lr(),0):M&&setTimeout(()=>Lr(),200));let Ni=()=>{if(ae()){yr(),wi();return}let a=wt(o),c=o.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640,E=f.innerWidth<=C,j=h&&E&&$;try{if(j){br(),ui=za();return}let F=!1;ne&&(ne=!1,br(),F=!0);let Y=za();if(!F&&Y!==ui&&(br(),F=!0),ui=Y,F&&od(),!$&&!a){B.style.height="",B.style.width="";return}if(!c&&!a){let te=o?.launcher?.width??o?.launcherWidth??jn;B.style.width=te,B.style.maxWidth=te}ja(),Ig()}finally{if(yr(),wi(),M&&$){let Y=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),U=o.launcher?.sidebarMode??!1,te=o.launcher?.mobileFullscreen??!0,se=wt(o)&&te&&Y,ge=U||te&&Y&&$||se;if(ge&&!eo){let Ye=e.getRootNode(),bt=Ye instanceof ShadowRoot?Ye.host:e.closest(".persona-host");bt&&!Zn&&(Zn=lu(bt,o.launcher?.zIndex??Jt)),eo=cu(e.ownerDocument)}else ge||(Zn?.(),Zn=null,eo?.(),eo=null)}}};Ni();let Ml=e.ownerDocument.defaultView??window;if(Ml.addEventListener("resize",Ni),Me.push(()=>Ml.removeEventListener("resize",Ni)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{yr()});a.observe(Fe),Me.push(()=>a.disconnect());let c=new ResizeObserver(()=>{ml()});c.observe(K),Me.push(()=>c.disconnect())}Ml.addEventListener("resize",ml),Me.push(()=>Ml.removeEventListener("resize",ml)),An=V.scrollTop;let nm=po(V),om=()=>{let a=V.scrollTop,c=po(V),f=c<nm;if(nm=c,!$o()){An=a,Ft();return}let{action:h,nextLastScrollTop:C}=Fy({following:Sn.isFollowing(),currentScrollTop:a,lastScrollTop:An,nearBottom:Jr(V,Co),userScrollThreshold:iC,isAutoScrolling:fn||qa||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=C,h==="resume"){Xa()||mn();return}h==="pause"&&hi()};if(V.addEventListener("scroll",om,{passive:!0}),Me.push(()=>V.removeEventListener("scroll",om)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{yC(),mp(le)});a.observe(le),a.observe(V),Me.push(()=>a.disconnect())}let rm=()=>{$o()&&Sn.isFollowing()&&Xa()&&hi()},sm=V.ownerDocument;sm.addEventListener("selectionchange",rm),Me.push(()=>{sm.removeEventListener("selectionchange",rm)});let Hw=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),im=a=>{Hw.has(a.key)&&(Mr(),lg()&&$o()&&Sn.isFollowing()&&hi())},am=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(Mr(),lg()&&$o()&&Sn.isFollowing()&&hi())};V.addEventListener("keydown",im),V.addEventListener("focusin",am),Me.push(()=>{V.removeEventListener("keydown",im),V.removeEventListener("focusin",am)});let lm=a=>{if(a.deltaY!==0&&Mr(),!$o())return;let c=$y({following:Sn.isFollowing(),deltaY:a.deltaY,nearBottom:Jr(V,Co),resumeWhenNearBottom:!0});c==="pause"?hi():c==="resume"&&!Xa()&&mn()};V.addEventListener("wheel",lm,{passive:!0}),V.addEventListener("touchmove",Mr,{passive:!0}),V.addEventListener("pointerdown",Mr,{passive:!0}),Me.push(()=>{V.removeEventListener("touchmove",Mr),V.removeEventListener("pointerdown",Mr)}),Me.push(()=>V.removeEventListener("wheel",lm)),Rt.addEventListener("click",()=>{Yn(),V.scrollTop=V.scrollHeight,An=V.scrollTop,mn(),qo(!0),Ft()}),Me.push(()=>Rt.remove()),Me.push(()=>{Jg(),Yn()});let cm=()=>{We&&(xr&&(We.removeEventListener("click",xr),xr=null),ie()?(We.style.display="",xr=()=>{at(!1,"user")},We.addEventListener("click",xr)):We.style.display="none")};cm(),(()=>{let{clearChatButton:a}=X;a&&a.addEventListener("click",()=>{if(no()){ep({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}O.clearMessages(),xn.clear(),mn(),jr(X.composerOverlay);try{localStorage.removeItem(ri),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ri}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ri)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),x?.clear&&Ya(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},Q.syncFromMetadata(),Se?.clear(),Ne?.reset(),it?.update()})})(),ze&&ze.addEventListener("submit",Al);let dm=[["keydown",Aw],["input",Sw],["paste",Tw],["focus",Qv]],lp=a=>{if(a)for(let[c,f]of dm)a.addEventListener(c,f)},cp=a=>{if(a)for(let[c,f]of dm)a.removeEventListener(c,f)};lp(me);let pm=()=>{on?.onComposerSwap((a,c)=>{cp(c),me=a,lp(a)})};pm();let dp=!1;function Iw(){if(!dp){dp=!0;try{let a=me?.value??"",c=Fe.ownerDocument??document,f=me?c.activeElement===me:!1;cp(me),ze?.removeEventListener("submit",Al),oe?.removeEventListener("click",Es),on?.destroy(),on=null;let h=null,C=()=>(h=ae()?Ac({config:o}):Js({config:o}),h.footer),E=yg(C)??C();H.replaceComposer(E),Fe=H.composer.footer;let j=h!==null&&E===h.footer;ci=!j,ag=j?h.setSendButtonMode:()=>{},hg(Fe),vg(Fe),Cg(),wg(),xg(),pm(),ze&&ze.addEventListener("submit",Al),lp(me),oe?.addEventListener("click",Es);let F=wr.indexOf(vo);vo.destroy(),vo=Ea(Ct),F>=0&&(wr[F]=vo),me&&(me.value=a),Sd(),ds(),xi(O.isStreaming()),br(),yr(),f&&me?.focus()}finally{dp=!1}}}let um=e.ownerDocument??document;um.addEventListener("keydown",Zf,!0);let gm="persona-attachment-drop-active",Fi=0,pp=()=>{Fi=0,K.classList.remove(gm)},Ms=()=>o.attachments?.enabled===!0&&mt!==null,fm=a=>{!Fc(a.dataTransfer)||!Ms()||(Fi++,Fi===1&&K.classList.add(gm))},mm=a=>{!Fc(a.dataTransfer)||!Ms()||(Fi--,Fi<=0&&pp())},hm=a=>{!Fc(a.dataTransfer)||!Ms()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},ym=a=>{if(!Fc(a.dataTransfer)||!Ms())return;a.preventDefault(),a.stopPropagation(),pp();let c=Array.from(a.dataTransfer.files??[]);c.length!==0&&mt.handleFiles(c)},Jo=!0;K.addEventListener("dragenter",fm,Jo),K.addEventListener("dragleave",mm,Jo),e.addEventListener("dragover",hm,Jo),e.addEventListener("drop",ym,Jo);let kl=e.ownerDocument,bm=a=>{Ms()&&a.preventDefault()},vm=a=>{Ms()&&a.preventDefault()};kl.addEventListener("dragover",bm),kl.addEventListener("drop",vm),Me.push(()=>{ze&&ze.removeEventListener("submit",Al),cp(me),um.removeEventListener("keydown",Zf,!0),on?.destroy()}),Me.push(()=>{K.removeEventListener("dragenter",fm,Jo),K.removeEventListener("dragleave",mm,Jo),e.removeEventListener("dragover",hm,Jo),e.removeEventListener("drop",ym,Jo),kl.removeEventListener("dragover",bm),kl.removeEventListener("drop",vm),pp()}),Me.push(()=>{O.cancel()}),St?Me.push(()=>{St?.destroy()}):sn&&Me.push(()=>{sn?.remove()});let At={update(a){let c=o.toolCall,f=o.messageActions,h=o.layout?.messages,C=o.colorScheme,E=o.loadingIndicator,j=o.iterationDisplay,F=o.features?.showReasoning,Y=o.features?.showToolCalls,U=o.features?.toolCallDisplay,te=o.features?.reasoningDisplay,se=o.features?.streamAnimation?.type,ge=o.features?.history?.enabled===!0,Ye=o.features?.history?.provider,bt=o.getIdentityProof,qt=o.clientToken;o=Bc({...o,features:s},a),s=o.features,o=Rc(o),r(),sd(),$s(e,o),Ra(e,o),Wa(e,o),Qt(),bo(),o.colorScheme!==C&&Rg();let yn=Wc.getForInstance(o.plugins);i.length=0,i.push(...yn),Lf(),$=o.launcher?.enabled??!0,J=o.launcher?.autoExpand??!1,xe=o.features?.showReasoning??!0,Pe=o.features?.showToolCalls??!0,Je=o.features?.scrollToBottom??{};let Tt=Cn();Be=o.features?.scrollBehavior??{},Tt!==Cn()&&(Yn(),mn()),Vg(),ug(),Ft();let kt=Le;if(Le=o.features?.showEventStreamToggle??!1,Le&&!kt){if(Se||(_e=new Ha(be),Se=new La(gt,_e),Ne=Ne??new Ia,_e.open().then(()=>Se?.restore()).catch(()=>{}),O.setSSEEventCallback((re,je)=>{o.onSSEEvent?.(re,je),Ne?.processEvent(re,je),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(je)})})),!Ge&&Te){let re=o.features?.eventStream?.classNames,je="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(re?.toggleButton?" "+re.toggleButton:"");Ge=v("button",je),Ge.style.width="28px",Ge.style.height="28px",Ge.style.color=pn.actionIconColor,Ge.type="button",Ge.setAttribute("aria-label","Event Stream"),Ge.title="Event Stream";let Ke=ce("activity","18px","currentColor",1.5);Ke&&Ge.appendChild(Ke);let ut=X.clearChatButtonWrapper,nt=X.closeButtonWrapper,Yt=ut||nt;Yt&&Yt.parentNode===Te?Te.insertBefore(Ge,Yt):Te.appendChild(Ge),Ge.addEventListener("click",()=>{Kt?is():Qc()})}}else!Le&&kt&&(is(),Ge&&(Ge.remove(),Ge=null),Se?.clear(),_e?.destroy(),Se=null,_e=null,Ne?.reset(),Ne=null);if(o.launcher?.enabled===!1&&St&&(St.destroy(),St=null),o.launcher?.enabled===!1&&sn&&(sn.remove(),sn=null),o.launcher?.enabled!==!1&&!St&&!sn){let{instance:re,element:je}=Au({config:o,plugins:i,onToggle:tm});St=re,re||(sn=je),e.appendChild(je)}St&&St.update(o),Oi(),mr&&o.launcher?.subtitle!==void 0&&(mr.textContent=o.launcher.subtitle);let _=o.layout?.header;if(_?.layout!==he&&Te){let re=_?Ma(o,_,{showClose:ie(),onClose:()=>at(!1,"user")}):ur({config:o,showClose:ie(),onClose:()=>at(!1,"user")});H.replaceHeader(re),Te=H.header.element,xt=H.header.iconHolder,Fo=H.header.headerTitle,mr=H.header.headerSubtitle,We=H.header.closeButton,he=_?.layout,Oi()}else if(_){if(xt&&(xt.style.display=_.showIcon===!1?"none":""),Fo&&(Fo.style.display=_.showTitle===!1?"none":""),mr&&(mr.style.display=_.showSubtitle===!1?"none":""),We){let re=ie()&&_.showCloseButton!==!1;We.style.display=re?"":"none"}if(X.clearChatButtonWrapper){let re=_.showClearChat;if(re!==void 0){X.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:je}=X;je&&!je.classList.contains("persona-absolute")&&(re?je.classList.remove("persona-ml-auto"):je.classList.add("persona-ml-auto"))}}}let He=o.layout?.showHeader!==!1;Te&&(Te.style.display=He?"":"none");let Ae=o.layout?.showFooter!==!1;Fe&&(Fe.style.display=Ae?"":"none"),yr(),Ft(),$!==ve?$?at(J,"auto"):(M=!0,wi()):J!==we&&at(J,"auto"),we=J,ve=$,Ni(),cm();let Vt=JSON.stringify(o.toolCall)!==JSON.stringify(c),lt=JSON.stringify(o.messageActions)!==JSON.stringify(f),an=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),Gt=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,$t=o.iterationDisplay!==j,Ie=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(Y??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(U)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(te);(Vt||lt||an||Gt||$t||Ie)&&O&&(ad++,yi(le,O.getMessages(),fe));let jt=o.features?.streamAnimation?.type;if(jt!==se&&jt&&jt!=="none"){let re=Vs(jt,o.features?.streamAnimation?.plugins);re&&hc(re,e)}let Ee=o.launcher??{},Wt=Ee.headerIconHidden??!1,pt=o.layout?.header?.showIcon,qe=Wt||pt===!1,Bt=Ee.headerIconName,Pt=Ee.headerIconSize??"48px";if(xt){let re=Te,je=re?.querySelector(".persona-flex-col");if(qe)xt.style.display="none",re&&je&&!re.contains(je)&&re.insertBefore(je,re.firstChild);else{if(xt.style.display="",xt.style.height=Pt,xt.style.width=Pt,re&&je&&(re.contains(xt)?xt.nextSibling!==je&&(xt.remove(),re.insertBefore(xt,je)):re.insertBefore(xt,je)),Bt){let ut=parseFloat(Pt)||24,nt=ce(Bt,ut*.6,"currentColor",1);nt?xt.replaceChildren(nt):xt.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let ut=xt.querySelector("img");if(ut)ut.src=Ee.iconUrl,ut.style.height=Pt,ut.style.width=Pt;else{let nt=document.createElement("img");nt.src=Ee.iconUrl,nt.alt="",nt.className="persona-rounded-xl persona-object-cover",nt.style.height=Pt,nt.style.width=Pt,xt.replaceChildren(nt)}}else{let ut=xt.querySelector("svg"),nt=xt.querySelector("img");(ut||nt)&&xt.replaceChildren(),xt.textContent=Ee.agentIconText??"\u{1F4AC}"}let Ke=xt.querySelector("img");Ke&&(Ke.style.height=Pt,Ke.style.width=Pt)}}let en=o.layout?.header?.showTitle,Nn=o.layout?.header?.showSubtitle;if(Fo&&(Fo.style.display=en===!1?"none":""),mr&&(mr.style.display=Nn===!1?"none":""),We){let re=ie()&&o.layout?.header?.showCloseButton!==!1;if(We.style.display=re?"":"none",!ae()){let Ht=Ee.closeButtonSize??"";We.style.height=Ht,We.style.width=Ht,We.style.minWidth=Ht,We.style.minHeight=Ht}let je=Ee.closeButtonPlacement??"inline",{closeButtonWrapper:Ke}=X,ut=je==="top-right",nt=Ke?.classList.contains("persona-absolute");if(Ke&&ut!==nt)if(Ke.remove(),ut){Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Ht=ki??K;Ht.style.position="relative",Ht.appendChild(Ke)}else{let Ht=Ee.clearChat?.placement??"inline",Dt=Ee.clearChat?.enabled??!0;Ke.className=Dt&&Ht==="inline"?"":"persona-ml-auto",Te&&Te.appendChild(Ke)}if(We.style.color=Ee.closeButtonColor||pn.actionIconColor,Ee.closeButtonBackgroundColor?(We.style.backgroundColor=Ee.closeButtonBackgroundColor,We.classList.remove("hover:persona-bg-gray-100")):(We.style.backgroundColor="",We.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let Ht=Ee.closeButtonBorderWidth||"0px",Dt=Ee.closeButtonBorderColor||"transparent";We.style.border=`${Ht} solid ${Dt}`,We.classList.remove("persona-border-none")}else We.style.border="",We.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(We.style.borderRadius=Ee.closeButtonBorderRadius,We.classList.remove("persona-rounded-full")):(We.style.borderRadius="",We.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(We.style.paddingLeft=Ee.closeButtonPaddingX,We.style.paddingRight=Ee.closeButtonPaddingX):(We.style.paddingLeft="",We.style.paddingRight=""),Ee.closeButtonPaddingY?(We.style.paddingTop=Ee.closeButtonPaddingY,We.style.paddingBottom=Ee.closeButtonPaddingY):(We.style.paddingTop="",We.style.paddingBottom=""),yc(We,Ee.closeButtonIconName??"x",{iconSize:ae()?Cu:void 0,iconText:Ee.closeButtonIconText??"\xD7"});let Yt=Ee.closeButtonTooltipText??"Close chat",bn=Ee.closeButtonShowTooltip??!0;We.setAttribute("aria-label",Yt),Ke&&Xt({anchor:We,trigger:Ke,text:()=>We?.getAttribute("aria-label")??Yt,enabled:bn})}let{clearChatButton:Ve,clearChatButtonWrapper:tn}=X;if(Ve){let re=Ee.clearChat??{},je=re.enabled??!0,Ke=o.layout?.header?.showClearChat,ut=Ke!==void 0?Ke:je,nt=re.placement??"inline";if(tn){tn.style.display=ut?"":"none";let{closeButtonWrapper:Yt}=X;!ae()&&Yt&&!Yt.classList.contains("persona-absolute")&&(ut?Yt.classList.remove("persona-ml-auto"):Yt.classList.add("persona-ml-auto"));let bn=nt==="top-right",Ht=tn.classList.contains("persona-absolute");if(!ae()&&bn!==Ht&&ut){if(tn.remove(),bn){tn.className="persona-absolute persona-top-4 persona-z-50",tn.style.right="48px";let Mn=ki??K;Mn.style.position="relative",Mn.appendChild(tn)}else{tn.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",tn.style.right="";let Mn=X.closeButtonWrapper;Te&&Mn&&Mn.parentElement===Te?Te.insertBefore(tn,Mn):Te&&Te.appendChild(tn)}let Dt=X.closeButtonWrapper;Dt&&!Dt.classList.contains("persona-absolute")&&(bn?Dt.classList.add("persona-ml-auto"):Dt.classList.remove("persona-ml-auto"))}}if(ut){if(!ae()){let Dt=re.size??"";Ve.style.height=Dt,Ve.style.width=Dt,Ve.style.minWidth=Dt,Ve.style.minHeight=Dt}let Yt=re.iconColor??"";if(Ve.style.color=Yt||pn.actionIconColor,yc(Ve,re.iconName??"refresh-cw",{iconSize:ae()?wu:void 0}),re.backgroundColor?(Ve.style.backgroundColor=re.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let Dt=re.borderWidth||"0px",Mn=re.borderColor||"transparent";Ve.style.border=`${Dt} solid ${Mn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");re.borderRadius?(Ve.style.borderRadius=re.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),re.paddingX?(Ve.style.paddingLeft=re.paddingX,Ve.style.paddingRight=re.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),re.paddingY?(Ve.style.paddingTop=re.paddingY,Ve.style.paddingBottom=re.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let bn=re.tooltipText??"Clear chat",Ht=re.showTooltip??!0;Ve.setAttribute("aria-label",bn),tn&&Xt({anchor:Ve,trigger:tn,text:()=>Ve?.getAttribute("aria-label")??bn,enabled:Ht})}}let Lt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Oc],cn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[oi.message,oi.messageAndClick];Q=Dc({parsers:Lt,handlers:cn,getSessionMetadata:I,updateSessionMetadata:R,emit:m.emit,documentRef:typeof document<"u"?document:null}),fe=iv(o,Q,Ce),IC(),O.updateConfig(o),(o.features?.history?.enabled===!0!==ge||o.features?.history?.provider!==Ye||o.getIdentityProof!==bt||o.clientToken!==qt)&&(hn({restoreFocus:!1}),xf()),Go(),ml(),yi(le,O.getMessages(),fe),ds(),Sd(),LC(),xi(O.isStreaming());let $i=o.voiceRecognition?.enabled===!0,Cm=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),ji=o.voiceRecognition?.provider?.type==="runtype";if($i&&(Cm||ji))if(!oe||!mo){let re=Ew(o.voiceRecognition,o.sendButton);re&&(oe=re.micButton,mo=re.micButtonWrapper,Kv.insertBefore(mo,Zt),oe.addEventListener("click",Es),oe.disabled=O.isStreaming())}else{let re=o.voiceRecognition??{},je=o.sendButton??{},Ke=re.iconName??"mic",ut=je.size??"40px",nt=re.iconSize??ut,Yt=parseFloat(nt)||24;oe.style.width=nt,oe.style.height=nt,oe.style.minWidth=nt,oe.style.minHeight=nt;let bn=re.iconColor??je.textColor;oe.innerHTML="";let Ht=ce(Ke,Yt,bn||"currentColor",1.5);Ht?oe.appendChild(Ht):oe.textContent="\u{1F3A4}";let Dt=re.backgroundColor??je.backgroundColor;Dt?oe.style.backgroundColor=Dt:oe.style.backgroundColor="",bn?oe.style.color=bn:oe.style.color="var(--persona-text, #111827)",re.borderWidth?(oe.style.borderWidth=re.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),re.borderColor?oe.style.borderColor=re.borderColor:oe.style.borderColor="",re.paddingX?(oe.style.paddingLeft=re.paddingX,oe.style.paddingRight=re.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),re.paddingY?(oe.style.paddingTop=re.paddingY,oe.style.paddingBottom=re.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Mn=re.tooltipText??"Start voice recognition",Ow=re.showTooltip??!1;oe.setAttribute("aria-label",Mn),mo&&Xt({anchor:oe,trigger:mo,text:()=>oe?.getAttribute("aria-label")??Mn,enabled:Ow}),mo.style.display="",oe.disabled=O.isStreaming()}else oe&&mo&&(mo.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()&&O.toggleVoice():oo&&Yo());if(o.attachments?.enabled===!0){if(!In||!ft){let re=o.attachments??{},Ke=(o.sendButton??{}).size??"40px";qn||(qn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),qn.style.display="none",ze.insertBefore(qn,me)),Mt||(Mt=document.createElement("input"),Mt.type="file",Mt.accept=(re.allowedTypes??Bo).join(","),Mt.multiple=(re.maxFiles??4)>1,Mt.style.display="none",Mt.setAttribute("aria-label","Attach files"),ze.insertBefore(Mt,me)),In=v("div","persona-send-button-wrapper"),ft=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ft.type="button",ft.setAttribute("aria-label",re.buttonTooltipText??"Attach file");let ut=re.buttonIconName??"paperclip",nt=Ke,Yt=parseFloat(nt)||40,bn=Math.round(Yt*.6);ft.style.width=nt,ft.style.height=nt,ft.style.minWidth=nt,ft.style.minHeight=nt,ft.style.fontSize="18px",ft.style.lineHeight="1";let Ht=ce(ut,bn,"currentColor",1.5);Ht?ft.appendChild(Ht):ft.textContent="\u{1F4CE}",ft.addEventListener("click",Mn=>{Mn.preventDefault(),Mt?.click()}),In.appendChild(ft);let Dt=re.buttonTooltipText??"Attach file";Xt({anchor:ft,trigger:In,text:()=>ft?.getAttribute("aria-label")??Dt}),ss?ss.append(In):ze.appendChild(In),!mt&&Mt&&qn&&(mt=_s.fromConfig(re),mt.setPreviewsContainer(qn),Mt.addEventListener("change",async()=>{mt&&Mt?.files&&(await mt.handleFileSelect(Mt.files),Mt.value="")}))}else{In.style.display="";let re=o.attachments??{};Mt&&(Mt.accept=(re.allowedTypes??Bo).join(","),Mt.multiple=(re.maxFiles??4)>1),mt&&mt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}if(K.querySelector(".persona-attachment-drop-overlay")?.remove(),K.appendChild(av(o.attachments?.dropOverlay)),ft){let re=o.attachments??{},je=re.buttonTooltipText??"Attach file";ft.setAttribute("aria-label",je),ft.textContent="";let Ke=parseFloat(o.sendButton?.size??"40px")||40,ut=ce(re.buttonIconName??"paperclip",Math.round(Ke*.6),"currentColor",1.5);ut?ft.appendChild(ut):ft.textContent="\u{1F4CE}",In&&Xt({anchor:ft,trigger:In,text:()=>ft?.getAttribute("aria-label")??je})}}else In&&(In.style.display="none"),mt&&mt.clearAttachments(),K.querySelector(".persona-attachment-drop-overlay")?.remove();let Ot=o.sendButton??{},up=Ot.useIcon??!1,Ll=Ot.iconText??"\u2191",_r=Ot.iconName,Hl=Ot.tooltipText??"Send message",Rw=Ot.showTooltip??!1,zi=Ot.size??"40px",Il=Ot.backgroundColor,Ui=Ot.textColor;if(up){if(ye.style.width=zi,ye.style.height=zi,ye.style.minWidth=zi,ye.style.minHeight=zi,ye.style.fontSize="18px",ye.style.lineHeight="1",Ui?ye.style.color=Ui:ye.style.color="var(--persona-button-primary-fg, #ffffff)",!O.isStreaming())if(ye.innerHTML="",_r){let re=parseFloat(zi)||24,je=Ui?.trim()||"currentColor",Ke=ce(_r,re,je,2);Ke?ye.appendChild(Ke):ye.textContent=Ll}else ye.textContent=Ll;ye.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Il?(ye.style.backgroundColor=Il,ye.classList.remove("persona-bg-persona-primary")):(ye.style.backgroundColor="",ye.classList.add("persona-bg-persona-primary"))}else ye.textContent=o.copy?.sendButtonLabel??"Send",ye.style.width="",ye.style.height="",ye.style.minWidth="",ye.style.minHeight="",ye.style.fontSize="",ye.style.lineHeight="",ye.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",Il?(ye.style.backgroundColor=Il,ye.classList.remove("persona-bg-persona-accent")):ye.classList.add("persona-bg-persona-accent"),Ui?ye.style.color=Ui:ye.classList.add("persona-text-white");Ot.borderWidth?(ye.style.borderWidth=Ot.borderWidth,ye.style.borderStyle="solid"):(ye.style.borderWidth="",ye.style.borderStyle=""),Ot.borderColor?ye.style.borderColor=Ot.borderColor:ye.style.borderColor="",Ot.paddingX?(ye.style.paddingLeft=Ot.paddingX,ye.style.paddingRight=Ot.paddingX):(ye.style.paddingLeft="",ye.style.paddingRight=""),Ot.paddingY?(ye.style.paddingTop=Ot.paddingY,ye.style.paddingBottom=Ot.paddingY):(ye.style.paddingTop="",ye.style.paddingBottom=""),O.isStreaming()||ye.setAttribute("aria-label",Hl),Zt&&Xt({anchor:ye,trigger:Zt,text:()=>ye.getAttribute("aria-label")??Hl,enabled:Rw});let ks=rr(o,ae());id(),ks?(le.style.maxWidth=ks,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",vn.style.maxWidth=ks,vn.style.marginLeft="auto",vn.style.marginRight="auto",vn.style.width="100%",ze&&(ze.style.maxWidth=ks,ze.style.marginLeft="auto",ze.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=ks,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),nn.style.maxWidth=ks,nn.style.marginLeft="auto",nn.style.marginRight="auto"):(le.style.maxWidth="",le.style.marginLeft="",le.style.marginRight="",le.style.width="",vn.style.maxWidth="",vn.style.marginLeft="",vn.style.marginRight="",vn.style.width="",ze&&(ze.style.maxWidth="",ze.style.marginLeft="",ze.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),nn.style.maxWidth="",nn.style.marginLeft="",nn.style.marginRight="");let Xo=o.statusIndicator??{},Ww=Xo.visible??!0;if(nn.style.display=Ww?"":"none",O){let re=O.getStatus();S(nn,(Ke=>Ke==="idle"?Xo.idleText??_t.idle:Ke==="connecting"?Xo.connectingText??_t.connecting:Ke==="connected"?Xo.connectedText??_t.connected:Ke==="error"?Xo.errorText??_t.error:_t[Ke])(re),Xo,re)}nn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Bw=Xo.align==="left"?"persona-text-left":Xo.align==="center"?"persona-text-center":"persona-text-right";nn.classList.add(Bw),vt()},open(){ie()&&at(!0,"api")},close(){ie()&&at(!1,"api")},toggle(){ie()&&at(!M,"api")},reconnect(){O.reconnectNow()},clearChat(){yo=!1,O.clearMessages(),xn.clear(),mn();try{localStorage.removeItem(ri),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ri}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ri)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),x?.clear&&Ya(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},Q.syncFromMetadata(),Se?.clear(),Ne?.reset(),it?.update()},setMessage(a){return!me||O.isStreaming()?!1:(!M&&ie()&&at(!0,"system"),me.value=a,me.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(O.isStreaming())return!1;let c=a?.trim()||me.value.trim();return c?(!M&&ie()&&at(!0,"system"),me.value="",me.style.height="auto",O.sendMessage(c),!0):!1},startVoiceRecognition(){return O.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()||(!M&&ie()&&at(!0,"system"),$e.manuallyDeactivated=!1,Gn(),O.toggleVoice().then(()=>{$e.active=O.isVoiceActive(),xo("user"),O.isVoiceActive()&&Ts()})),!0):oo?!0:em()?(!M&&ie()&&at(!0,"system"),$e.manuallyDeactivated=!1,Gn(),Tl("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{$e.active=!1,$e.manuallyDeactivated=!0,Gn(),xo("user"),Po()}),!0):!1:oo?($e.manuallyDeactivated=!0,Gn(),Yo("user"),!0):!1},injectMessage(a){return!M&&ie()&&at(!0,"system"),O.injectMessage(a)},injectAssistantMessage(a){!M&&ie()&&at(!0,"system");let c=O.injectAssistantMessage(a);return Z&&(Z=!1,de&&(clearTimeout(de),de=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),c},injectUserMessage(a){return!M&&ie()&&at(!0,"system"),O.injectUserMessage(a)},injectSystemMessage(a){return!M&&ie()&&at(!0,"system"),O.injectSystemMessage(a)},injectMessageBatch(a){return!M&&ie()&&at(!0,"system"),O.injectMessageBatch(a)},injectComponentDirective(a){return!M&&ie()&&at(!0,"system"),O.injectComponentDirective(a)},injectTestMessage(a){!M&&ie()&&at(!0,"system"),O.injectTestEvent(a)},async connectStream(a,c){return O.connectStream(a,c)},__pushEventStreamEvent(a){Se&&(Ne?.processEvent(a.type,a.payload),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!Le||!Se||Qc()},hideEventStream(){Kt&&is()},isEventStreamVisible(){return Kt},listConversations(a){return O.listConversations(a)},getActiveConversationId(){return O.getActiveConversationId()},openConversation(a,c){return Zd(a,{focusComposer:c?.focus===!0})},startNewConversation(a){return ep({focusComposer:a?.focus===!0})},deleteConversation(a){return Vf(a)},renameConversation(a,c){return tp(a,{title:c})},setConversationStarred(a,c){return tp(a,{starred:c})},clearConversationHistory(a){return Kf(a)},resetHistoryIdentity(){return Gf()},getHistoryIdentityStatus(){return Tn?Tn.getIdentityStatus():Wd()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return Bi({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})},hideHistory(a){hn(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return Ze},showArtifacts(){un(o)&&(yo=!1,as=!0,bo(),De?.setMobileOpen(!0))},hideArtifacts(){un(o)&&(yo=!0,bo())},upsertArtifact(a){return un(o)?(Io(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(yo=!1,as=!0),O.upsertArtifact(a)):null},selectArtifact(a){un(o)&&O.selectArtifact(a)},clearArtifacts(){un(o)&&O.clearArtifacts()},getArtifacts(){return O?.getArtifacts()??[]},getSelectedArtifactId(){return O?.getSelectedArtifactId()??null},focusInput(){return $&&!M&&!ae()||!me?!1:(me.focus(),!0)},async resolveApproval(a,c,f){let C=O.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===a);if(!C?.approval)throw new Error(`Approval not found: ${a}`);if(C.approval.toolType==="webmcp"){O.resolveWebMcpApproval(C.id,c);return}return O.resolveApproval(C.approval,c,f)},setFollowUpSuggestions(a){rC(a)},clearFollowUpSuggestions(){qg()},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...T}},updatePersistentMetadata(a){R(a)},on(a,c){return m.on(a,c)},off(a,c){m.off(a,c)},isOpen(){return ie()&&M},isVoiceActive(){return $e.active},toggleReadAloud(a){O.toggleReadAloud(a)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(a){return O.getReadAloudState(a)},onReadAloudChange(a){return O.onReadAloudChange(a)},getState(){return{open:ie()&&M,launcherEnabled:$,voiceActive:$e.active,streaming:O.isStreaming()}},showCSATFeedback(a){!M&&ie()&&at(!0,"system");let c=le.querySelector(".persona-feedback-container");c&&c.remove();let f=Vu({onSubmit:async(h,C)=>{O.isClientTokenMode()&&await O.submitCSATFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!M&&ie()&&at(!0,"system");let c=le.querySelector(".persona-feedback-container");c&&c.remove();let f=Ku({onSubmit:async(h,C)=>{O.isClientTokenMode()&&await O.submitNPSFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});le.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,c){return O.submitCSATFeedback(a,c)},async submitNPSFeedback(a,c){return O.submitNPSFeedback(a,c)},destroy(){Md(),Rr!=null&&(clearInterval(Rr),Rr=null),Me.forEach(a=>a()),P.remove(),G?.remove(),St?.destroy(),sn?.remove(),xr&&We.removeEventListener("click",xr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,c={controller:At,getMessages:At.getMessages,getStatus:At.getStatus,getMetadata:At.getPersistentMetadata,updateMetadata:At.updatePersistentMetadata,clearHistory:()=>At.clearChat(),setVoiceActive:f=>f?At.startVoiceRecognition():At.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Me.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.focusInput()};if(window.addEventListener("persona:focusInput",c),Me.push(()=>{window.removeEventListener("persona:focusInput",c)}),Le){let U=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===a)&&At.showEventStream()},te=se=>{let ge=se.detail;(!ge?.instanceId||ge.instanceId===a)&&At.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",te),Me.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",te)})}let f=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.showHistory()},h=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",h),Me.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",h)});let C=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.showArtifacts()},E=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.hideArtifacts()},j=U=>{let te=U.detail;te?.instanceId&&te.instanceId!==a||te?.artifact&&At.upsertArtifact(te.artifact)},F=U=>{let te=U.detail;te?.instanceId&&te.instanceId!==a||typeof te?.id=="string"&&At.selectArtifact(te.id)},Y=U=>{let te=U.detail;(!te?.instanceId||te.instanceId===a)&&At.clearArtifacts()};window.addEventListener("persona:showArtifacts",C),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",j),window.addEventListener("persona:selectArtifact",F),window.addEventListener("persona:clearArtifacts",Y),Me.push(()=>{window.removeEventListener("persona:showArtifacts",C),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",j),window.removeEventListener("persona:selectArtifact",F),window.removeEventListener("persona:clearArtifacts",Y)})}let _n=Yk(o.persistState);if(_n&&ie()){let a=Jk(_n.storage),c=`${_n.keyPrefix}widget-open`,f=`${_n.keyPrefix}widget-voice`,h=`${_n.keyPrefix}widget-voice-mode`;if(a){let C=_n.persist?.openState&&a.getItem(c)==="true",E=_n.persist?.voiceState&&a.getItem(f)==="true",j=_n.persist?.voiceState&&a.getItem(h)==="true";if(C&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{At.open(),setTimeout(()=>{if(E||j)At.startVoiceRecognition();else if(_n.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0)),_n.persist?.openState&&(m.on("widget:opened",()=>{a.setItem(c,"true")}),m.on("widget:closed",()=>{a.setItem(c,"false")})),_n.persist?.voiceState&&(m.on("voice:state",F=>{a.setItem(f,F.active?"true":"false")}),m.on("user:message",F=>{a.setItem(h,F.viaVoice?"true":"false")})),_n.clearOnChatClear){let F=()=>{a.removeItem(c),a.removeItem(f),a.removeItem(h)},Y=()=>F();window.addEventListener("persona:clear-chat",Y),Me.push(()=>{window.removeEventListener("persona:clear-chat",Y)})}}}if(A&&ie()&&(St?.setPanelOpen(!0,"auto"),setTimeout(()=>{At.open()},0)),hs(),!sC){let a=qi(()=>{O&&(ad++,xn.clear(),yi(le,O.getMessages(),fe))});Me.push(a)}return At};var lv=(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},Zk=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},e0=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},t0=(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.")},cv=(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"},Zu=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=""},dv=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Zu(e)},Ju=e=>{e.style.transition=""},Xu=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=""},Qu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},$c=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},n0=(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))},o0=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},r0=e=>{let t=Kr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:dn(t,r)??r;return{inset:o(n?.inset,Xl),canvasBackground:o(n?.canvasBackground,Ql)}},pv=(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},s0=(e,t,n,o,r,s,i,l)=>{let d=Pn(s),u=d.reveal==="push",p=l!=null,g=l?.inset??"",y=l?.canvasBackground??"";n0(e,t,n,o,u),o0(e,t,n,o,d.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=i?"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 m=e.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=x:!1;if(b&&T&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xu(t),Ju(o),dv(o),Qu(n),$c(r,o),pv(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??Jt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(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"),dv(o),Zk(o,d.maxHeight),pv(o,p&&i,g,y),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xu(t),Ju(o),Qu(n),$c(r,o);let D=d.animate?"transform 180ms ease":"none",k=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=i?"translateX(0)":k;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=D,o.style.transform=A,o.style.pointerEvents=i?"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",Ju(o),Zu(o),$c(r,o);let D=lv(d.width,e.clientWidth),k=Math.max(0,e.clientWidth),A=d.animate?"margin-left 180ms ease":"none",W=d.side==="right"?i?-D:0:i?0:-D;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=`${k+D}px`,t.style.transition=A,t.style.marginLeft=`${W}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}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=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xu(t),Zu(o),Qu(n),$c(r,o);let D=d.reveal==="emerge";D?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=i?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",W=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${k}`,o.style.width=k,o.style.maxWidth=k,o.style.minWidth=k,o.style.minHeight="0",e0(o,d.maxHeight),o.style.overflow=D||W?"hidden":"visible",o.style.transition=A,D){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let I=p?`calc(${lv(d.width,e.clientWidth)}px - (2 * ${g}))`:d.width;r.style.width=I,r.style.minWidth=I,r.style.maxWidth=I,r.style.boxSizing="border-box"}}},i0=(e,t)=>{let n=e.ownerDocument.createElement("div");return cv(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){cv(n,o)},destroy(){n.remove()}}},a0=(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,i=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),p=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),o.insertBefore(i,e),d.appendChild(e);let y=null,m=()=>{y?.disconnect(),y=null},b=null,x=()=>{b=t?.launcher?.detachedPanel===!0?r0(t):null};x();let T=()=>{s0(i,l,d,u,p,t,g,b)},L=null,D=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=ma(()=>{x(),T()}))},k=()=>{m(),Pn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{T()}),y.observe(i)))},A=!1,W=()=>{T(),k(),g&&!A&&i.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,t0(i,Pn(t)))},I=i.ownerDocument.defaultView,R=()=>{W()};return I?.addEventListener("resize",R),Pn(t).reveal==="push"?(l.appendChild(d),l.appendChild(u),i.appendChild(l)):(i.appendChild(d),i.appendChild(u)),W(),D(),{mode:"docked",host:p,shell:i,syncWidgetState(z){let q=z.launcherEnabled?z.open:!0;g!==q&&(g=q,W())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(g=!0),x(),W(),D()},destroy(){I?.removeEventListener("resize",R),L?.(),L=null,m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},jc=(e,t)=>wt(t)?a0(e,t):i0(e,t);var l0=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},uv=(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)},gv=e=>{let t=l0(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=jc(t,r),i,l=[],d=(T,L)=>{let k=!(L?.launcher?.enabled??!0)||wt(L),A=o.createElement("div");if(A.setAttribute("data-persona-root","true"),k&&(A.style.height="100%",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1",A.style.minHeight="0",A.style.minWidth="0"),n){let W=T.attachShadow({mode:"open"});W.appendChild(A),uv(W,o)}else T.appendChild(A),uv(T,o);return t.id&&A.setAttribute("data-persona-instance",t.id),A},u=()=>{s.syncWidgetState(i.getState())},p=()=>{l.forEach(T=>T()),l=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},g=()=>{let T=d(s.host,r);i=Yu(T,r,{debugTools:e.debugTools}),p()},y=()=>{l.forEach(T=>T()),l=[],i.destroy()};g(),e.onChatReady?.();let m=T=>{y(),s.destroy(),s=jc(t,T),r=T,g()},b={update(T){let L=Bc(r??{},T),D=wt(r),k=wt(L),A=pr(r),W=pr(L);if(D!==k||A!==W){m(L);return}r=L,s.updateConfig(r),i.update(T),u()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},x=new Proxy(b,{get(T,L,D){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,D);let k=i[L];return typeof k=="function"?k.bind(i):k}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=x),x};function c0(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 d0(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:c0(o,n)?2:3}function fv(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function eg(e,t){let n=t.trim();if(!n)return[...e].sort(fv);let o=[];for(let r of e){let s=d0(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:fv(r.item,s.item)),o.map(r=>r.item)}function p0(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 u0(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>eg(e.items,t),resolve:e.resolve}}function g0(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=>eg(t,p0(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}var vv=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),f0=new Set(["button","a","input","select","textarea","details","summary"]),m0=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),tg=/\b(product|card|item|listing|result)\b/i,og=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,h0=3e3,y0=100;function Cv(e){let t=typeof e.className=="string"?e.className:"";if(tg.test(t)||e.id&&tg.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&tg.test(o.value))return!0}return!1}function wv(e){return og.test((e.textContent??"").trim())}function xv(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 b0(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function mv(e){let t=e.match(og);return t?t[0]:null}function hv(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 v0(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 C0="commerce-card",w0="result-card";function yv(e){return!Cv(e)||!wv(e)||!xv(e)&&!b0(e)?0:5200}function bv(e){return!Cv(e)||wv(e)||!xv(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Sv=[{id:C0,scoreElement(e){return yv(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||og.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(yv(e)===0)return null;let{title:n,href:o}=hv(e),r=mv((e.textContent??"").trim())??mv(t.text)??"",s=v0(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:w0,scoreElement(e){return bv(e)},formatSummary(e,t){if(bv(e)===0)return null;let{title:n,href:o}=hv(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
144
|
+
`)}}];function x0(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function S0(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,i=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),u=e.rules??Sv;return l==="simple"&&e.rules&&e.rules.length>0?(x0(),u=[]):l==="simple"&&(u=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:u}}function ng(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var A0=["data-testid","data-product","data-action","data-id","data-name","data-type"];function T0(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"||f0.has(t)||n&&m0.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Av(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 E0(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 i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let d=e.getAttribute("role");d&&(t.role=d);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Tv(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${ng(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of A0){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${ng(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}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(i=>ng(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let d=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function M0(e){return e==="static"?y0:h0}function Ev(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Tv(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:T0(e),attributes:E0(e)}}function k0(e,t,n,o){let r=M0(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function P0(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 L0(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let u=l,p=u.tagName.toLowerCase();if(vv.has(p)){l=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!Av(u)){l=i.nextNode();continue}let g=Ev(u,e.maxTextLength),y=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!y&&!m){l=i.nextNode();continue}if(o.has(g.selector)){l=i.nextNode();continue}o.add(g.selector);let{score:b,formattingRule:x}=k0(u,g,e.rules,n);r.push({el:u,domIndex:s,enriched:g,score:b,formattingRule:x}),s+=1}l=i.nextNode()}r.sort((u,p)=>{let g=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return g!==y?g-y:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let d=[];for(let u of r){if(d.length>=e.maxElements)break;P0(d,u)||d.push(u)}return d.sort((u,p)=>{let g=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return g!==y?g-y:g===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),d.map(u=>{let p;if(u.formattingRule?.formatSummary){let y=u.formattingRule.formatSummary(u.el,u.enriched,n);y&&(p=y)}let g={...u.enriched};return p&&(g.formattedSummary=p),g})}function H0(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,u=d.tagName.toLowerCase();if(vv.has(u)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Av(d)){s=r.nextNode();continue}let p=Ev(d,e.maxTextLength),g=p.text.length>0,y=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!g&&!y){s=r.nextNode();continue}o.has(p.selector)||(o.add(p.selector),n.push(p))}s=r.nextNode()}let i=[],l=[];for(let d of n)d.interactivity!=="static"?i.push(d):l.push(d);return[...i,...l].slice(0,e.maxElements)}function I0(e={}){let t=S0(e),n=t.root??document.body;return n?t.mode==="simple"?H0(t,n):L0(t,n):[]}var zc=100;function R0(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
|
|
145
|
+
${s.map(i=>`- ${i.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(
|
|
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(i=>`- ${i.selector}: "${i.text.substring(0,zc)}" (clickable)`);o.push(`Interactive elements:
|
|
149
149
|
${s.join(`
|
|
150
|
-
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(
|
|
150
|
+
`)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,zc)}" (navigable)`);o.push(`Navigation links:
|
|
151
151
|
${s.join(`
|
|
152
|
-
`)}`)}if(r.input.length>0){let s=r.input.map(
|
|
152
|
+
`)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,zc)}" (input)`);o.push(`Form inputs:
|
|
153
153
|
${s.join(`
|
|
154
|
-
`)}`)}if(r.static.length>0){let s=r.static.map(
|
|
154
|
+
`)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,zc)}"`);o.push(`Content:
|
|
155
155
|
${s.join(`
|
|
156
156
|
`)}`)}return o.join(`
|
|
157
157
|
|
|
158
|
-
`)}function
|
|
158
|
+
`)}function W0(){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 B0(){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 O0(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:go(e.colors.primary,.95),100:go(e.colors.primary,.9),200:go(e.colors.primary,.8),300:go(e.colors.primary,.7),400:go(e.colors.primary,.6),500:e.colors.primary,600:go(e.colors.primary,.8),700:go(e.colors.primary,.7),800:go(e.colors.primary,.6),900:go(e.colors.primary,.5),950:go(e.colors.primary,.45)}}),{...t,palette:n}}}}function D0(){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 _0(){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 go(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)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function N0(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var F0={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"}}},Mv={components:{panel:{borderRadius:"0",shadow:"none"}}},kv={id:"shop",label:"Shopping Assistant",config:{theme:F0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:jn},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"]}},Pv={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Mv}},Lv={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Mv}},Hv={shop:kv,minimal:Pv,fullscreen:Lv};function $0(e){return Hv[e]}var j0=gv;function rg(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@${Ro}/dist`}function _o(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function z0(e){if(e)return{getHeaders:_o(e.getHeaders),onFeedback:_o(e.onFeedback),onCopy:_o(e.onCopy),requestMiddleware:_o(e.requestMiddleware),actionHandlers:_o(e.actionHandlers),actionParsers:_o(e.actionParsers),postprocessMessage:_o(e.postprocessMessage),contextProviders:_o(e.contextProviders),streamParser:_o(e.streamParser)}}var Iv=`({ 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
|
+
}`,Rv=`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
|
+
}`,Wv=`(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
|
+
}`,Bv=`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,27 +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
|
+
}`,U0=`(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
|
+
}`,q0=`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
|
-
`);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,
|
|
232
|
-
`)}function
|
|
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
|
|
235
|
-
`)}function
|
|
236
|
-
`).map((
|
|
237
|
-
`)};`,""," // Constants",` var CDN_BASE = '${
|
|
238
|
-
`)}var
|
|
230
|
+
}`;function V0(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 Uc(e){return e.parserType??V0(e.streamParser)??"plain"}function qc(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 Vc(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,l])=>i!=="onFeedback"&&i!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,l])=>{i==="onFeedback"||i==="onCopy"||(typeof l=="string"?o.push(`${t} ${i}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${i}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function Kc(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,i])=>{typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Gc(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,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function Yc(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,i])=>{s!=="render"&&(typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?n.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${l}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?n.push(`${t} ${d}: "${u}",`):typeof u=="boolean"&&n.push(`${t} ${d}: ${u},`))}),n.push(`${t} },`)):typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function sg(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 Ov(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}: {`),Ov(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function fr(e,t,n,o){n&&(e.push(`${o}${t}: {`),Ov(e,n,`${o} `),e.push(`${o}},`))}function Ba(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function K0(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:z0(n.hooks)}:void 0;return t==="esm"?G0(o,r):t==="script-installer"?X0(o,r):t==="script-advanced"?Z0(o,r):t==="react-component"?Y0(o,r):t==="react-advanced"?J0(o,r):Q0(o,r)}function G0(e,t){let n=t?.hooks,o=Uc(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ba(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&&fr(s,"theme",e.theme," "),e.launcher&&fr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Gc(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),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(...qc(e," ")),s.push(...Vc(e," ",n)),s.push(...Kc(e," ")),s.push(...Yc(e," ")),s.push(...sg(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 Y0(e,t){let n=t?.hooks,o=Uc(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: '${Ba(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&&fr(s,"theme",e.theme," "),e.launcher&&fr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Gc(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),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(...qc(e," ")),s.push(...Vc(e," ",n)),s.push(...Kc(e," ")),s.push(...Yc(e," ")),s.push(...sg(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 J0(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: '${Ba(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&&fr(o,"theme",e.theme," "),e.launcher&&fr(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(...Gc(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(...qc(e," ")),o.push(...Vc(e," ",n)),o.push(...Kc(e," ")),o.push(...Yc(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(${U0}),`)),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(` ${Iv}`),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(` ${Iv}`),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(` ${Wv}`),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(` ${Wv}`),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 Dv(e){let t=Uc(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,i])=>{typeof i=="string"&&(r[s]=i)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(r[s]=i)}),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(([i,l])=>{i!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,l])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(i==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(d[u]=p)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function X0(e,t){let n=Dv(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="${rg(t)}/install.global.js" data-config='${s}'></script>`}function Q0(e,t){let n=t?.hooks,o=Uc(e),r=o!=="plain",s=rg(t),i=["<!-- 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: '${Ba(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&i.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&i.push(` clientToken: "${e.clientToken}",`),e.agentId&&i.push(` agentId: "${e.agentId}",`),e.target&&i.push(` target: "${e.target}",`),e.flowId&&i.push(` flowId: "${e.flowId}",`),r&&i.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&fr(i,"theme",e.theme," "),e.launcher&&fr(i,"launcher",e.launcher," "),e.copy&&(i.push(" copy: {"),Object.entries(e.copy).forEach(([l,d])=>{i.push(` ${l}: "${d}",`)}),i.push(" },")),e.sendButton&&(i.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.voiceRecognition&&(i.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"?i.push(` ${l}: ${d},`):typeof d=="number"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.statusIndicator&&(i.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.features&&(i.push(" features: {"),Object.entries(e.features).forEach(([l,d])=>{i.push(` ${l}: ${d},`)}),i.push(" },")),i.push(...Gc(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(i.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{i.push(` "${l}",`)}),i.push(" ],")),e.suggestionChipsConfig&&(i.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&i.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&i.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&i.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&i.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),i.push(" },")),i.push(...qc(e," ")),i.push(...Vc(e," ",n)),i.push(...Kc(e," ")),i.push(...Yc(e," ")),i.push(...sg(n," ")),e.debug&&i.push(` debug: ${e.debug},`),n?.postprocessMessage?i.push(` postprocessMessage: ${n.postprocessMessage}`):i.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),i.push(" }"),i.push(" });"),i.push("</script>"),i.join(`
|
|
235
|
+
`)}function Z0(e,t){let n=t?.hooks,o=Dv(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
|
|
236
|
+
`).map((i,l)=>l===0?i:" "+i).join(`
|
|
237
|
+
`)};`,""," // Constants",` var CDN_BASE = '${rg(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(${q0});`),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(` ${Rv}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Rv}`),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(` ${Bv}`),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(` ${Bv}`),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: '${Ba(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 _v={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Nv=.1,Fv=.15,$v=1.5,ig=24,jv=40,eP=`
|
|
239
239
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
240
240
|
.persona-dc-root {
|
|
241
241
|
display: flex;
|
|
@@ -386,7 +386,7 @@ ${s.join(`
|
|
|
386
386
|
.persona-dc-stage {
|
|
387
387
|
height: 550px;
|
|
388
388
|
min-height: 400px;
|
|
389
|
-
padding: ${
|
|
389
|
+
padding: ${ig}px;
|
|
390
390
|
overflow: auto;
|
|
391
391
|
background: #f0f1f3;
|
|
392
392
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -476,5 +476,5 @@ ${s.join(`
|
|
|
476
476
|
min-height: 300px;
|
|
477
477
|
}
|
|
478
478
|
}
|
|
479
|
-
`;function
|
|
479
|
+
`;function tP(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=eP,document.head.appendChild(e)}function nP(e,t){let n=e.clientWidth-ig*2-jv,o=e.clientHeight-ig*2-jv;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function oP(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 rP(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:i=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:u}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");tP();let p=Math.max(0,Math.min(o,n.length-1)),g=r,y=s,m=null,b=1,x=!1,T=v("div","persona-dc-root"),L=v("div","persona-dc-toolbar"),D=v("div","persona-dc-toolbar-lead"),k=v("div","persona-dc-toolbar-trail"),A=st({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Le(-1)}),W=v("div");W.style.position="relative";let I=v("button","persona-dc-title-btn");I.type="button",I.setAttribute("aria-expanded","false"),I.setAttribute("aria-haspopup","listbox");let R=v("span","persona-dc-title-text"),z=v("span","persona-dc-title-chevron"),q=ce("chevron-down",12,"currentColor",2);q&&z.appendChild(q),I.append(R,z);let Q=v("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let $=!1;function J(){Q.innerHTML="";for(let be=0;be<n.length;be++){let _e=n[be],gt=v("button","persona-dc-dropdown-item");gt.type="button",gt.setAttribute("role","option"),gt.setAttribute("aria-current",be===p?"true":"false");let Se=v("span");if(Se.textContent=_e.title,gt.appendChild(Se),_e.description){let Ne=v("span","persona-dc-dropdown-desc");Ne.textContent=_e.description,gt.appendChild(Ne)}gt.addEventListener("click",()=>{we(),Je(be)}),Q.appendChild(gt)}}function pe(){$=!$,Q.style.display=$?"":"none",I.setAttribute("aria-expanded",$?"true":"false"),$&&J()}function we(){$&&($=!1,Q.style.display="none",I.setAttribute("aria-expanded","false"))}I.addEventListener("click",be=>{be.stopPropagation(),pe()});let ve=()=>we();document.addEventListener("click",ve),W.append(I,Q);let he=st({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Le(1)}),ne=v("span","persona-dc-counter");D.append(A,W,he,ne);let ae=null;l&&(ae=lr({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:be=>{g=be,Ce.dataset.device=g,m=null,Be()}}),k.appendChild(ae.element));let ie=null;if(i){let be=v("div","persona-dc-zoom-controls"),_e=st({icon:"minus",label:"Zoom out",size:14,onClick:()=>{m=Math.max(Fv,(m??b)-Nv),Be()}});ie=v("span","persona-dc-zoom-level"),ie.title="Reset to 100%",ie.style.cursor="pointer",ie.addEventListener("click",()=>{m=1,Be()});let gt=st({icon:"plus",label:"Zoom in",size:14,onClick:()=>{m=Math.min($v,(m??b)+Nv),Be()}}),Se=st({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Be()}});be.append(_e,ie,gt,Se),k.appendChild(be)}if(d){let be=v("div","persona-dc-separator");k.appendChild(be);let _e=lr({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:gt=>{y=gt,Ce.dataset.colorScheme=y,xe()}});k.appendChild(_e.element)}let M=v("div","persona-dc-separator");k.appendChild(M);let Z=st({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(Z),L.append(D,k);let de=v("div","persona-dc-stage"),Ce=v("div","persona-dc-iframe-wrapper");Ce.dataset.device=g,Ce.dataset.colorScheme=y;let fe=v("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[p].title,Ce.appendChild(fe),de.appendChild(Ce),T.append(L,de),e.appendChild(T);function xe(){try{let be=fe.contentDocument?.body;if(!be)return;y==="dark"?be.classList.add("theme-dark"):be.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>xe());function Pe(){let be=n[p];R.textContent=be.title,ne.textContent=`${p+1} / ${n.length}`,fe.title=be.title}function Le(be){let _e=((p+be)%n.length+n.length)%n.length;Je(_e)}function Je(be){be<0||be>=n.length||(p=be,fe.src=n[p].url,Pe(),u?.(p,n[p]))}function Be(){if(x)return;let be=_v[g]??_v.desktop;b=nP(de,be);let _e=Math.max(Fv,Math.min($v,m??b));oP(Ce,fe,be,_e,g),ie&&(ie.textContent=`${Math.round(_e*100)}%`)}let Re=new ResizeObserver(()=>Be());Re.observe(de),Pe(),fe.src=n[p].url,requestAnimationFrame(()=>Be());function et(){x||(x=!0,Re.disconnect(),document.removeEventListener("click",ve),T.remove())}return{element:T,goTo:Je,next:()=>Le(1),prev:()=>Le(-1),getIndex:()=>p,setDevice(be){g=be,Ce.dataset.device=be,ae?.setSelected(be),m=null,Be()},setColorScheme(be){y=be,Ce.dataset.colorScheme=be},setZoom(be){m=be,Be()},destroy:et}}export{dh as ASK_USER_QUESTION_CLIENT_TOOL,ch as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ol as ASK_USER_QUESTION_TOOL_NAME,Bs as AgentWidgetClient,da as AgentWidgetSession,_s as AttachmentManager,Vr as BrowserSpeechEngine,ay as DEFAULT_COMPONENTS,Up as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,jn as DEFAULT_FLOATING_LAUNCHER_WIDTH,sy as DEFAULT_PALETTE,iy as DEFAULT_SEMANTIC,Qe as DEFAULT_WIDGET_CONFIG,Xn as HistoryProviderError,Hv as PRESETS,Lv as PRESET_FULLSCREEN,Pv as PRESET_MINIMAL,kv as PRESET_SHOP,Ds as ReadAloudController,Sp as SUGGEST_REPLIES_CLIENT_TOOL,ah as SUGGEST_REPLIES_PARAMETERS_SCHEMA,io as SUGGEST_REPLIES_TOOL_NAME,zT as THEME_ZONES,Ro as VERSION,so as WEBMCP_TOOL_PREFIX,Ki as WebMcpBridge,W0 as accessibilityPlugin,B0 as animationsPlugin,zb as applyFeaturePreferences,$s as applyThemeVariables,Ys as attachHeaderToContainer,O0 as brandPlugin,Js as buildComposer,Yy as buildDefaultHeader,ur as buildHeader,Ma as buildHeaderWithLayout,Jy as buildMinimalHeader,Zi as builtInClientToolsForDispatch,kn as canonicalArtifactDisplayMode,I0 as collectEnrichedPageContext,co as componentRegistry,Dc as createActionManager,Yu as createAgentExperience,Bx as createAskUserQuestionBubble,Op as createBestAvailableVoiceProvider,CM as createBubbleWithLayout,Vu as createCSATFeedback,eu as createComboButton,$k as createComponentMiddleware,zu as createComponentStreamParser,Hm as createDefaultSanitizer,rP as createDemoCarousel,Vw as createDirectivePostprocessor,Us as createDropdownMenu,Fx as createFlexibleJsonStreamParser,st as createIconButton,Ip as createImagePart,Pp as createJsonStreamParser,ar as createLabelButton,_u as createLocalStorageAdapter,Wl as createMarkdownProcessor,Ls as createMarkdownProcessorFromConfig,rb as createMessageActions,Ku as createNPSFeedback,Mp as createPlainTextParser,N0 as createPlugin,kp as createRegexJsonParser,Lu as createRovingTablist,g0 as createSlashCommandsSource,Zp as createSplitButton,Pa as createStandardBubble,u0 as createStaticMentionSource,Wo as createTextPart,Zl as createTheme,ma as createThemeObserver,lr as createToggleGroup,Xs as createTypingIndicator,qr as createVoiceProvider,jc as createWidgetHostLayout,Lp as createXmlParser,j0 as default,oi as defaultActionHandlers,Oc as defaultJsonActionParser,eg as defaultMentionFilter,Sv as defaultParseRules,ec as detectColorScheme,Kw as directivePostprocessor,Qi as ensureAskUserQuestionSheet,Ho as escapeHtml,qu as extractComponentDirectiveFromMessage,Ux as fileToImagePart,R0 as formatEnrichedContext,zr as generateAssistantMessageId,K0 as generateCodeSnippet,oS as generateMessageId,Tv as generateStableSelector,ia as generateUserMessageId,Kr as getActiveTheme,Gp as getColorScheme,Hp as getDisplayText,Xy as getHeaderLayout,zx as getImageParts,$0 as getPreset,Nc as hasComponentDirective,oa as hasImages,fu as headerLayouts,_0 as highContrastPlugin,gv as initAgentWidget,Qo as isAskUserQuestionMessage,Fk as isComponentDirectiveType,wt as isDockedMountMode,rS as isHistoryProviderError,Rs as isSuggestRepliesMessage,Vl as isVoiceSupported,Nr as isWebMcpToolName,Qr as isWelcomeVisible,Tp as latestAgentSuggestions,NE as listRegisteredStreamAnimations,Tm as loadMarkdownParsers,km as markdownPostprocessor,fa as mergeWithDefaults,jx as normalizeContent,Fr as normalizeMediaType,qi as onMarkdownParsersReady,Zo as parseAskUserQuestionPayload,lh as parseSuggestRepliesPayload,Fb as parseWidgetPreferenceSlice,la as pickBestVoice,Wc as pluginRegistry,D0 as reducedMotionPlugin,DE as registerStreamAnimationPlugin,jr as removeAskUserQuestionSheet,Uu as renderComponentDirective,ob as renderLoadingIndicatorWithFallback,ce as renderLucideIcon,Um as resolveArtifactDisplay,Io as resolveArtifactDisplayMode,Rc as resolveConfigPreferences,Pn as resolveDockConfig,Vi as resolveSanitizer,Vp as resolveTokens,gr as resolveWelcomeConfig,yp as stripWebMcpPrefix,Kp as themeToCssVariables,_E as unregisterStreamAnimationPlugin,qx as validateImageFile,ly as validateTheme};
|
|
480
480
|
//# sourceMappingURL=index.js.map
|