@runtypelabs/persona 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +52 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -1
- package/dist/index.d.ts +16 -1
- package/dist/index.global.js +41 -39
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +51 -49
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +16 -1
- package/dist/smart-dom-reader.d.ts +16 -1
- package/dist/theme-editor-preview.cjs +45 -43
- package/dist/theme-editor-preview.d.cts +16 -1
- package/dist/theme-editor-preview.d.ts +16 -1
- package/dist/theme-editor-preview.js +45 -43
- package/dist/theme-editor.cjs +1 -1
- package/dist/theme-editor.d.cts +16 -1
- package/dist/theme-editor.d.ts +16 -1
- package/dist/theme-editor.js +1 -1
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.js +1 -1
- package/dist/widget.css +238 -0
- package/package.json +1 -1
- package/src/components/approval-actions.test.ts +309 -0
- package/src/components/approval-actions.ts +461 -0
- package/src/components/message-bubble.ts +7 -0
- package/src/styles/widget.css +238 -0
- package/src/theme-reference.ts +2 -2
- package/src/types.ts +16 -1
- package/src/ui.ts +25 -4
- package/src/utils/streaming-table.test.ts +100 -0
- package/src/utils/streaming-table.ts +103 -0
- package/src/utils/tokens.ts +15 -12
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
"use strict";var yg=Object.create;var ma=Object.defineProperty;var bg=Object.getOwnPropertyDescriptor;var vg=Object.getOwnPropertyNames;var xg=Object.getPrototypeOf,wg=Object.prototype.hasOwnProperty;var Es=(n,e)=>()=>(n&&(e=n(n=0)),e);var gi=(n,e)=>{for(var t in e)ma(n,t,{get:e[t],enumerable:!0})},Bp=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of vg(e))!wg.call(n,o)&&o!==t&&ma(n,o,{get:()=>e[o],enumerable:!(r=bg(e,o))||r.enumerable});return n};var Dp=(n,e,t)=>(t=n!=null?yg(xg(n)):{},Bp(e||!n||!n.__esModule?ma(t,"default",{value:n,enumerable:!0}):t,n)),Cg=n=>Bp(ma({},"__esModule",{value:!0}),n);var Op={};gi(Op,{DOMPurify:()=>Fp.default,Marked:()=>Np.Marked});var Np,Fp,_p=Es(()=>{"use strict";Np=require("marked"),Fp=Dp(require("dompurify"),1)});var os,Ii=Es(()=>{"use strict";os=class{constructor(e=24e3,t={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}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 e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Tf(n){return n.replace(/\/+$/,"")}async function Mf(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var La,Su=Es(()=>{"use strict";Ii();La=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new os(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${Tf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,m=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!m.ok||!m.body)throw new Error(await Mf(m));let f=m.body.getReader();for(;;){let{done:g,value:u}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;u&&u.byteLength>0&&d.enqueue(u)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Pa,Tu=Es(()=>{"use strict";Pa=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Mu={};gi(Mu,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var Eu=Es(()=>{"use strict";Su();Tu()});var Ry={};gi(Ry,{createThemePreview:()=>Zm});module.exports=Cg(Ry);var $p=null,ks=null,Xo=null;var Up=()=>ks?Promise.resolve(ks):Xo||($p?(Xo=$p().then(n=>(ks=n,n)),Xo):(Xo=Promise.resolve().then(()=>(_p(),Op)).then(n=>(ks=n,n)),Xo)),Eo=()=>ks;var Ag=n=>{if(n)return n},fi=n=>{let e=null;return t=>{var o,s;let r=Eo();if(!r)return so(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Ag(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},ga=n=>n?fi({markedOptions:n.options,renderer:n.renderer}):fi(),Oy=fi();var so=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Sg={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"]},Tg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Mg=()=>{let n=null;return e=>{let t=Eo();if(!t)return so(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Tg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,Sg)}},fa=n=>n===!1?null:typeof n=="function"?n:Mg();var ko="webmcp:",hi=new Map,qp=n=>{var e;hi.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&hi.set(t.name,r)}},yi=n=>hi.get(Kp(n)),ha={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},zp=null;function Vp(n){if(n.length===0)return"0:empty";let e=n.map(t=>{var r,o;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${n.length}:${Eg(e.join(""))}`}function jp(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Eg(n){let e=jp(n,0).toString(36),t=jp(n,2654435761).toString(36);return`${e}.${t}`}var ya=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}qp(t);let r=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Lg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return mr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return mr(v?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=Kp(e),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return mr(`Failed to read WebMCP registry: ${x}`)}qp(a);let i=a.find(v=>v.name===s);if(!i)return mr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return mr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let d=yi(s),c={toolName:s,args:t,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return mr("User declined the tool call.");if(r!=null&&r.aborted)return mr("Aborted by cancel()");let m=new AbortController,f=!1,g=setTimeout(()=>{f=!0,m.abort()},this.timeoutMs),u=()=>m.abort();r&&(r.aborted?m.abort():r.addEventListener("abort",u,{once:!0}));try{let v=await o.executeTool(i,Rg(t),{signal:m.signal});return Pg(v)}catch(v){if(f)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return mr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",u)}}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}(zp?await zp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ha.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):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Ig;try{return await t(e)}catch(o){return ha.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>kg(e,r))}},Kp=n=>n.startsWith(ko)?n.slice(ko.length):n,Jo=n=>n.startsWith(ko),kg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Lg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Pg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Hg(e)}]}},mr=n=>({isError:!0,content:[{type:"text",text:n}]}),Ig=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Wg(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
|
|
1
|
+
"use strict";var Pg=Object.create;var ha=Object.defineProperty;var Ig=Object.getOwnPropertyDescriptor;var Wg=Object.getOwnPropertyNames;var Rg=Object.getPrototypeOf,Hg=Object.prototype.hasOwnProperty;var Is=(t,e)=>()=>(t&&(e=t(t=0)),e);var yi=(t,e)=>{for(var n in e)ha(t,n,{get:e[n],enumerable:!0})},Fp=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wg(e))!Hg.call(t,o)&&o!==n&&ha(t,o,{get:()=>e[o],enumerable:!(r=Ig(e,o))||r.enumerable});return t};var Op=(t,e,n)=>(n=t!=null?Pg(Rg(t)):{},Fp(e||!t||!t.__esModule?ha(n,"default",{value:t,enumerable:!0}):n,t)),Bg=t=>Fp(ha({},"__esModule",{value:!0}),t);var Up={};yi(Up,{DOMPurify:()=>$p.default,Marked:()=>_p.Marked});var _p,$p,zp=Is(()=>{"use strict";_p=require("marked"),$p=Op(require("dompurify"),1)});var cs,Ri=Is(()=>{"use strict";cs=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.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(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}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 e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),r=new Float32Array(n),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function $f(t){return t.replace(/\/+$/,"")}async function Uf(t){var e,n;try{let r=await t.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${t.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Wa,Iu=Is(()=>{"use strict";Ri();Wa=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new cs(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,n){let r=++this.generation;this.run(r,e,n)}async run(e,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${$f(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,u=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!u.ok||!u.body)throw new Error(await Uf(u));let f=u.body.getReader();for(;;){let{done:g,value:m}=await f.read();if(e!==this.generation){await f.cancel().catch(()=>{});return}if(g)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Ra,Wu=Is(()=>{"use strict";Ra=class{constructor(e,n,r={}){this.primary=e;this.fallback=n;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,n,r,o;(n=(e=this.primary).destroy)==null||n.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Ru={};yi(Ru,{FallbackSpeechEngine:()=>Ra,RuntypeSpeechEngine:()=>Wa});var Hu=Is(()=>{"use strict";Iu();Wu()});var tb={};yi(tb,{createThemePreview:()=>dg});module.exports=Bg(tb);var qp=null,Ws=null,ns=null;var jp=()=>Ws?Promise.resolve(Ws):ns||(qp?(ns=qp().then(t=>(Ws=t,t)),ns):(ns=Promise.resolve().then(()=>(zp(),Up)).then(t=>(Ws=t,t)),ns)),Io=()=>Ws;var Dg=t=>{if(t)return t},bi=t=>{let e=null;return n=>{var o,s;let r=Io();if(!r)return co(n);if(!e){let{Marked:a}=r,i=t==null?void 0:t.markedOptions;e=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Dg(t==null?void 0:t.renderer);d&&e.use({renderer:d})}return e.parse(n)}},ya=t=>t?bi({markedOptions:t.options,renderer:t.renderer}):bi(),ib=bi();var co=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Ng={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"]},Fg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Og=()=>{let t=null;return e=>{let n=Io();if(!n)return co(e);if(!t){let{DOMPurify:r}=n;t=r(typeof window!="undefined"?window:void 0),t.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Fg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Ng)}},ba=t=>t===!1?null:typeof t=="function"?t:Og();var Vp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Kp=t=>t.includes("|"),Gp=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},_g=t=>`| ${t.join(" | ")} |`,$g=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Ug=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Qp=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
+
`),n=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!Kp(o)||Vp.test(o)||!Vp.test(s))continue;let a=Gp(o).length;if(a<1)continue;let i=$g(a);e[r+1]!==i&&(e[r+1]=i,n=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!Kp(c))break;let u=_g(Ug(Gp(c),a));e[d]!==u&&(e[d]=u,n=!0)}r=d-1}return n?e.join(`
|
|
3
|
+
`):t};var zr="webmcp:",vi=new Map,Xp=t=>{var e;vi.clear();for(let n of t){let r=(e=n.title)==null?void 0:e.trim();r&&vi.set(n.name,r)}},Rs=t=>vi.get(eu(t)),va={warn(t,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Jp=null;function Zp(t){if(t.length===0)return"0:empty";let e=t.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${t.length}:${zg(e.join(""))}`}function Yp(t,e){let n=3735928559^e,r=1103547991^e;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function zg(t){let e=Yp(t,0).toString(36),n=Yp(t,2654435761).toString(36);return`${e}.${n}`}var xa=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=e.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(o){return va.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Xp(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=jg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return fr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let x=typeof document!="undefined"&&!!document.modelContext;return fr(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=eu(e),a;try{a=await o.getTools()}catch(x){let v=x instanceof Error?x.message:String(x);return fr(`Failed to read WebMCP registry: ${v}`)}Xp(a);let i=a.find(x=>x.name===s);if(!i)return fr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return fr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return fr("Aborted by cancel()");let d=Rs(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return fr("User declined the tool call.");if(r!=null&&r.aborted)return fr("Aborted by cancel()");let u=new AbortController,f=!1,g=setTimeout(()=>{f=!0,u.abort()},this.timeoutMs),m=()=>u.abort();r&&(r.aborted?u.abort():r.addEventListener("abort",m,{once:!0}));try{let x=await o.executeTool(i,Qg(n),{signal:u.signal});return Vg(x)}catch(x){if(f)return fr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return fr("Aborted by cancel()");let v=x instanceof Error?x.message:String(x);return fr(v)}finally{clearTimeout(g),r&&r.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}(Jp?await Jp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){va.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,va.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let n=(r=this.confirmHandler)!=null?r:Kg;try{return await n(e)}catch(o){return va.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>qg(e,r))}},eu=t=>t.startsWith(zr)?t.slice(zr.length):t,rs=t=>t.startsWith(zr),qg=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},jg=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Vg=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Xg(e)}]}},fr=t=>({isError:!0,content:[{type:"text",text:t}]}),Kg=async t=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Gg(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
|
|
2
4
|
|
|
3
5
|
Arguments:
|
|
4
|
-
${e}`:"")+(
|
|
6
|
+
${e}`:"")+(t.description?`
|
|
5
7
|
|
|
6
|
-
${n.description}`:"");return window.confirm(t)},Wg=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Rg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Hg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var ao=require("partial-json");var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Lr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ls=(...n)=>n.filter(Boolean).join(" ");var bi="ask_user_question",Ps=8,Yo="data-persona-ask-sheet-for",Bg="Other",Dg="Other\u2026",Qp="Type your own answer here",Xp="Send",Ng="Next",Fg="Back",Og="Submit all",_g="Skip",$g=3,vi="data-ask-current-index",xi="data-ask-question-count",Jp="data-ask-answers",wi="data-ask-grouped",Yp="data-ask-layout",Ug=n=>n.layout==="pills"?"pills":"rows",qg=n=>n.getAttribute(Yp)==="pills"?"pills":"rows",Gp=!1,Zp=n=>n.replace(/["\\]/g,"\\$&"),Lo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===bi,Ci=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},Zo=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=(0,ao.parse)(o,ao.STR|ao.OBJ|ao.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Is=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Ps&&!Gp&&(Gp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ps}.`)),e.slice(0,Ps)},zg=n=>{var e;return(e=Is(n)[0])!=null?e:null},jg=(n,e)=>{var t;return(t=Is(n)[e])!=null?t:null},Vg=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},eu=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},Kg=(n,e,t,r)=>{let s=b("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=eu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Gg=n=>{let t=b("span",n==="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 t.setAttribute("aria-hidden","true"),t},Qg=(n,e,t,r)=>{var m,f,g;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!t){for(let u=0;u<$g;u++)s.appendChild(Gg(r));return s}if(d.forEach((u,v)=>{s.appendChild(Kg(u,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let u=r==="rows"?Bg:Dg;if(r==="rows"){let v=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=b("span","persona-ask-row-content"),I=document.createElement("input");I.type="text",I.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",I.placeholder=(m=e.freeTextPlaceholder)!=null?m:Qp,I.setAttribute("data-ask-free-text-input","true"),I.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:u),x.appendChild(I),v.appendChild(x);let M=eu(r,a,d.length);M&&v.appendChild(M),s.appendChild(v)}else{let v=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=e.freeTextLabel)!=null?g:u,s.appendChild(v)}}return s},tu=(n,e)=>{var s,a;let r=b("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:Qp,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:Xp,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Xg=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:Xp,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Jg=(n,e,t)=>{var c,m,f,g;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Fg,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(m=t.skipLabel)!=null?m:_g,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(f=t.submitAllLabel)!=null?f:Og:(g=t.nextLabel)!=null?g:Ng,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Po=n=>{let e=n.getAttribute(Jp);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},nu=(n,e)=>{n.setAttribute(Jp,JSON.stringify(e))},sr=n=>{var t;let e=Number((t=n.getAttribute(vi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Yg=(n,e)=>{n.setAttribute(vi,String(Math.max(0,Math.floor(e))))},es=n=>{var t;let e=Number((t=n.getAttribute(xi))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},io=n=>n.getAttribute(wi)==="true",Zg=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},ef=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},ba=(n,e)=>{let{payload:t}=Zo(e),r=Is(t),o=Po(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},ru=n=>{let e=Po(n),t=sr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",m=o.has(c);d.setAttribute("aria-pressed",m?"true":"false"),d.classList.toggle("persona-ask-pill-selected",m)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},ou=n=>{if(!io(n))return;let e=Po(n),t=sr(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ai=(n,e,t)=>{let r=Ci(t),o=qg(n),{payload:s,complete:a}=Zo(e),i=io(n),d=sr(n),c=es(n),m=i?jg(s,d):zg(s),f=!!(m!=null&&m.multiSelect),g=n.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let u=n.querySelector('[data-ask-stepper="true"]');u&&u.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let E=typeof(m==null?void 0:m.question)=="string"?m.question:"";v.textContent=E,v.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let E=Qg(m,r,a,o);x.replaceWith(E)}if(o!=="rows"){let E=n.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(tu(r,o))}let I=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!I?n.appendChild(Xg(r)):(!f||i)&&I&&I.remove(),n.setAttribute("data-multi-select",f?"true":"false");let M=n.querySelector('[data-ask-nav-row="true"]');if(i){let E=Jg(d,c,r);M?M.replaceWith(E):n.appendChild(E)}else M&&M.remove();ru(n),ou(n)},tf=(n,e,t)=>{let r=Ci(e),o=Ug(r),s=n.toolCall.id,a=Is(t),i=Math.max(1,a.length),d=i>1,c=Zg(n,a),m=d?ef(n,i):0,f=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Yo,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(xi,String(i)),f.setAttribute(vi,String(m)),f.setAttribute(wi,d?"true":"false"),f.setAttribute(Yp,o),nu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Vg(f,r);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),u=b("div","persona-ask-sheet-question persona-flex-1");u.setAttribute("data-ask-question","true"),u.textContent="",g.appendChild(u);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),f.appendChild(g);let I=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return I.setAttribute("data-ask-pill-list","true"),I.setAttribute("role","group"),f.appendChild(I),o!=="rows"&&f.appendChild(tu(r,o)),Ai(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nf=(n,e,t)=>{let{payload:r}=Zo(e),o=Math.max(1,Is(r).length);o>es(n)&&(n.setAttribute(xi,String(o)),o>1&&!io(n)&&n.setAttribute(wi,"true")),Ai(n,e,t)};var va=(n,e,t)=>{if(!t||!Lo(n)||Ci(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${Yo}]`).forEach(c=>{c.getAttribute(Yo)!==o&&c.remove()});let a=t.querySelector(`[${Yo}="${Zp(o)}"]`);if(a){nf(a,n,e);return}let{payload:i}=Zo(n),d=tf(n,e,i);t.appendChild(d)},ts=(n,e)=>{if(!n)return;let t=e?`[${Yo}="${Zp(e)}"]`:`[${Yo}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Si=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),lo=(n,e)=>{let t=Po(n),r=sr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,nu(n,t),ru(n),ou(n)},xa=(n,e,t,r)=>{let o=es(n),s=Math.max(0,Math.min(o-1,r));Yg(n,s),Ai(n,e,t)};var $r="suggest_replies";var rf={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},su={name:$r,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:rf,origin:"sdk",annotations:{readOnlyHint:!0}},Ti=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Mi=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===$r},of=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},au=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Mi(r))continue;let o=of((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},iu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var sf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ps,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},af={name:bi,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:sf,origin:"sdk",annotations:{readOnlyHint:!0}},Ei=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(af),iu(n)&&e.push(su),e};var ns=require("partial-json"),lu=n=>n.replace(/\\n/g,`
|
|
7
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${t.description}`:"");return window.confirm(n)},Gg=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Qg=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Xg=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var po=require("partial-json");var y=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Wr=(t,e,n)=>{let r=t.createElement(e);return n&&(r.className=n),r};var Et=(t,e={},...n)=>{let r=document.createElement(t);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Hs=(...t)=>t.filter(Boolean).join(" ");var xi="ask_user_question",Bs=8,os="data-persona-ask-sheet-for",Jg="Other",Yg="Other\u2026",nu="Type your own answer here",ru="Send",Zg="Next",ef="Back",tf="Submit all",nf="Skip",rf=3,wi="data-ask-current-index",Ci="data-ask-question-count",ou="data-ask-answers",Ai="data-ask-grouped",su="data-ask-layout",of=t=>t.layout==="pills"?"pills":"rows",sf=t=>t.getAttribute(su)==="pills"?"pills":"rows",tu=!1,au=t=>t.replace(/["\\]/g,"\\$&"),Wo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===xi,Si=t=>{var e,n;return(n=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?n:{}},ss=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,po.parse)(o,po.STR|po.OBJ|po.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ds=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Bs&&!tu&&(tu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Bs}.`)),e.slice(0,Bs)},af=t=>{var e;return(e=Ds(t)[0])!=null?e:null},lf=(t,e)=>{var n;return(n=Ds(t)[e])!=null?n:null},cf=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},iu=(t,e,n)=>{if(t!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},df=(t,e,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let c=y("span","persona-ask-row-description");c.textContent=t.description,a.appendChild(c)}s.appendChild(a);let d=iu(n,r,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},pf=t=>{let n=y("span",t==="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},uf=(t,e,n,r)=>{var u,f,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!n){for(let m=0;m<rf;m++)s.appendChild(pf(r));return s}if(d.forEach((m,x)=>{s.appendChild(df(m,x,r,a))}),(t==null?void 0:t.allowFreeText)!==!1){let m=r==="rows"?Jg:Yg;if(r==="rows"){let x=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(d.length)),x.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),M=document.createElement("input");M.type="text",M.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",M.placeholder=(u=e.freeTextPlaceholder)!=null?u:nu,M.setAttribute("data-ask-free-text-input","true"),M.setAttribute("aria-label",(f=e.freeTextLabel)!=null?f:m),v.appendChild(M),x.appendChild(v);let R=iu(r,a,d.length);R&&x.appendChild(R),s.appendChild(x)}else{let x=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(g=e.freeTextLabel)!=null?g:m,s.appendChild(x)}}return s},lu=(t,e)=>{var s,a;let r=y("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=t.freeTextPlaceholder)!=null?s:nu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:ru,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},mf=t=>{var r;let e=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=t.submitLabel)!=null?r:ru,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},gf=(t,e,n)=>{var c,u,f,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:ef,o.setAttribute("data-ask-user-action","back"),o.disabled=t===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=n.skipLabel)!=null?u:nf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=t===e-1;return i.textContent=d?(f=n.submitAllLabel)!=null?f:tf:(g=n.nextLabel)!=null?g:Zg,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Ro=t=>{let e=t.getAttribute(ou);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},cu=(t,e)=>{t.setAttribute(ou,JSON.stringify(e))},ar=t=>{var n;let e=Number((n=t.getAttribute(wi))!=null?n:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},ff=(t,e)=>{t.setAttribute(wi,String(Math.max(0,Math.floor(e))))},as=t=>{var n;let e=Number((n=t.getAttribute(Ci))!=null?n:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},uo=t=>t.getAttribute(Ai)==="true",hf=(t,e)=>{var o;let n=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},yf=(t,e)=>{var r;let n=(r=t.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},wa=(t,e)=>{let{payload:n}=ss(e),r=Ds(n),o=Ro(t),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},du=t=>{let e=Ro(t),n=ar(t),r=e[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var f;let c=(f=d.getAttribute("data-option-label"))!=null?f:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=t.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pu=t=>{if(!uo(t))return;let e=Ro(t),n=ar(t),r=e[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ti=(t,e,n)=>{let r=Si(n),o=sf(t),{payload:s,complete:a}=ss(e),i=uo(t),d=ar(t),c=as(t),u=i?lf(s,d):af(s),f=!!(u!=null&&u.multiSelect),g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let m=t.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=t.querySelector('[data-ask-question="true"]');if(x){let T=typeof(u==null?void 0:u.question)=="string"?u.question:"";x.textContent=T,x.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let v=t.querySelector('[data-ask-pill-list="true"]');if(v){let T=uf(u,r,a,o);v.replaceWith(T)}if(o!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(lu(r,o))}let M=t.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!M?t.appendChild(mf(r)):(!f||i)&&M&&M.remove(),t.setAttribute("data-multi-select",f?"true":"false");let R=t.querySelector('[data-ask-nav-row="true"]');if(i){let T=gf(d,c,r);R?R.replaceWith(T):t.appendChild(T)}else R&&R.remove();du(t),pu(t)},bf=(t,e,n)=>{let r=Si(e),o=of(r),s=t.toolCall.id,a=Ds(n),i=Math.max(1,a.length),d=i>1,c=hf(t,a),u=d?yf(t,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(os,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",t.id),f.setAttribute(Ci,String(i)),f.setAttribute(wi,String(u)),f.setAttribute(Ai,d?"true":"false"),f.setAttribute(su,o),cu(f,c),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),cf(f,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=y("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",g.appendChild(m);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",g.appendChild(x),f.appendChild(g);let M=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),f.appendChild(M),o!=="rows"&&f.appendChild(lu(r,o)),Ti(f,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},vf=(t,e,n)=>{let{payload:r}=ss(e),o=Math.max(1,Ds(r).length);o>as(t)&&(t.setAttribute(Ci,String(o)),o>1&&!uo(t)&&t.setAttribute(Ai,"true")),Ti(t,e,n)};var Ca=(t,e,n)=>{if(!n||!Wo(t)||Si(e).enabled===!1)return;let o=t.toolCall.id;n.querySelectorAll(`[${os}]`).forEach(c=>{c.getAttribute(os)!==o&&c.remove()});let a=n.querySelector(`[${os}="${au(o)}"]`);if(a){vf(a,t,e);return}let{payload:i}=ss(t),d=bf(t,e,i);n.appendChild(d)},is=(t,e)=>{if(!t)return;let n=e?`[${os}="${au(e)}"]`:`[${os}]`;t.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Ei=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),mo=(t,e)=>{let n=Ro(t),r=ar(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[r]:n[r]=e,cu(t,n),du(t),pu(t)},Aa=(t,e,n,r)=>{let o=as(t),s=Math.max(0,Math.min(o-1,r));ff(t,s),Ti(t,e,n)};var qr="suggest_replies";var xf={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},uu={name:qr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:xf,origin:"sdk",annotations:{readOnlyHint:!0}},Mi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ki=t=>{var e;return t.variant==="tool"&&((e=t.toolCall)==null?void 0:e.name)===qr},wf=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e==null?void 0:e.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},mu=t=>{var e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.role==="user")return null;if(!ki(r))continue;let o=wf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},gu=t=>{var n;let e=(n=t==null?void 0:t.features)==null?void 0:n.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var Cf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Bs,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},Af={name:xi,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:Cf,origin:"sdk",annotations:{readOnlyHint:!0}},Li=t=>{var r;let e=[],n=(r=t==null?void 0:t.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&e.push(Af),gu(t)&&e.push(uu),e};var ls=require("partial-json"),fu=t=>t.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),go=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Sf=t=>{var a,i;let e=(a=t.completedAt)!=null?a:Date.now(),n=(i=t.startedAt)!=null?i:e,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},hu=t=>t.status==="complete"?Sf(t):t.status==="pending"?"Waiting":"",Tf=t=>{var o,s,a;let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((a=(s=t.startedAt)!=null?s:t.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var yu=t=>t.status==="complete"?Tf(t):"Using tool...",Sa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Fs=t=>{var n,r,o;let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return Sa(e)},Ta=t=>{var n,r,o;let e=t.durationMs!==void 0?t.durationMs:Math.max(0,((n=t.completedAt)!=null?n:Date.now())-((o=(r=t.startedAt)!=null?r:t.completedAt)!=null?o:Date.now()));return Sa(e)},Pi=(t,e,n)=>{var s;if(!e)return n;let r=((s=t.name)==null?void 0:s.trim())||"tool",o=Fs(t);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ea=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Ns(r,n.slice(s,a.index),[]),a[1]!==void 0?Ns(r,a[1],["bold"]):a[2]!==void 0?Ns(r,a[2],["italic"]):a[3]!==void 0&&Ns(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Ns(r,n.slice(s),[]),r},Ns=(t,e,n)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&t.push({text:r[o],styles:n}),o<r.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Ef=()=>{let t=null,e=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Hs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},pu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},uu=()=>{var e;let n=df();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},mu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,ns.parse)(t,ns.STR|ns.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?lu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=lu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var gu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var fu="4.0.0";var Bs=fu;var uf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function mf(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Li=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function gf(n){switch(n){case"json":return mu;case"regex-json":return uu;case"xml":return gu;default:return pu}}var hu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ff(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=hu(t);if(!hu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Hs(n);return Hs(e)!==null&&a===null?e:n}var Ds=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;this.apiUrl=(t=e.apiUrl)!=null?t:uf,this.headers={"Content-Type":"application/json","X-Persona-Version":Bs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:gf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new ya(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Bs},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Bs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isAgentMode()?this.dispatchAgent(e,t):this.isClientTokenMode()?this.dispatchClientToken(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let L=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:L}),L}let c=await this.buildPayload(e.messages),m=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Li).map(L=>{var R,A,W;return{id:L.id,role:L.role,content:(W=(A=(R=L.contentParts)!=null?R:L.llmContent)!=null?A:L.rawContent)!=null?W:L.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...m&&Object.keys(m).length>0&&{metadata:m},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,u=!!(g&&g.length>0),v=u?Vp(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,I=u&&x&&this.lastSentClientToolsFingerprint===v,M=!1,E=null,F;for(let L=0;;L++){let A={...f,...u&&(M||!I)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),F=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Bs},body:JSON.stringify(A),signal:r.signal}),F.status===409&&L===0&&u){let W=await F.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}E=W!=null?W:{error:"Chat request failed"}}break}if(!F.ok){let L=E!=null?E:await F.json().catch(()=>({error:"Chat request failed"}));if(F.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(F.status===429){let A=new Error(L.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let R=new Error(L.error||"Failed to send message");throw t({type:"error",error:R}),R}if(!F.body){let L=new Error("No response body received");throw t({type:"error",error:L}),L}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(F.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Sa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,m;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Sa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(m=r==null?void 0:r.streamResponse)!=null?m:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=e.slice().filter(Li).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Ei(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Li).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),m=new Date(d.createdAt).getTime();return c-m}).map(i=>{var d,c,m;return{role:i.role,content:(m=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?m:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Ei(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=m=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...m!==void 0&&{partId:m}};return r.current=f,o(f),f},c=m=>r.current?r.current:d(m);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let m=c(i.partId);i.partId!==void 0&&!m.partId&&(m.partId=i.partId),m.content+=i.text,o(m)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r){var rn,hr,hn,Ve;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,m=T=>{let ue=T.reasoning?{...T.reasoning,chunks:[...T.reasoning.chunks]}:void 0,Le=T.toolCall?{...T.toolCall,chunks:T.toolCall.chunks?[...T.toolCall.chunks]:void 0}:void 0,Me=T.tools?T.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...T,reasoning:ue,toolCall:Le,tools:Me}},f=T=>{if(T.role!=="assistant"||T.variant)return!0;let ue=Array.isArray(T.contentParts)&&T.contentParts.length>0,Le=typeof T.rawContent=="string"&&T.rawContent.trim()!=="";return typeof T.content=="string"&&T.content.trim()!==""||ue||Le||!!T.stopReason},g=T=>{f(T)&&t({type:"message",message:m(T)})},u=null,v=null,x={current:null},I={current:null},M=null,E="",F=new Map,L=new Map,R=new Map,A=new Map,W=new Map,N={lastId:null,byStep:new Map},D={lastId:null,byCall:new Map},k=T=>{if(T==null)return null;try{return String(T)}catch{return null}},j=T=>{var ue,Le,Me,He,Ze;return k((Ze=(He=(Me=(Le=(ue=T.stepId)!=null?ue:T.step_id)!=null?Le:T.step)!=null?Me:T.parentId)!=null?He:T.flowStepId)!=null?Ze:T.flow_step_id)},V=T=>{var ue,Le,Me,He,Ze,Ge,ut;return k((ut=(Ge=(Ze=(He=(Me=(Le=(ue=T.callId)!=null?ue:T.call_id)!=null?Le:T.requestId)!=null?Me:T.request_id)!=null?He:T.toolCallId)!=null?Ze:T.tool_call_id)!=null?Ge:T.stepId)!=null?ut:T.step_id)},ne=r,Re=!1,Ue=()=>{if(u)return u;let T,ue=M;return!Re&&ne?(T=ne,Re=!0):ne&&ue?T=`${ne}_${ue}`:T=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,u={id:T,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(u),u},xe=(T,ue)=>{N.lastId=ue,T&&N.byStep.set(T,ue)},Ie=(T,ue)=>{var Ze;let Le=(Ze=T.reasoningId)!=null?Ze:T.id,Me=j(T);if(Le){let Ge=String(Le);return xe(Me,Ge),Ge}if(Me){let Ge=N.byStep.get(Me);if(Ge)return N.lastId=Ge,Ge}if(N.lastId&&!ue)return N.lastId;if(!ue)return null;let He=`reason-${c()}`;return xe(Me,He),He},_e=T=>{let ue=A.get(T);if(ue)return ue;let Le={id:`reason-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"streaming",chunks:[]}};return A.set(T,Le),g(Le),Le},Se=(T,ue)=>{D.lastId=ue,T&&D.byCall.set(T,ue)},ve=new Set,re=new Map,X=new Set,ie=new Map,he=T=>{if(!T)return!1;let ue=T.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},oe=(T,ue)=>{var Ze;let Le=(Ze=T.toolId)!=null?Ze:T.id,Me=V(T);if(Le){let Ge=String(Le);return Se(Me,Ge),Ge}if(Me){let Ge=D.byCall.get(Me);if(Ge)return D.lastId=Ge,Ge}if(D.lastId&&!ue)return D.lastId;if(!ue)return null;let He=`tool-${c()}`;return Se(Me,He),He},K=T=>{let ue=W.get(T);if(ue)return ue;let Le={id:`tool-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:T,status:"pending"}};return W.set(T,Le),g(Le),Le},te=T=>{if(typeof T=="number"&&Number.isFinite(T))return T;if(typeof T=="string"){let ue=Number(T);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Le=Date.parse(T);if(!Number.isNaN(Le))return Le}return Date.now()},qe=T=>{if(typeof T=="string")return T;if(T==null)return"";try{return JSON.stringify(T)}catch{return String(T)}},Y=new Map,le=new Map,Pe=new Map,it=(T,ue,Le)=>{var ut;let Me=Pe.get(T);Me||(Me=[],Pe.set(T,Me));let He=0,Ze=Me.length;for(;He<Ze;){let Wt=He+Ze>>>1;Me[Wt].seq<ue?He=Wt+1:Ze=Wt}((ut=Me[He])==null?void 0:ut.seq)===ue?Me[He]={seq:ue,text:Le}:Me.splice(He,0,{seq:ue,text:Le});let Ge="";for(let Wt=0;Wt<Me.length;Wt++)Ge+=Me[Wt].text;return Ge},lt=(T,ue)=>{let Le=qe(ue),Me=le.get(T.id),He=ff(Me,Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=G=>{var ke;let de=(ke=T.content)!=null?ke:"";G.trim()!==""&&(de.trim().length===0||G.startsWith(de)||G.trimStart().startsWith(de.trim()))&&(T.content=G)},ut=()=>{var G;if(Ze){let de=(G=Ze.close)==null?void 0:G.call(Ze);de instanceof Promise&&de.catch(()=>{})}Y.delete(T.id),le.delete(T.id),T.streaming=!1,g(T)};if(!Ze){Ge(Le),ut();return}let Wt=Hs(He);if(Wt!==null&&Wt.trim()!==""){Ge(Wt),ut();return}let q=G=>{var vt;let de=typeof G=="string"?G:(vt=G==null?void 0:G.text)!=null?vt:null;if(de!==null&&de.trim()!=="")return de;let ke=Ze.getExtractedText();return ke!==null&&ke.trim()!==""?ke:Le},ot;try{ot=Ze.processChunk(He)}catch{Ge(Le),ut();return}if(ot instanceof Promise){ot.then(G=>{Ge(q(G)),ut()}).catch(()=>{Ge(Le),ut()});return}Ge(q(ot)),ut()},rt=null,Ee=(T,ue,Le,Me)=>{var Wt;T.rawContent=ue,Y.has(T.id)||Y.set(T.id,this.createStreamParser());let He=Y.get(T.id),Ze=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(Ze&&le.set(T.id,ue),He.__isPlainTextParser===!0){T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T);return}let ut=He.processChunk(ue);if(ut instanceof Promise)ut.then(q=>{var G;let ot=typeof q=="string"?q:(G=q==null?void 0:q.text)!=null?G:null;ot!==null&&ot.trim()!==""?(T.content=ot,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}).catch(()=>{T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T)});else{let q=typeof ut=="string"?ut:(Wt=ut==null?void 0:ut.text)!=null?Wt:null;q!==null&&q.trim()!==""?(T.content=q,g(T)):!Ze&&!ue.trim().startsWith("<")&&(T.content=Me!==void 0?ue:T.content+Le,le.delete(T.id),Y.delete(T.id),T.rawContent=void 0,g(T))}},pe=(T,ue)=>{var Wt,q;let Le=ue!=null?ue:T.content;if(Le==null||Le===""){T.streaming=!1,g(T);return}let Me=le.get(T.id),He=Me!=null?Me:qe(Le);T.rawContent=He;let Ze=Y.get(T.id),Ge=null,ut=!1;if(Ze&&(Ge=Ze.getExtractedText(),Ge===null&&(Ge=Hs(He)),Ge===null)){let ot=Ze.processChunk(He);ot instanceof Promise?(ut=!0,ot.then(G=>{var ke;let de=typeof G=="string"?G:(ke=G==null?void 0:G.text)!=null?ke:null;de!==null&&(T.content=de,T.streaming=!1,Y.delete(T.id),le.delete(T.id),g(T))}).catch(()=>{})):Ge=typeof ot=="string"?ot:(Wt=ot==null?void 0:ot.text)!=null?Wt:null}if(!ut){Ge!==null&&Ge.trim()!==""?T.content=Ge:le.has(T.id)||(T.content=qe(Le));let ot=Y.get(T.id);if(ot){let G=(q=ot.close)==null?void 0:q.call(ot);G instanceof Promise&&G.catch(()=>{}),Y.delete(T.id)}le.delete(T.id),T.streaming=!1,g(T)}},Xe=(T,ue,Le)=>{let Me=L.get(T);if(Me)return Me;let He={id:`nested-${ue}-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Le?{variant:Le}:{},...Le==="reasoning"?{reasoning:{id:T,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return L.set(T,He),g(He),He},J=[],ce,we=new Map,je=0,Pt="agent",Te=null,me=null,fn=new Map,It=(rn=this.config.iterationDisplay)!=null?rn:"separate";for(ce=()=>{var T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un,ye,dt,Qt,on,wr,fs,Hr,ho,Cr,_,Fo,Ar,Sr,Br,Tr,lr,Oo,ra,qn,zn,cr,dr,yo,Dr,yn,Mr,_o,bo,$o,oa,Uo,sa,qo,ht,hs,tr,Rn,aa,ia;for(let Zr=0;Zr<J.length;Zr++){let tt=J[Zr].payloadType,w=J[Zr].payload;if(tt==="reasoning_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$),Xe(U,$,"reasoning");continue}let Q=(T=Ie(w,!0))!=null?T:`reason-${c()}`,fe=_e(Q);fe.reasoning=(ue=fe.reasoning)!=null?ue:{id:Q,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Me=fe.reasoning.startedAt)!=null?Me:te((Le=w.startedAt)!=null?Le:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(tt==="reasoning_delta"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Oe=L.get(U),Je=(Ge=(Ze=(He=w.reasoningText)!=null?He:w.text)!=null?Ze:w.delta)!=null?Ge:"";Je&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(Je)),g(Oe));continue}let $=(Wt=(ut=Ie(w,!1))!=null?ut:Ie(w,!0))!=null?Wt:`reason-${c()}`,Q=_e($);Q.reasoning=(q=Q.reasoning)!=null?q:{id:$,status:"streaming",chunks:[]},Q.reasoning.startedAt=(G=Q.reasoning.startedAt)!=null?G:te((ot=w.startedAt)!=null?ot:w.timestamp);let fe=(vt=(ke=(de=w.reasoningText)!=null?de:w.text)!=null?ke:w.delta)!=null?vt:"";if(fe&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let Je=it($,Oe,String(fe));Q.reasoning.chunks=[Je]}else Q.reasoning.chunks.push(String(fe))}if(Q.reasoning.status=w.done?"complete":"streaming",w.done){Q.reasoning.completedAt=te((Yt=w.completedAt)!=null?Yt:w.timestamp);let Oe=(Zt=Q.reasoning.startedAt)!=null?Zt:Date.now();Q.reasoning.durationMs=Math.max(0,((pn=Q.reasoning.completedAt)!=null?pn:Date.now())-Oe)}Q.streaming=Q.reasoning.status!=="complete",g(Q)}else if(tt==="reasoning_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)&&L.has(U)){let Je=L.get(U);if(Je.reasoning){let Et=typeof w.text=="string"?w.text:"";Et&&Je.reasoning.chunks.length===0&&Je.reasoning.chunks.push(Et),Je.reasoning.status="complete",Je.streaming=!1,g(Je)}F.delete(U),L.delete(U);continue}let $=(et=(Ht=Ie(w,!1))!=null?Ht:Ie(w,!0))!=null?et:`reason-${c()}`,Q=typeof w.text=="string"?w.text:"";!A.get($)&&(Q||w.scope==="loop")&&_e($);let fe=A.get($);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),Q&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(Q),fe.reasoning.status="complete",fe.reasoning.completedAt=te((Rt=w.completedAt)!=null?Rt:w.timestamp);let Je=(ct=fe.reasoning.startedAt)!=null?ct:Date.now();fe.reasoning.durationMs=Math.max(0,((Kt=fe.reasoning.completedAt)!=null?Kt:Date.now())-Je),fe.streaming=!1,g(fe)}let Oe=j(w);Oe&&N.byStep.delete(Oe)}else if(tt==="tool_start"){u&&(u.streaming=!1,g(u),u=null),typeof w.iteration=="number"&&(je=w.iteration);let U=(An=(Jn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Jn:oe(w,!0))!=null?An:`tool-${c()}`,$=(en=w.toolName)!=null?en:w.name;if(he($)){ve.add(U);continue}Se(V(w),U);let Q=K(U),fe=(In=Q.toolCall)!=null?In:{id:U,status:"pending"};fe.name=$!=null?$:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(xt=fe.startedAt)!=null?xt:te((yr=w.startedAt)!=null?yr:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,Q.toolCall=fe,Q.streaming=!0,w.executionId&&(Q.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(Q)}else if(tt==="tool_output_delta"){let U=(br=(Nn=oe(w,!1))!=null?Nn:oe(w,!0))!=null?br:`tool-${c()}`;if(ve.has(U))continue;let $=K(U),Q=(Pr=$.toolCall)!=null?Pr:{id:U,status:"running"};Q.startedAt=(yt=Q.startedAt)!=null?yt:te((ir=w.startedAt)!=null?ir:w.timestamp);let fe=(mo=(vr=(uo=w.text)!=null?uo:w.delta)!=null?vr:w.message)!=null?mo:"";fe&&(Q.chunks=(Wn=Q.chunks)!=null?Wn:[],Q.chunks.push(String(fe))),Q.status="running",$.toolCall=Q,$.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(Ir=$.agentMetadata)!=null?Ir:{executionId:(No=Oe==null?void 0:Oe.executionId)!=null?No:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g($)}else if(tt==="tool_complete"){let U=(Kr=(Vr=oe(w,!1))!=null?Vr:oe(w,!0))!=null?Kr:`tool-${c()}`;if(ve.has(U)){ve.delete(U);continue}let $=K(U),Q=(go=$.toolCall)!=null?go:{id:U,status:"running"};Q.status="complete",w.result!==void 0&&(Q.result=w.result),typeof w.duration=="number"&&(Q.duration=w.duration),Q.completedAt=te((fo=w.completedAt)!=null?fo:w.timestamp);let fe=(Gr=w.duration)!=null?Gr:w.executionTime;if(typeof fe=="number")Q.durationMs=fe;else{let Et=(Ct=Q.startedAt)!=null?Ct:Date.now();Q.durationMs=Math.max(0,((Fn=Q.completedAt)!=null?Fn:Date.now())-Et)}$.toolCall=Q,$.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&($.agentMetadata=(St=$.agentMetadata)!=null?St:{executionId:(On=Oe==null?void 0:Oe.executionId)!=null?On:w.executionId,iteration:(Sn=Oe==null?void 0:Oe.iteration)!=null?Sn:w.iteration}),g($);let Je=V(w);Je&&D.byCall.delete(Je)}else if(tt==="await"&&w.toolName){let U=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,$=(Yn=U!=null?U:w.toolId)!=null?Yn:`local-${c()}`,Q=K($),fe=w.toolName,Oe=w.origin==="webmcp"&&!Jo(fe)?`webmcp:${fe}`:fe,Je=Jo(Oe),Et=(Zn=Q.toolCall)!=null?Zn:{id:$,status:"pending"};Et.name=Oe,Et.args=w.parameters,Et.status=Je?"running":"complete",Et.chunks=(_n=Et.chunks)!=null?_n:[],Et.startedAt=(Xr=Et.startedAt)!=null?Xr:te((Wr=(Qr=w.startedAt)!=null?Qr:w.timestamp)!=null?Wr:w.awaitedAt),Je?(Et.completedAt=void 0,Et.duration=void 0,Et.durationMs=void 0):Et.completedAt=($n=Et.completedAt)!=null?$n:Et.startedAt,Q.toolCall=Et,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tn=w.executionId)!=null?Tn:(Bt=Q.agentMetadata)==null?void 0:Bt.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},g(Q)}else if(tt==="text_start"){let U=typeof w.id=="string"?w.id:null,$=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(U&&$){F.set(U,$);continue}let Q=u;Q&&(Pt==="flow"?(pe(Q),rt=Q):(Q.streaming=!1,g(Q)),u=null),M=typeof w.id=="string"?w.id:M,E=""}else if(tt==="text_delta"){let U=typeof w.id=="string"?w.id:null,$=U?F.get(U):void 0;if(U&&$){let fe=typeof w.delta=="string"?w.delta:"",Oe=((er=R.get(U))!=null?er:"")+fe;if(R.set(U,Oe),Oe.trim()==="")continue;let Je=Xe(U,$);Je.agentMetadata={...Je.agentMetadata,executionId:w.executionId,parentToolId:$},Ee(Je,Oe,fe,void 0);continue}if(M=typeof w.id=="string"?w.id:M,Pt==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(E+=fe,E.trim()==="")continue;let Oe=Ue();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ee(Oe,E,fe,void 0),v=Oe;continue}let Q=Ue();Q.content+=(Jr=w.delta)!=null?Jr:"",Q.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Te!=null?Te:void 0,agentName:me==null?void 0:me.agentName},v=Q,g(Q)}else if(tt==="text_complete"){let U=typeof w.id=="string"?w.id:null;if(U&&F.has(U)){let Q=L.get(U);Q&&pe(Q),F.delete(U),R.delete(U),L.delete(U);continue}let $=u;$&&(Pt==="flow"?(pe($),rt=$):(((Rr=$.content)!=null?Rr:"")===""&&typeof w.text=="string"&&($.content=w.text),$.streaming=!1,g($)),u=null),M=null,E=""}else if(tt==="step_complete"){let U=w.stepType,$=w.executionType;if(U==="tool"||$==="context")continue;if(w.success===!1){let Q=w.error,fe=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((Yr=Q.message)!=null?Yr:"Step failed"):"Step failed";t({type:"error",error:new Error(fe)});let Oe=u;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),t({type:"status",status:"idle"});continue}{let Q=rt;rt=null;let fe=w.stopReason,Oe=(xr=w.result)==null?void 0:xr.response;if(Q)fe&&(Q.stopReason=fe),Oe!=null?lt(Q,Oe):Q.streaming!==!1&&(Y.delete(Q.id),le.delete(Q.id),Q.streaming=!1,g(Q));else{let Je=Oe!=null&&Oe!=="";if(Je||fe){let Et=Ue();fe&&(Et.stopReason=fe),Je?pe(Et,Oe):(Et.streaming=!1,g(Et))}}continue}}else if(tt==="execution_start")Pt=w.kind==="flow"?"flow":"agent",Pt==="agent"&&(me={executionId:w.executionId,agentId:(Un=w.agentId)!=null?Un:"virtual",agentName:(ye=w.agentName)!=null?ye:"",status:"running",currentIteration:0,maxTurns:(dt=w.maxTurns)!=null?dt:1,startedAt:te(w.startedAt)});else if(tt==="turn_start"){let U=typeof w.iteration=="number"?w.iteration:je;if(U!==je){if(me&&(me.currentIteration=U),It==="separate"&&U>1){let $=u;$&&($.streaming=!1,g($),fn.set(U-1,$),u=null)}je=U}Te=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let U=(Qt=w.toolCallId)!=null?Qt:D.lastId;if(U){let $=W.get(U);$!=null&&$.toolCall&&($.toolCall.chunks=(on=$.toolCall.chunks)!=null?on:[],$.toolCall.chunks.push((wr=w.delta)!=null?wr:""),g($))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let U=w.stopReason,$=u!=null?u:v;if(U&&$!==null){let Q=w.id;(!Q||((fs=$.agentMetadata)==null?void 0:fs.turnId)===Q)&&($.stopReason=U,g($))}Te===w.id&&(Te=null)}else if(tt==="media_start"){let U=String(w.id);we.set(U,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let U=we.get(String(w.id));U&&typeof w.delta=="string"&&U.parts.push(w.delta)}else if(tt==="media_complete"){let U=String(w.id),$=we.get(U);we.delete(U);let Q=(ho=(Hr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Hr:$==null?void 0:$.mediaType)!=null?ho:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:$&&$.parts.length>0?$.parts.join(""):void 0,Je=null;if(fe)Je={type:"media",data:fe,mediaType:Q};else if(Oe){let jn=Q.toLowerCase();Je={type:jn==="image"||jn.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:Q}}let Et=(Cr=w.toolCallId)!=null?Cr:$==null?void 0:$.toolCallId,Nr=Je?[Je]:[],Hn=[];for(let jn of Nr){if(!jn||typeof jn!="object")continue;let un=jn,eo=typeof un.type=="string"?un.type:void 0,Fr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",mn=null,Bn="";if(eo==="media"){let Vn=typeof un.data=="string"?un.data:void 0;if(!Vn)continue;Bn=Fr.length>0?Fr:"application/octet-stream",mn=`data:${Bn};base64,${Vn}`}else if(eo==="image-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else if(eo==="file-url"){let Vn=typeof un.url=="string"?un.url:void 0;if(!Vn)continue;Bn=Fr,mn=Vn}else continue;if(mn)if(eo==="image-url"||Bn.startsWith("image/"))Hn.push({type:"image",image:mn,...Bn.includes("/")?{mimeType:Bn}:{}});else if(Bn.startsWith("audio/"))Hn.push({type:"audio",audio:mn,mimeType:Bn});else if(Bn.startsWith("video/"))Hn.push({type:"video",video:mn,mimeType:Bn});else{let Vn=Bn||"application/octet-stream";Hn.push({type:"file",data:mn,mimeType:Vn,filename:mf(Vn)})}}if(Hn.length>0){let jn=c(),un=Et,Fr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${jn}`:String(jn)}`,role:"assistant",content:"",contentParts:Hn,createdAt:new Date().toISOString(),streaming:!1,sequence:jn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:je}};g(Fr);let mn=u;mn&&(mn.streaming=!1,g(mn)),u=null,x.current=null}}else if(tt==="execution_complete"){let U=(_=w.kind)!=null?_:Pt;U==="agent"&&me&&(me.status=w.success?"complete":"error",me.completedAt=te(w.completedAt),me.stopReason=w.stopReason);let $=u;$&&(U==="flow"&&$.streaming!==!1?pe($):($.streaming=!1,g($)),u=null),M=null,E="",rt=null,t({type:"status",status:"idle"})}else if(tt==="execution_error"){let U=typeof w.error=="string"?w.error:(Ar=(Fo=w.error)==null?void 0:Fo.message)!=null?Ar:"Execution error";t({type:"error",error:new Error(U)})}else if(tt!=="ping"){if(tt==="approval_start"){let U=(Sr=w.approvalId)!=null?Sr:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(Br=me==null?void 0:me.agentId)!=null?Br:"virtual",executionId:(lr=(Tr=w.executionId)!=null?Tr:me==null?void 0:me.executionId)!=null?lr:"",toolName:(Oo=w.toolName)!=null?Oo:"",toolType:w.toolType,description:(qn=w.description)!=null?qn:`Execute ${(ra=w.toolName)!=null?ra:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let U=(zn=w.approvalId)!=null?zn:`approval-${c()}`,$={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:"pending",agentId:(cr=me==null?void 0:me.agentId)!=null?cr:"virtual",executionId:(yo=(dr=w.executionId)!=null?dr:me==null?void 0:me.executionId)!=null?yo:"",toolName:(Dr=w.toolName)!=null?Dr:"",toolType:w.toolType,description:(Mr=w.description)!=null?Mr:`Execute ${(yn=w.toolName)!=null?yn:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g($)}else if(tt==="approval_complete"){let U=w.approvalId;if(U){let Q={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:U,status:(_o=w.decision)!=null?_o:"approved",agentId:(bo=me==null?void 0:me.agentId)!=null?bo:"virtual",executionId:(oa=($o=w.executionId)!=null?$o:me==null?void 0:me.executionId)!=null?oa:"",toolName:(Uo=w.toolName)!=null?Uo:"",description:(sa=w.description)!=null?sa:"",resolvedAt:Date.now()}};g(Q)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let U=w.artifactType,$=String(w.id),Q=typeof w.title=="string"?w.title:void 0;if(t({type:"artifact_start",id:$,artifactType:U,title:Q,component:typeof w.component=="string"?w.component:void 0}),ie.set($,{markdown:"",title:Q}),!X.has($)){X.add($);let fe={id:`artifact-ref-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:$,title:Q,artifactType:U,status:"streaming"}})};re.set($,fe),g(fe)}}else if(tt==="artifact_delta"){let U=String(w.id),$=typeof w.delta=="string"?w.delta:String((qo=w.delta)!=null?qo:"");t({type:"artifact_delta",id:U,artDelta:$});let Q=ie.get(U);Q&&(Q.markdown+=$)}else if(tt==="artifact_update"){let U=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};t({type:"artifact_update",id:String(w.id),props:U,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let U=String(w.id);t({type:"artifact_complete",id:U});let $=re.get(U);if($){$.streaming=!1;try{let Q=JSON.parse((ht=$.rawContent)!=null?ht:"{}");if(Q.props){Q.props.status="complete";let fe=ie.get(U);fe!=null&&fe.markdown&&(Q.props.markdown=fe.markdown)}$.rawContent=JSON.stringify(Q)}catch{}ie.delete(U),g($),re.delete(U)}}}else if(tt==="transcript_insert"){let U=w.message;if(!U||typeof U!="object")continue;let $=String((hs=U.id)!=null?hs:`msg-${c()}`),Q=U.role,Oe={id:$,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:c()};if(g(Oe),Oe.rawContent)try{let Je=JSON.parse(Oe.rawContent),Et=(tr=Je==null?void 0:Je.props)==null?void 0:tr.artifactId;typeof Et=="string"&&X.add(Et)}catch{}u=null,x.current=null,Y.delete($),le.delete($)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let U=typeof w.error=="string"?w.error:((Rn=w.error)==null?void 0:Rn.message)!=null?String(w.error.message):"Execution error";t({type:"error",error:new Error(U)});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let U=null;if(w.error instanceof Error)U=w.error;else if(tt==="dispatch_error"){let $=(aa=w.message)!=null?aa:w.error;$!=null&&$!==""&&(U=new Error(String($)))}else{let $=w.error;typeof $=="string"&&$!==""?U=new Error($):$!=null&&typeof $=="object"&&"message"in $&&(U=new Error(String((ia=$.message)!=null?ia:$)))}if(U){t({type:"error",error:U});let $=u;$&&$.streaming&&($.streaming=!1,g($)),t({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:T,value:ue}=await o.read();if(T)break;a+=s.decode(ue,{stream:!0});let Le=a.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>t,processChunk:async r=>{if(r.length<=e)return t!==null?{text:t,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(t=s),e=r.length,t!==null?{text:t,raw:r}:null},close:async()=>{}}},Os=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},bu=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},vu=()=>{var e;let t=Ef();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:t.processChunk(n)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},xu=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let o=(0,ls.parse)(n,ls.STR|ls.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?fu(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=fu(o.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var wu=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(t=r[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Cu="4.2.0";var _s=Cu;var kf="https://api.runtype.com/v1/dispatch",Ma="https://api.runtype.com";function Lf(t){var s,a;let e=t.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Ii=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Pf(t){switch(t){case"json":return xu;case"regex-json":return vu;case"xml":return wu;default:return bu}}var Au=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function If(t,e){if(!t)return e;let n=t.trim(),r=e.trim();if(n.length===0)return e;if(r.length===0)return t;let o=Au(n);if(!Au(r))return t;if(!o||r===n||r.startsWith(n))return e;let a=Os(t);return Os(e)!==null&&a===null?e:t}var $s=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=e.apiUrl)!=null?n:kf,this.headers={"Content-Type":"application/json","X-Persona-Version":_s,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Pf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new xa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(e=this.config).onSessionInit)==null||n.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let e=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...e&&{sessionId:e}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return this.isAgentMode()?this.dispatchAgent(e,n):this.isClientTokenMode()?this.dispatchClientToken(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,f={sessionId:d.sessionId,messages:e.messages.filter(Ii).map(E=>{var I,A,L;return{id:E.id,role:E.role,content:(L=(A=(I=E.contentParts)!=null?I:E.llmContent)!=null?A:E.rawContent)!=null?L:E.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,m=!!(g&&g.length>0),x=m?Zp(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,M=m&&v&&this.lastSentClientToolsFingerprint===x,R=!1,T=null,k;for(let E=0;;E++){let A={...f,...m&&(R||!M)&&g?{clientTools:g}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},body:JSON.stringify(A),signal:r.signal}),k.status===409&&E===0&&m){let L=await k.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){R=!0,this.lastSentClientToolsFingerprint=null;continue}T=L!=null?L:{error:"Chat request failed"}}break}if(!k.ok){let E=T!=null?T:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:A}),A}if(k.status===429){let A=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(E.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!k.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ma}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(e,n,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ma}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=e.slice().filter(Ii).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let c=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return c-u}).map(i=>{var d,c,u;return{role:i.role,content:(u=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Li(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(e){var s,a;let r={messages:e.slice().filter(Ii).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),u=new Date(d.createdAt).getTime();return c-u}).map(i=>{var d,c,u;return{role:i.role,content:(u=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?u:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Li(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let c=await d({messages:e,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(e,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=f,o(f),f},c=u=>r.current?r.current:d(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,n,r){var pn,Ft,Yt,Rr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=B=>{let K=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,ue=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Be=B.tools?B.tools.map($e=>({...$e,chunks:$e.chunks?[...$e.chunks]:void 0})):void 0;return{...B,reasoning:K,toolCall:ue,tools:Be}},f=B=>{if(B.role!=="assistant"||B.variant)return!0;let K=Array.isArray(B.contentParts)&&B.contentParts.length>0,ue=typeof B.rawContent=="string"&&B.rawContent.trim()!=="";return typeof B.content=="string"&&B.content.trim()!==""||K||ue||!!B.stopReason},g=B=>{f(B)&&n({type:"message",message:u(B)})},m=null,x=null,v={current:null},M={current:null},R=null,T="",k=new Map,E=new Map,I=new Map,A=new Map,L=new Map,O={lastId:null,byStep:new Map},_={lastId:null,byCall:new Map},H=B=>{if(B==null)return null;try{return String(B)}catch{return null}},U=B=>{var K,ue,Be,$e,De;return H((De=($e=(Be=(ue=(K=B.stepId)!=null?K:B.step_id)!=null?ue:B.step)!=null?Be:B.parentId)!=null?$e:B.flowStepId)!=null?De:B.flow_step_id)},F=B=>{var K,ue,Be,$e,De,Le,it;return H((it=(Le=(De=($e=(Be=(ue=(K=B.callId)!=null?K:B.call_id)!=null?ue:B.requestId)!=null?Be:B.request_id)!=null?$e:B.toolCallId)!=null?De:B.tool_call_id)!=null?Le:B.stepId)!=null?it:B.step_id)},ee=r,Ae=!1,pe=()=>{if(m)return m;let B,K=R;return!Ae&&ee?(B=ee,Ae=!0):ee&&K?B=`${ee}_${K}`:B=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:B,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(m),m},te=(B,K)=>{O.lastId=K,B&&O.byStep.set(B,K)},xe=(B,K)=>{var De;let ue=(De=B.reasoningId)!=null?De:B.id,Be=U(B);if(ue){let Le=String(ue);return te(Be,Le),Le}if(Be){let Le=O.byStep.get(Be);if(Le)return O.lastId=Le,Le}if(O.lastId&&!K)return O.lastId;if(!K)return null;let $e=`reason-${c()}`;return te(Be,$e),$e},We=B=>{let K=A.get(B);if(K)return K;let ue={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"streaming",chunks:[]}};return A.set(B,ue),g(ue),ue},le=(B,K)=>{_.lastId=K,B&&_.byCall.set(B,K)},me=new Set,re=new Map,oe=new Set,de=new Map,ze=B=>{if(!B)return!1;let K=B.replace(/_+/g,"_").replace(/^_|_$/g,"");return K==="emit_artifact_markdown"||K==="emit_artifact_component"},Fe=(B,K)=>{var De;let ue=(De=B.toolId)!=null?De:B.id,Be=F(B);if(ue){let Le=String(ue);return le(Be,Le),Le}if(Be){let Le=_.byCall.get(Be);if(Le)return _.lastId=Le,Le}if(_.lastId&&!K)return _.lastId;if(!K)return null;let $e=`tool-${c()}`;return le(Be,$e),$e},G=B=>{let K=L.get(B);if(K)return K;let ue={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:B,status:"pending"}};return L.set(B,ue),g(ue),ue},X=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let K=Number(B);if(!Number.isNaN(K)&&Number.isFinite(K))return K;let ue=Date.parse(B);if(!Number.isNaN(ue))return ue}return Date.now()},ve=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},Y=new Map,ie=new Map,Ee=new Map,Je=(B,K,ue)=>{var it;let Be=Ee.get(B);Be||(Be=[],Ee.set(B,Be));let $e=0,De=Be.length;for(;$e<De;){let Wt=$e+De>>>1;Be[Wt].seq<K?$e=Wt+1:De=Wt}((it=Be[$e])==null?void 0:it.seq)===K?Be[$e]={seq:K,text:ue}:Be.splice($e,0,{seq:K,text:ue});let Le="";for(let Wt=0;Wt<Be.length;Wt++)Le+=Be[Wt].text;return Le},nt=(B,K)=>{let ue=ve(K),Be=ie.get(B.id),$e=If(Be,ue);B.rawContent=$e;let De=Y.get(B.id),Le=P=>{var Me;let ce=(Me=B.content)!=null?Me:"";P.trim()!==""&&(ce.trim().length===0||P.startsWith(ce)||P.trimStart().startsWith(ce.trim()))&&(B.content=P)},it=()=>{var P;if(De){let ce=(P=De.close)==null?void 0:P.call(De);ce instanceof Promise&&ce.catch(()=>{})}Y.delete(B.id),ie.delete(B.id),B.streaming=!1,g(B)};if(!De){Le(ue),it();return}let Wt=Os($e);if(Wt!==null&&Wt.trim()!==""){Le(Wt),it();return}let yt=P=>{var Mt;let ce=typeof P=="string"?P:(Mt=P==null?void 0:P.text)!=null?Mt:null;if(ce!==null&&ce.trim()!=="")return ce;let Me=De.getExtractedText();return Me!==null&&Me.trim()!==""?Me:ue},Rt;try{Rt=De.processChunk($e)}catch{Le(ue),it();return}if(Rt instanceof Promise){Rt.then(P=>{Le(yt(P)),it()}).catch(()=>{Le(ue),it()});return}Le(yt(Rt)),it()},wt=null,dt=(B,K,ue,Be)=>{var Wt;B.rawContent=K,Y.has(B.id)||Y.set(B.id,this.createStreamParser());let $e=Y.get(B.id),De=K.trim().startsWith("{")||K.trim().startsWith("[");if(De&&ie.set(B.id,K),$e.__isPlainTextParser===!0){B.content=Be!==void 0?K:B.content+ue,ie.delete(B.id),Y.delete(B.id),B.rawContent=void 0,g(B);return}let it=$e.processChunk(K);if(it instanceof Promise)it.then(yt=>{var P;let Rt=typeof yt=="string"?yt:(P=yt==null?void 0:yt.text)!=null?P:null;Rt!==null&&Rt.trim()!==""?(B.content=Rt,g(B)):!De&&!K.trim().startsWith("<")&&(B.content=Be!==void 0?K:B.content+ue,ie.delete(B.id),Y.delete(B.id),B.rawContent=void 0,g(B))}).catch(()=>{B.content=Be!==void 0?K:B.content+ue,ie.delete(B.id),Y.delete(B.id),B.rawContent=void 0,g(B)});else{let yt=typeof it=="string"?it:(Wt=it==null?void 0:it.text)!=null?Wt:null;yt!==null&&yt.trim()!==""?(B.content=yt,g(B)):!De&&!K.trim().startsWith("<")&&(B.content=Be!==void 0?K:B.content+ue,ie.delete(B.id),Y.delete(B.id),B.rawContent=void 0,g(B))}},tt=(B,K)=>{var Wt,yt;let ue=K!=null?K:B.content;if(ue==null||ue===""){B.streaming=!1,g(B);return}let Be=ie.get(B.id),$e=Be!=null?Be:ve(ue);B.rawContent=$e;let De=Y.get(B.id),Le=null,it=!1;if(De&&(Le=De.getExtractedText(),Le===null&&(Le=Os($e)),Le===null)){let Rt=De.processChunk($e);Rt instanceof Promise?(it=!0,Rt.then(P=>{var Me;let ce=typeof P=="string"?P:(Me=P==null?void 0:P.text)!=null?Me:null;ce!==null&&(B.content=ce,B.streaming=!1,Y.delete(B.id),ie.delete(B.id),g(B))}).catch(()=>{})):Le=typeof Rt=="string"?Rt:(Wt=Rt==null?void 0:Rt.text)!=null?Wt:null}if(!it){Le!==null&&Le.trim()!==""?B.content=Le:ie.has(B.id)||(B.content=ve(ue));let Rt=Y.get(B.id);if(Rt){let P=(yt=Rt.close)==null?void 0:yt.call(Rt);P instanceof Promise&&P.catch(()=>{}),Y.delete(B.id)}ie.delete(B.id),B.streaming=!1,g(B)}},He=(B,K,ue)=>{let Be=E.get(B);if(Be)return Be;let $e={id:`nested-${K}-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...ue?{variant:ue}:{},...ue==="reasoning"?{reasoning:{id:B,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:K}};return E.set(B,$e),g($e),$e},Q=[],Ve,je=new Map,we=0,Se="agent",Ye=null,Qe=null,Te=new Map,_e=(pn=this.config.iterationDisplay)!=null?pn:"separate";for(Ve=()=>{var B,K,ue,Be,$e,De,Le,it,Wt,yt,Rt,P,ce,Me,Mt,Ze,qt,yn,vt,xt,Ht,Ct,un,Ut,On,En,Mn,vn,kn,lr,At,br,vr,Hr,cr,ut,yo,xr,bo,Bn,Uo,Gr,Br,Qr,Xr,vo,xo,Jr,bt,_n,$n,Ln,St,Yn,Zn,Un,Yr,Dr,Zr,zn,Bt,Pn,er,eo,Nr,to,ye,Dn,wr,mt,sn,an,Cr,xs,Fr,wo,Ar,z,zo,Sr,Tr,Or,Er,dr,qo,la,qn,jn,pr,ur,Co,_r,xn,Mr,jo,Ao,Vo,ca,Ko,da,Go,pt,ws,tr,Nn;for(let Qo=0;Qo<Q.length;Qo++){let st=Q[Qo].payloadType,w=Q[Qo].payload;if(st==="reasoning_start"){let j=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&q){k.set(j,q),He(j,q,"reasoning");continue}let J=(B=xe(w,!0))!=null?B:`reason-${c()}`,fe=We(J);fe.reasoning=(K=fe.reasoning)!=null?K:{id:J,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:X((ue=w.startedAt)!=null?ue:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(st==="reasoning_delta"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)&&E.has(j)){let Oe=E.get(j),gt=(Le=(De=($e=w.reasoningText)!=null?$e:w.text)!=null?De:w.delta)!=null?Le:"";gt&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(gt)),g(Oe));continue}let q=(Wt=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?Wt:`reason-${c()}`,J=We(q);J.reasoning=(yt=J.reasoning)!=null?yt:{id:q,status:"streaming",chunks:[]},J.reasoning.startedAt=(P=J.reasoning.startedAt)!=null?P:X((Rt=w.startedAt)!=null?Rt:w.timestamp);let fe=(Mt=(Me=(ce=w.reasoningText)!=null?ce:w.text)!=null?Me:w.delta)!=null?Mt:"";if(fe&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let gt=Je(q,Oe,String(fe));J.reasoning.chunks=[gt]}else J.reasoning.chunks.push(String(fe))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=X((Ze=w.completedAt)!=null?Ze:w.timestamp);let Oe=(qt=J.reasoning.startedAt)!=null?qt:Date.now();J.reasoning.durationMs=Math.max(0,((yn=J.reasoning.completedAt)!=null?yn:Date.now())-Oe)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(st==="reasoning_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)&&E.has(j)){let gt=E.get(j);if(gt.reasoning){let It=typeof w.text=="string"?w.text:"";It&>.reasoning.chunks.length===0&>.reasoning.chunks.push(It),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(j),E.delete(j);continue}let q=(xt=(vt=xe(w,!1))!=null?vt:xe(w,!0))!=null?xt:`reason-${c()}`,J=typeof w.text=="string"?w.text:"";!A.get(q)&&(J||w.scope==="loop")&&We(q);let fe=A.get(q);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),J&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(J),fe.reasoning.status="complete",fe.reasoning.completedAt=X((Ht=w.completedAt)!=null?Ht:w.timestamp);let gt=(Ct=fe.reasoning.startedAt)!=null?Ct:Date.now();fe.reasoning.durationMs=Math.max(0,((un=fe.reasoning.completedAt)!=null?un:Date.now())-gt),fe.streaming=!1,g(fe)}let Oe=U(w);Oe&&O.byStep.delete(Oe)}else if(st==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof w.iteration=="number"&&(we=w.iteration);let j=(On=(Ut=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Ut:Fe(w,!0))!=null?On:`tool-${c()}`,q=(En=w.toolName)!=null?En:w.name;if(ze(q)){me.add(j);continue}le(F(w),j);let J=G(j),fe=(Mn=J.toolCall)!=null?Mn:{id:j,status:"pending"};fe.name=q!=null?q:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(kn=fe.startedAt)!=null?kn:X((vn=w.startedAt)!=null?vn:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,J.toolCall=fe,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(st==="tool_output_delta"){let j=(At=(lr=Fe(w,!1))!=null?lr:Fe(w,!0))!=null?At:`tool-${c()}`;if(me.has(j))continue;let q=G(j),J=(br=q.toolCall)!=null?br:{id:j,status:"running"};J.startedAt=(Hr=J.startedAt)!=null?Hr:X((vr=w.startedAt)!=null?vr:w.timestamp);let fe=(yo=(ut=(cr=w.text)!=null?cr:w.delta)!=null?ut:w.message)!=null?yo:"";fe&&(J.chunks=(xr=J.chunks)!=null?xr:[],J.chunks.push(String(fe))),J.status="running",q.toolCall=J,q.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&(q.agentMetadata=(Uo=q.agentMetadata)!=null?Uo:{executionId:(bo=Oe==null?void 0:Oe.executionId)!=null?bo:w.executionId,iteration:(Bn=Oe==null?void 0:Oe.iteration)!=null?Bn:w.iteration}),g(q)}else if(st==="tool_complete"){let j=(Br=(Gr=Fe(w,!1))!=null?Gr:Fe(w,!0))!=null?Br:`tool-${c()}`;if(me.has(j)){me.delete(j);continue}let q=G(j),J=(Qr=q.toolCall)!=null?Qr:{id:j,status:"running"};J.status="complete",w.result!==void 0&&(J.result=w.result),typeof w.duration=="number"&&(J.duration=w.duration),J.completedAt=X((Xr=w.completedAt)!=null?Xr:w.timestamp);let fe=(vo=w.duration)!=null?vo:w.executionTime;if(typeof fe=="number")J.durationMs=fe;else{let It=(xo=J.startedAt)!=null?xo:Date.now();J.durationMs=Math.max(0,((Jr=J.completedAt)!=null?Jr:Date.now())-It)}q.toolCall=J,q.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&(q.agentMetadata=($n=q.agentMetadata)!=null?$n:{executionId:(bt=Oe==null?void 0:Oe.executionId)!=null?bt:w.executionId,iteration:(_n=Oe==null?void 0:Oe.iteration)!=null?_n:w.iteration}),g(q);let gt=F(w);gt&&_.byCall.delete(gt)}else if(st==="await"&&w.toolName){let j=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(Ln=j!=null?j:w.toolId)!=null?Ln:`local-${c()}`,J=G(q),fe=w.toolName,Oe=w.origin==="webmcp"&&!rs(fe)?`webmcp:${fe}`:fe,gt=rs(Oe),It=(St=J.toolCall)!=null?St:{id:q,status:"pending"};It.name=Oe,It.args=w.parameters,It.status=gt?"running":"complete",It.chunks=(Yn=It.chunks)!=null?Yn:[],It.startedAt=(Yr=It.startedAt)!=null?Yr:X((Un=(Zn=w.startedAt)!=null?Zn:w.timestamp)!=null?Un:w.awaitedAt),gt?(It.completedAt=void 0,It.duration=void 0,It.durationMs=void 0):It.completedAt=(Dr=It.completedAt)!=null?Dr:It.startedAt,J.toolCall=It,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(zn=w.executionId)!=null?zn:(Zr=J.agentMetadata)==null?void 0:Zr.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},g(J)}else if(st==="text_start"){let j=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(j&&q){k.set(j,q);continue}let J=m;J&&(Se==="flow"?(tt(J),wt=J):(J.streaming=!1,g(J)),m=null),R=typeof w.id=="string"?w.id:R,T=""}else if(st==="text_delta"){let j=typeof w.id=="string"?w.id:null,q=j?k.get(j):void 0;if(j&&q){let fe=typeof w.delta=="string"?w.delta:"",Oe=((Bt=I.get(j))!=null?Bt:"")+fe;if(I.set(j,Oe),Oe.trim()==="")continue;let gt=He(j,q);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:q},dt(gt,Oe,fe,void 0);continue}if(R=typeof w.id=="string"?w.id:R,Se==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(T+=fe,T.trim()==="")continue;let Oe=pe();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},dt(Oe,T,fe,void 0),x=Oe;continue}let J=pe();J.content+=(Pn=w.delta)!=null?Pn:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ye!=null?Ye:void 0,agentName:Qe==null?void 0:Qe.agentName},x=J,g(J)}else if(st==="text_complete"){let j=typeof w.id=="string"?w.id:null;if(j&&k.has(j)){let J=E.get(j);J&&tt(J),k.delete(j),I.delete(j),E.delete(j);continue}let q=m;q&&(Se==="flow"?(tt(q),wt=q):(((er=q.content)!=null?er:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),m=null),R=null,T=""}else if(st==="step_complete"){let j=w.stepType,q=w.executionType;if(j==="tool"||q==="context")continue;if(w.success===!1){let J=w.error,fe=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&"message"in J?String((eo=J.message)!=null?eo:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Oe=m;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),n({type:"status",status:"idle"});continue}{let J=wt;wt=null;let fe=w.stopReason,Oe=(Nr=w.result)==null?void 0:Nr.response;if(J)fe&&(J.stopReason=fe),Oe!=null?nt(J,Oe):J.streaming!==!1&&(Y.delete(J.id),ie.delete(J.id),J.streaming=!1,g(J));else{let gt=Oe!=null&&Oe!=="";if(gt||fe){let It=pe();fe&&(It.stopReason=fe),gt?tt(It,Oe):(It.streaming=!1,g(It))}}continue}}else if(st==="execution_start")Se=w.kind==="flow"?"flow":"agent",Se==="agent"&&(Qe={executionId:w.executionId,agentId:(to=w.agentId)!=null?to:"virtual",agentName:(ye=w.agentName)!=null?ye:"",status:"running",currentIteration:0,maxTurns:(Dn=w.maxTurns)!=null?Dn:1,startedAt:X(w.startedAt)});else if(st==="turn_start"){let j=typeof w.iteration=="number"?w.iteration:we;if(j!==we){if(Qe&&(Qe.currentIteration=j),_e==="separate"&&j>1){let q=m;q&&(q.streaming=!1,g(q),Te.set(j-1,q),m=null)}we=j}Ye=typeof w.id=="string"?w.id:null,x=null}else if(st==="tool_input_delta"){let j=(wr=w.toolCallId)!=null?wr:_.lastId;if(j){let q=L.get(j);q!=null&&q.toolCall&&(q.toolCall.chunks=(mt=q.toolCall.chunks)!=null?mt:[],q.toolCall.chunks.push((sn=w.delta)!=null?sn:""),g(q))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let j=w.stopReason,q=m!=null?m:x;if(j&&q!==null){let J=w.id;(!J||((an=q.agentMetadata)==null?void 0:an.turnId)===J)&&(q.stopReason=j,g(q))}Ye===w.id&&(Ye=null)}else if(st==="media_start"){let j=String(w.id);je.set(j,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let j=je.get(String(w.id));j&&typeof w.delta=="string"&&j.parts.push(w.delta)}else if(st==="media_complete"){let j=String(w.id),q=je.get(j);je.delete(j);let J=(xs=(Cr=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Cr:q==null?void 0:q.mediaType)!=null?xs:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,gt=null;if(fe)gt={type:"media",data:fe,mediaType:J};else if(Oe){let mn=J.toLowerCase();gt={type:mn==="image"||mn.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:J}}let It=(Fr=w.toolCallId)!=null?Fr:q==null?void 0:q.toolCallId,Vn=gt?[gt]:[],kr=[];for(let mn of Vn){if(!mn||typeof mn!="object")continue;let Zt=mn,no=typeof Zt.type=="string"?Zt.type:void 0,ro=typeof Zt.mediaType=="string"?Zt.mediaType.toLowerCase():"",In=null,Wn="";if(no==="media"){let wn=typeof Zt.data=="string"?Zt.data:void 0;if(!wn)continue;Wn=ro.length>0?ro:"application/octet-stream",In=`data:${Wn};base64,${wn}`}else if(no==="image-url"){let wn=typeof Zt.url=="string"?Zt.url:void 0;if(!wn)continue;Wn=ro,In=wn}else if(no==="file-url"){let wn=typeof Zt.url=="string"?Zt.url:void 0;if(!wn)continue;Wn=ro,In=wn}else continue;if(In)if(no==="image-url"||Wn.startsWith("image/"))kr.push({type:"image",image:In,...Wn.includes("/")?{mimeType:Wn}:{}});else if(Wn.startsWith("audio/"))kr.push({type:"audio",audio:In,mimeType:Wn});else if(Wn.startsWith("video/"))kr.push({type:"video",video:In,mimeType:Wn});else{let wn=Wn||"application/octet-stream";kr.push({type:"file",data:In,mimeType:wn,filename:Lf(wn)})}}if(kr.length>0){let mn=c(),Zt=It,ro={id:`agent-media-${typeof Zt=="string"&&Zt.length>0?`${Zt}-${mn}`:String(mn)}`,role:"assistant",content:"",contentParts:kr,createdAt:new Date().toISOString(),streaming:!1,sequence:mn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(ro);let In=m;In&&(In.streaming=!1,g(In)),m=null,v.current=null}}else if(st==="execution_complete"){let j=(wo=w.kind)!=null?wo:Se;j==="agent"&&Qe&&(Qe.status=w.success?"complete":"error",Qe.completedAt=X(w.completedAt),Qe.stopReason=w.stopReason);let q=m;q&&(j==="flow"&&q.streaming!==!1?tt(q):(q.streaming=!1,g(q)),m=null),R=null,T="",wt=null,n({type:"status",status:"idle"})}else if(st==="execution_error"){let j=typeof w.error=="string"?w.error:(z=(Ar=w.error)==null?void 0:Ar.message)!=null?z:"Execution error";n({type:"error",error:new Error(j)})}else if(st!=="ping"){if(st==="approval_start"){let j=(zo=w.approvalId)!=null?zo:`approval-${c()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(Sr=Qe==null?void 0:Qe.agentId)!=null?Sr:"virtual",executionId:(Or=(Tr=w.executionId)!=null?Tr:Qe==null?void 0:Qe.executionId)!=null?Or:"",toolName:(Er=w.toolName)!=null?Er:"",toolType:w.toolType,description:(qo=w.description)!=null?qo:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let j=(la=w.approvalId)!=null?la:`approval-${c()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:"pending",agentId:(qn=Qe==null?void 0:Qe.agentId)!=null?qn:"virtual",executionId:(pr=(jn=w.executionId)!=null?jn:Qe==null?void 0:Qe.executionId)!=null?pr:"",toolName:(ur=w.toolName)!=null?ur:"",toolType:w.toolType,description:(_r=w.description)!=null?_r:`Execute ${(Co=w.toolName)!=null?Co:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(st==="approval_complete"){let j=w.approvalId;if(j){let J={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:j,status:(xn=w.decision)!=null?xn:"approved",agentId:(Mr=Qe==null?void 0:Qe.agentId)!=null?Mr:"virtual",executionId:(Ao=(jo=w.executionId)!=null?jo:Qe==null?void 0:Qe.executionId)!=null?Ao:"",toolName:(Vo=w.toolName)!=null?Vo:"",description:(ca=w.description)!=null?ca:"",resolvedAt:Date.now()}};g(J)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let j=w.artifactType,q=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:j,title:J,component:typeof w.component=="string"?w.component:void 0}),de.set(q,{markdown:"",title:J}),!oe.has(q)){oe.add(q);let fe={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:J,artifactType:j,status:"streaming"}})};re.set(q,fe),g(fe)}}else if(st==="artifact_delta"){let j=String(w.id),q=typeof w.delta=="string"?w.delta:String((Ko=w.delta)!=null?Ko:"");n({type:"artifact_delta",id:j,artDelta:q});let J=de.get(j);J&&(J.markdown+=q)}else if(st==="artifact_update"){let j=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:j,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let j=String(w.id);n({type:"artifact_complete",id:j});let q=re.get(j);if(q){q.streaming=!1;try{let J=JSON.parse((da=q.rawContent)!=null?da:"{}");if(J.props){J.props.status="complete";let fe=de.get(j);fe!=null&&fe.markdown&&(J.props.markdown=fe.markdown)}q.rawContent=JSON.stringify(J)}catch{}de.delete(j),g(q),re.delete(j)}}}else if(st==="transcript_insert"){let j=w.message;if(!j||typeof j!="object")continue;let q=String((Go=j.id)!=null?Go:`msg-${c()}`),J=j.role,Oe={id:q,role:J==="user"?"user":J==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:c()};if(g(Oe),Oe.rawContent)try{let gt=JSON.parse(Oe.rawContent),It=(pt=gt==null?void 0:gt.props)==null?void 0:pt.artifactId;typeof It=="string"&&oe.add(It)}catch{}m=null,v.current=null,Y.delete(q),ie.delete(q)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let j=typeof w.error=="string"?w.error:((ws=w.error)==null?void 0:ws.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(j)});let q=m;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let j=null;if(w.error instanceof Error)j=w.error;else if(st==="dispatch_error"){let q=(tr=w.message)!=null?tr:w.error;q!=null&&q!==""&&(j=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?j=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(j=new Error(String((Nn=q.message)!=null?Nn:q)))}if(j){n({type:"error",error:j});let q=m;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}Q.length=0};;){let{done:B,value:K}=await o.read();if(B)break;a+=s.decode(K,{stream:!0});let ue=a.split(`
|
|
10
12
|
|
|
11
|
-
`);a=(
|
|
12
|
-
`),Ze="message",Ge="";for(let q of He)q.startsWith("event:")?Ze=q.replace("event:","").trim():q.startsWith("data:")&&(Ge+=q.replace("data:","").trim());if(!Ge)continue;let ut;try{ut=JSON.parse(Ge)}catch(q){t({type:"error",error:q instanceof Error?q:new Error("Failed to parse chat stream payload")});continue}let Wt=Ze!=="message"?Ze:(hn=ut.type)!=null?hn:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,Wt,ut),this.parseSSEEvent){x.current=u;let q=await this.handleCustomSSEEvent(ut,t,x,g,c,I);if(x.current&&x.current!==u&&(u=x.current),q)continue}J.push({payloadType:Wt,payload:ut}),ce()}}ce()}};function Ta(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function Ns(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Ma="[Image]";function Pi(n){return{type:"text",text:n}}var yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],hf=["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"],Ur=[...yu,...hf];function yf(n){return yu.includes(n)||n.startsWith("image/")}function Ea(n){return yf(n.type)}async function bu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ea(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function vu(n,e=Ur,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function bf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function xu(n,e){let t=bf(e).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"}[n]||t||"FILE"}Ii();var wu=16e3,vf=24e3,xf=4096,wf=1380533830;function Cf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===wf?new Uint8Array(n,44):new Uint8Array(n)}function Af(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Fs=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:wu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let m=window.AudioContext||window.webkitAudioContext,f=new m({sampleRate:wu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new os(vf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${Af(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(u,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let I=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${I}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(xf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let m=0;m<d.length;m++){let f=Math.max(-1,Math.min(1,d[m]));c[m]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Cf(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Io=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ss(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Fs(n.runtype);case"browser":if(!Io.isSupported())throw new Error("Browser speech recognition not supported");return new Io(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Cu(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ss({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ss({type:"runtype",runtype:n.runtype});if(Io.isSupported())return ss({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Wi(n){try{return Cu(n),!0}catch{return!1}}function ka(n){var t;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var as=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ka(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,m;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(m=t.onError)==null||m.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Os=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function Ri(n){if(!n)return"";let e=Sf(n);return Au(e!==null?e:n)}function Sf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Au(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);a=(Ft=ue.pop())!=null?Ft:"";for(let Be of ue){let $e=Be.split(`
|
|
14
|
+
`),De="message",Le="";for(let yt of $e)yt.startsWith("event:")?De=yt.replace("event:","").trim():yt.startsWith("data:")&&(Le+=yt.replace("data:","").trim());if(!Le)continue;let it;try{it=JSON.parse(Le)}catch(yt){n({type:"error",error:yt instanceof Error?yt:new Error("Failed to parse chat stream payload")});continue}let Wt=De!=="message"?De:(Yt=it.type)!=null?Yt:"message";if((Rr=this.onSSEEvent)==null||Rr.call(this,Wt,it),this.parseSSEEvent){v.current=m;let yt=await this.handleCustomSSEEvent(it,n,v,g,c,M);if(v.current&&v.current!==m&&(m=v.current),yt)continue}Q.push({payloadType:Wt,payload:it}),Ve()}}Ve()}};function ka(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Us(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var La="[Image]";function Wi(t){return{type:"text",text:t}}var Su=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Wf=["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"],jr=[...Su,...Wf];function Rf(t){return Su.includes(t)||t.startsWith("image/")}function Pa(t){return Rf(t.type)}async function Tu(t){return new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Pa(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)})}function Eu(t,e=jr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Hf(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Mu(t,e){let n=Hf(e).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"}[t]||n||"FILE"}Ri();var ku=16e3,Bf=24e3,Df=4096,Nf=1380533830;function Ff(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Nf?new Uint8Array(t,44):new Uint8Array(t)}function Of(t){var r;let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var zs=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:ku,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,f=new u({sampleRate:ku});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new cs(Bf);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),f.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Of(r)}/ws/agents/${encodeURIComponent(e)}/voice`,x=new WebSocket(m,["runtype.bearer",n]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,c,x,o))},x.onmessage=v=>this.handleMessage(v,o),x.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let M=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${M}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,r,o){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Df,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let f=Math.max(-1,Math.min(1,d[u]));c[u]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){var o,s;if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let r=Ff(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,r){this.transcriptCallbacks.forEach(o=>o(e,n,r))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Ho=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ds(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(t.runtype);case"browser":if(!Ho.isSupported())throw new Error("Browser speech recognition not supported");return new Ho(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;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: ${t.type}`)}}function Lu(t){if((t==null?void 0:t.type)==="custom"&&t.custom)return ds({type:"custom",custom:t.custom});if((t==null?void 0:t.type)==="runtype"&&t.runtype)return ds({type:"runtype",runtype:t.runtype});if(Ho.isSupported())return ds({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Hi(t){try{return Lu(t),!0}catch{return!1}}function Ia(t){var n;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=t.find(s=>s.name===r);if(o)return o}return(n=t.find(r=>r.lang.startsWith("en")))!=null?n:t[0]}var ps=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,n){var a;if(!t.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(u=n.onError)==null||u.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var qs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,n;return(n=(e=this.engine)==null?void 0:e.supportsPause)!=null?n:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,n;this.stop(),(n=(e=this.engine)==null?void 0:e.destroy)==null||n.call(e),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Bi(t){if(!t)return"";let e=_f(t);return Pu(e!==null?e:t)}function _f(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Pu(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
15
|
`),e=e.replace(/\n{2,}/g,`
|
|
14
|
-
`),e.trim()}var
|
|
16
|
+
`),e.trim()}var Bu=null;var Di=()=>Bu?Bu():Promise.resolve().then(()=>(Hu(),Ru));var zf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function qf(t,e){return zf.some(n=>t[n]!==e[n])}function Du(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
15
17
|
|
|
16
|
-
_Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]}),Pu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Iu=n=>Jo(n)||n===$r,Ia=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Os(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,m,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,u=!!(g!=null&&g.name)&&(Jo(g.name)||g.name===$r&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&u&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(m=this.callbacks).onError)==null||f.call(m,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ds(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!t||!r||!this.config.clientToken||Hi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Wi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=as.isSupported()?new as({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,m=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&m)return Hi().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:u})=>{let v=new g({host:d,agentId:c,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&t?new u(v,t,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&t)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ss(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let m=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=m.id}if(c){this.pendingVoiceUserMessageId=null;let m=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=m.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let m=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=m.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,m,f;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((m=e.browser)==null?void 0:m.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!kf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Ds(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:m,rawContent:f}=e,u={id:a!=null?a:t==="user"?Ta():t==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...m!==void 0&&{voiceProcessing:m},...f!==void 0&&{rawContent:f}};return this.upsertMessage(u),u}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:m,streaming:f=!1,voiceProcessing:g,rawContent:u}=r,x={id:d!=null?d:o==="user"?Ta():o==="assistant"?Ns():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:m!=null?m:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...u!==void 0&&{rawContent:u}};t.push(x)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,m,f,g,u;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Ta(),s=Ns(),a={id:o,role:"user",content:r||Ma,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let I=Lu(v,this.config.errorMessage);if(I){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:I,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(m=this.callbacks).onError)==null||f.call(m,v):(u=(g=this.callbacks).onError)==null||u.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Ns();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){let m=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!m){let f=Lu(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,m||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var o,s,a;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var m,f,g,u,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(m=a==null?void 0:a.createdAt)!=null?m:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(c?x=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):x=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),x){let I=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((g=M==null?void 0:M.error)!=null?g:`Approval request failed: ${x.status}`)}I=x.body}else x instanceof ReadableStream&&(I=x);I?await this.connectStream(I,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let I=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(v=(u=this.callbacks).onError)==null||v.call(u,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var m,f,g,u,v,x,I,M,E,F,L,R;let r=this.messages.find(A=>A.id===e.id);if(((m=r==null?void 0:r.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(v=(u=this.callbacks).onError)==null||v.call(u,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let A=(x=e.toolCall)==null?void 0:x.args,W=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(W.length===1){let N=typeof((I=W[0])==null?void 0:I.question)=="string"?W[0].question:"";N&&(a={[N]:t})}}this.markAskUserQuestionResolved(e,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(E=e.toolCall)==null?void 0:E.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof t=="string"?t:Object.entries(t).map(([W,N])=>`${W}: ${Array.isArray(N)?N.join(", "):N}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((W,N)=>{let D=typeof(W==null?void 0:W.question)=="string"?W.question:"";if(!D)return;let k=A[D],j=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:D,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:j||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:t});if(!A.ok){let W=await A.json().catch(()=>null);throw new Error((F=W==null?void 0:W.error)!=null?F:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let W=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,W||(R=(L=this.callbacks).onError)==null||R.call(L,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==$r)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,m,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async g=>{var R,A,W,N,D,k,j;let u=(R=g.toolCall)==null?void 0:R.name,v=(A=g.toolCall)==null?void 0:A.id;if(!u||!v)return null;let x=`${e}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let I=this.markWebMcpToolRunning(g),M=(N=(W=g.agentMetadata)==null?void 0:W.webMcpToolCallId)!=null?N:u;if(u===$r)return{dedupeKey:x,resumeKey:M,output:Ti(),toolMessage:g,startedAt:I,completedAt:Date.now()};let E=new AbortController;this.webMcpResolveControllers.add(E),o.push(E);let F=this.client.executeWebMcpToolCall(u,(D=g.toolCall)==null?void 0:D.args,E.signal),L;if(!F)L={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{L=await F}catch(V){let ne=V instanceof Error&&(V.name==="AbortError"||V.message.includes("aborted")||V.message.includes("abort"));return ne||(j=(k=this.callbacks).onError)==null||j.call(k,V instanceof Error?V:new Error(String(V))),this.markWebMcpToolComplete(g,_s(ne?"Aborted by cancel()":Pu(V)),I),this.webMcpInflightKeys.delete(x),null}return E.signal.aborted?(this.markWebMcpToolComplete(g,_s("Aborted by cancel()"),I),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:M,output:L,toolMessage:g,startedAt:I,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let u=await this.client.resumeFlow(e,g,{signal:s.signal});if(!u.ok){let v=await u.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${u.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===$r?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(m=this.callbacks).onError)==null||f.call(m,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,_s("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,x,I,M,E,F,L,R,A,W,N,D;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(x=e.toolCall)==null?void 0:x.name,o=(I=e.toolCall)==null?void 0:I.id;if(!t){(E=(M=this.callbacks).onError)==null||E.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(j){(L=(F=this.callbacks).onError)==null||L.call(F,j instanceof Error?j:new Error(String(j)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===$r,m=(R=e.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,m,d),g="execute",u=a;try{let k;if(c?k=Ti():f?k=await f:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},u=Date.now(),d.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),a);return}let j=(W=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?W:r;g="resume",await this.resumeWithToolOutput(t,j,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,k,a,u,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let j=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(g==="execute"||j||d.aborted)&&this.markWebMcpToolComplete(e,_s(j||d.aborted?"Aborted by cancel()":Pu(k)),a),j||(D=(N=this.callbacks).onError)==null||D.call(N,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Ri(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ka(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Ri(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N;if(s!==r)return o;let a={...o,...t};if(((m=o.agentMetadata)==null?void 0:m.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let D=o.approval,k=t.approval;a.approval={...D,...k,executionId:k.executionId||D.executionId,toolName:k.toolName||D.toolName,description:k.description||D.description,toolType:(u=k.toolType)!=null?u:D.toolType,reason:(v=k.reason)!=null?v:D.reason,parameters:(x=k.parameters)!=null?x:D.parameters}}let i=(I=t.toolCall)==null?void 0:I.name,d=(M=t.agentMetadata)==null?void 0:M.executionId,c=(E=t.toolCall)==null?void 0:E.id;if(i&&Iu(i)&&d&&c&&((F=t.agentMetadata)==null?void 0:F.awaitingLocalTool)===!0){let D=`${d}:${c}`,k=this.webMcpInflightKeys.has(D),j=this.webMcpResolvedKeys.has(D),V=(L=o.toolCall)==null?void 0:L.name,ne=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&V!==void 0&&Iu(V)&&((W=o.toolCall)==null?void 0:W.status)==="complete";(k||j||ne)&&(a.agentMetadata={...(N=a.agentMetadata)!=null?N:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var C=require("lucide"),Lf={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},Ae=(n,e=24,t="currentColor",r=2)=>{let o=Lf[n];return o?Pf(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Pf(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,m])=>{c!=="stroke"&&d.setAttribute(c,String(m))}),o.appendChild(d)}),o}var Wa={allowedTypes:Ur,maxFileSize:10*1024*1024,maxFiles:4};function If(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Wf(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var $s=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Wa.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Wa.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Wa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Wa.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let m=vu(c,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let f=(o=m.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await bu(c),g=Ea(c)?URL.createObjectURL(c):null,u={id:If(),file:c,previewUrl:g,contentPart:f};this.attachments.push(u),this.renderPreview(u)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Ea(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=b("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=Wf(e.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=xu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=Ae("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Wu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Us(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Wu(s)&&Wu(o)?t[r]=Us(s,o):t[r]=o}return t}var qr="min(440px, calc(100vw - 24px))",Hu="440px",Rf={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:qr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Rf,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Ru(n,e){if(!(!n&&!e))return n?e?Us(n,e):n:e}function Bu(n){var e,t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R;return n?{...Nt,...n,theme:Ru(Nt.theme,n.theme),darkTheme:Ru(Nt.darkTheme,n.darkTheme),launcher:{...Nt.launcher,...n.launcher,dock:{...(e=Nt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Nt.copy,...n.copy},sendButton:{...Nt.sendButton,...n.sendButton},statusIndicator:{...Nt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,X,ie,he,oe,K,te,qe,Y,le;let A=(re=Nt.features)==null?void 0:re.artifacts,W=(X=n.features)==null?void 0:X.artifacts,N=(ie=Nt.features)==null?void 0:ie.scrollToBottom,D=(he=n.features)==null?void 0:he.scrollToBottom,k=(oe=Nt.features)==null?void 0:oe.scrollBehavior,j=(K=n.features)==null?void 0:K.scrollBehavior,V=(te=Nt.features)==null?void 0:te.streamAnimation,ne=(qe=n.features)==null?void 0:qe.streamAnimation,Re=(Y=Nt.features)==null?void 0:Y.askUserQuestion,Ue=(le=n.features)==null?void 0:le.askUserQuestion,xe=A===void 0&&W===void 0?void 0:{...A,...W,layout:{...A==null?void 0:A.layout,...W==null?void 0:W.layout}},Ie=N===void 0&&D===void 0?void 0:{...N,...D},_e=k===void 0&&j===void 0?void 0:{...k,...j},Se=V===void 0&&ne===void 0?void 0:{...V,...ne},ve=Re===void 0&&Ue===void 0?void 0:{...Re,...Ue,styles:{...Re==null?void 0:Re.styles,...Ue==null?void 0:Ue.styles}};return{...Nt.features,...n.features,...Ie!==void 0?{scrollToBottom:Ie}:{},..._e!==void 0?{scrollBehavior:_e}:{},...xe!==void 0?{artifacts:xe}:{},...Se!==void 0?{streamAnimation:Se}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Nt.layout,...n.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(m=Nt.layout)==null?void 0:m.messages)==null?void 0:f.avatar,...(u=(g=n.layout)==null?void 0:g.messages)==null?void 0:u.avatar},timestamp:{...(x=(v=Nt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(I=n.layout)==null?void 0:I.messages)==null?void 0:M.timestamp}},slots:{...(E=Nt.layout)==null?void 0:E.slots,...(F=n.layout)==null?void 0:F.slots}},markdown:{...Nt.markdown,...n.markdown,options:{...(L=Nt.markdown)==null?void 0:L.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...Nt.messageActions,...n.messageActions}}:Nt}var Hf={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"}},Bf={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"}},Df={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:qr,maxWidth:Hu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function is(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?is(n,r):r}function Du(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=is(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Nf(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Nu(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Nu(s,o):t[r]=o}return t}function Ff(n,e){return e?Nu(n,e):n}function Wo(n,e={}){var o,s,a,i,d,c,m,f,g,u,v,x,I;let t={palette:Hf,semantic:Bf,components:Df},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(m=n==null?void 0:n.semantic)==null?void 0:m.colors,interactive:{...t.semantic.colors.interactive,...(g=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...t.semantic.colors.feedback,...(v=(u=n==null?void 0:n.semantic)==null?void 0:u.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...t.semantic.typography,...(I=n==null?void 0:n.semantic)==null?void 0:I.typography}},components:Ff(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let M=Nf(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let M of e.plugins)r=M.transform(r);return r}function Fu(n){var x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe,J,ce,we,je,Pt,Te,me,fn,It,rn,hr,hn,Ve,T,ue,Le,Me,He,Ze,Ge,ut,Wt,q,ot,G,de,ke,vt,Yt,Zt,pn,Ht,et,Rt,ct,Kt,Jn,An,en,In,yr,xt,Nn,br,Pr,ir,yt,uo,vr,mo,Wn,No,jr,Ir,Vr,Kr,go,fo,Gr,Ct,Fn,On,Sn,St,Yn,Zn,_n,Qr,Wr,Xr,$n,Bt,Tn,er,Jr,Rr,Yr,xr,Un;let e=Du(n),t={};for(let[ye,dt]of Object.entries(e)){let Qt=ye.replace(/\./g,"-");t[`--persona-${Qt}`]=dt.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(I=t["--persona-semantic-colors-secondary"])!=null?I:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(M=t["--persona-semantic-colors-accent"])!=null?M:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(E=t["--persona-semantic-colors-surface"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(F=t["--persona-semantic-colors-background"])!=null?F:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(L=t["--persona-semantic-colors-container"])!=null?L:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(R=t["--persona-semantic-colors-text"])!=null?R:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(A=t["--persona-semantic-colors-text-muted"])!=null?A:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(N=t["--persona-semantic-colors-border"])!=null?N:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(D=t["--persona-semantic-colors-divider"])!=null?D:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(k=t["--persona-components-voice-recording-indicator"])!=null?k:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(j=t["--persona-components-voice-recording-background"])!=null?j:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(V=t["--persona-components-voice-processing-icon"])!=null?V:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Re=t["--persona-components-approval-requested-background"])!=null?Re:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Ue=t["--persona-components-approval-requested-border"])!=null?Ue:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(xe=t["--persona-components-approval-requested-text"])!=null?xe:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Ie=t["--persona-components-approval-requested-shadow"])!=null?Ie:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-approval-approve-bg"]=(_e=t["--persona-components-approval-approve-background"])!=null?_e:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Se=t["--persona-components-approval-deny-background"])!=null?Se:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ve=t["--persona-components-attachment-image-background"])!=null?ve:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(X=t["--persona-semantic-typography-fontFamily"])!=null?X:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ie=t["--persona-semantic-typography-fontSize"])!=null?ie:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(he=t["--persona-semantic-typography-fontWeight"])!=null?he:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(oe=t["--persona-semantic-typography-lineHeight"])!=null?oe:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(te=t["--persona-palette-radius-md"])!=null?te:"0.375rem",t["--persona-radius-lg"]=(qe=t["--persona-palette-radius-lg"])!=null?qe:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(it=(Pe=t["--persona-components-launcher-borderRadius"])!=null?Pe:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-launcher-bg"]=(lt=t["--persona-components-launcher-background"])!=null?lt:t["--persona-primary"],t["--persona-launcher-fg"]=(rt=t["--persona-components-launcher-foreground"])!=null?rt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(Ee=t["--persona-components-launcher-border"])!=null?Ee:t["--persona-border"],t["--persona-button-primary-bg"]=(pe=t["--persona-components-button-primary-background"])!=null?pe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Xe=t["--persona-components-button-primary-foreground"])!=null?Xe:t["--persona-text-inverse"],t["--persona-button-radius"]=(ce=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?ce:"9999px",t["--persona-panel-radius"]=(je=(we=t["--persona-components-panel-borderRadius"])!=null?we:t["--persona-radius-xl"])!=null?je:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(me=(Te=t["--persona-components-panel-shadow"])!=null?Te:t["--persona-palette-shadows-xl"])!=null?me:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(fn=t["--persona-components-launcher-shadow"])!=null?fn:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(rn=(It=t["--persona-components-input-borderRadius"])!=null?It:t["--persona-radius-lg"])!=null?rn:"0.5rem",t["--persona-message-user-radius"]=(hn=(hr=t["--persona-components-message-user-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?hn:"0.5rem",t["--persona-message-assistant-radius"]=(T=(Ve=t["--persona-components-message-assistant-borderRadius"])!=null?Ve:t["--persona-radius-lg"])!=null?T:"0.5rem",t["--persona-header-bg"]=(ue=t["--persona-components-header-background"])!=null?ue:t["--persona-surface"],t["--persona-header-border"]=(Le=t["--persona-components-header-border"])!=null?Le:t["--persona-divider"],t["--persona-header-icon-bg"]=(Me=t["--persona-components-header-iconBackground"])!=null?Me:t["--persona-primary"],t["--persona-header-icon-fg"]=(He=t["--persona-components-header-iconForeground"])!=null?He:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ze=t["--persona-components-header-titleForeground"])!=null?Ze:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Ge=t["--persona-components-header-subtitleForeground"])!=null?Ge:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ut=t["--persona-components-header-actionIconForeground"])!=null?ut:t["--persona-muted"];let r=(Wt=n.components)==null?void 0:Wt.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(q=n.components)==null?void 0:q.introCard;t["--persona-intro-card-bg"]=(ot=t["--persona-components-introCard-background"])!=null?ot:t["--persona-surface"],t["--persona-intro-card-radius"]=(G=t["--persona-components-introCard-borderRadius"])!=null?G:"1rem",t["--persona-intro-card-padding"]=(de=t["--persona-components-introCard-padding"])!=null?de:"1.5rem",t["--persona-intro-card-shadow"]=(vt=(ke=o==null?void 0:o.shadow)!=null?ke:t["--persona-components-introCard-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Yt=t["--persona-components-input-background"])!=null?Yt:t["--persona-surface"],t["--persona-input-placeholder"]=(Zt=t["--persona-components-input-placeholder"])!=null?Zt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(pn=t["--persona-components-message-user-background"])!=null?pn:t["--persona-accent"],t["--persona-message-user-text"]=(Ht=t["--persona-components-message-user-text"])!=null?Ht:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(et=t["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Rt=t["--persona-components-message-assistant-background"])!=null?Rt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ct=t["--persona-components-message-assistant-text"])!=null?ct:t["--persona-text"],t["--persona-message-assistant-border"]=(Kt=t["--persona-components-message-assistant-border"])!=null?Kt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Jn=t["--persona-components-message-assistant-shadow"])!=null?Jn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(en=(An=t["--persona-components-scrollToBottom-background"])!=null?An:t["--persona-button-primary-bg"])!=null?en:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(yr=(In=t["--persona-components-scrollToBottom-foreground"])!=null?In:t["--persona-button-primary-fg"])!=null?yr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(xt=t["--persona-components-scrollToBottom-border"])!=null?xt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Nn=t["--persona-components-scrollToBottom-size"])!=null?Nn:"40px",t["--persona-scroll-to-bottom-radius"]=(ir=(Pr=(br=t["--persona-components-scrollToBottom-borderRadius"])!=null?br:t["--persona-button-radius"])!=null?Pr:t["--persona-radius-full"])!=null?ir:"9999px",t["--persona-scroll-to-bottom-shadow"]=(uo=(yt=t["--persona-components-scrollToBottom-shadow"])!=null?yt:t["--persona-palette-shadows-sm"])!=null?uo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(mo=t["--persona-components-scrollToBottom-gap"])!=null?mo:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(No=(Wn=t["--persona-components-scrollToBottom-fontSize"])!=null?Wn:t["--persona-palette-typography-fontSize-sm"])!=null?No:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(jr=t["--persona-components-scrollToBottom-iconSize"])!=null?jr:"14px",t["--persona-tool-bubble-shadow"]=(Ir=t["--persona-components-toolBubble-shadow"])!=null?Ir:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Vr=t["--persona-components-reasoningBubble-shadow"])!=null?Vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Kr=t["--persona-components-composer-shadow"])!=null?Kr:"none",t["--persona-md-inline-code-bg"]=(go=t["--persona-components-markdown-inlineCode-background"])!=null?go:t["--persona-container"],t["--persona-md-inline-code-color"]=(fo=t["--persona-components-markdown-inlineCode-foreground"])!=null?fo:t["--persona-text"],t["--persona-md-link-color"]=(Ct=(Gr=t["--persona-components-markdown-link-foreground"])!=null?Gr:t["--persona-accent"])!=null?Ct:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Fn=t["--persona-components-markdown-codeBlock-background"])!=null?Fn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(On=t["--persona-components-markdown-codeBlock-borderColor"])!=null?On:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Sn=t["--persona-components-markdown-codeBlock-textColor"])!=null?Sn:"inherit",t["--persona-md-table-header-bg"]=(St=t["--persona-components-markdown-table-headerBackground"])!=null?St:t["--persona-container"],t["--persona-md-table-border-color"]=(Yn=t["--persona-components-markdown-table-borderColor"])!=null?Yn:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(_n=t["--persona-components-markdown-blockquote-borderColor"])!=null?_n:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Qr=t["--persona-components-markdown-blockquote-background"])!=null?Qr:"transparent",t["--persona-md-blockquote-text-color"]=(Wr=t["--persona-components-markdown-blockquote-textColor"])!=null?Wr:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Xr=t["--persona-components-collapsibleWidget-container"])!=null?Xr:t["--persona-surface"],t["--cw-surface"]=($n=t["--persona-components-collapsibleWidget-surface"])!=null?$n:t["--persona-surface"],t["--cw-border"]=(Bt=t["--persona-components-collapsibleWidget-border"])!=null?Bt:t["--persona-border"],t["--persona-message-border"]=(Tn=t["--persona-components-message-border"])!=null?Tn:t["--persona-border"];let m=n.components,f=m==null?void 0:m.iconButton;f&&(f.background&&(t["--persona-icon-btn-bg"]=f.background),f.border&&(t["--persona-icon-btn-border"]=f.border),f.color&&(t["--persona-icon-btn-color"]=f.color),f.padding&&(t["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(t["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(t["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(t["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(t["--persona-icon-btn-active-border"]=f.activeBorder));let g=m==null?void 0:m.labelButton;g&&(g.background&&(t["--persona-label-btn-bg"]=g.background),g.border&&(t["--persona-label-btn-border"]=g.border),g.color&&(t["--persona-label-btn-color"]=g.color),g.padding&&(t["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(t["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(t["--persona-label-btn-gap"]=g.gap));let u=m==null?void 0:m.toggleGroup;u&&(u.gap&&(t["--persona-toggle-group-gap"]=u.gap),u.borderRadius&&(t["--persona-toggle-group-radius"]=u.borderRadius));let v=m==null?void 0:m.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,t["--persona-dropdown-bg"]=(er=t["--persona-dropdown-bg"])!=null?er:ye.copyMenuBackground),ye.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,t["--persona-dropdown-border"]=(Jr=t["--persona-dropdown-border"])!=null?Jr:ye.copyMenuBorder),ye.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,t["--persona-dropdown-shadow"]=(Rr=t["--persona-dropdown-shadow"])!=null?Rr:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Yr=t["--persona-dropdown-radius"])!=null?Yr:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(xr=t["--persona-dropdown-item-hover-bg"])!=null?xr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(t["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(t["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(t["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(t["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(t["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(t["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let dt=(Un=is(n,ye.toolbarBackground))!=null?Un:ye.toolbarBackground;t["--persona-artifact-toolbar-bg"]=dt}}return t}var Of={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"}}},Ou=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Bi=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},_f=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Bi()},$f=n=>_f(n),Uf=n=>Wo(n),qf=n=>{var t;let e=Wo(void 0,{validate:!1});return Wo({...n,palette:{...e.palette,colors:{...Of.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ra=n=>{let e=$f(n),t=Ou(n==null?void 0:n.theme),r=Ou(n==null?void 0:n.darkTheme);return e==="dark"?qf(Us(t!=null?t:{},r!=null?r:{})):Uf(t)},zf=n=>Fu(n),ls=(n,e)=>{let t=Ra(e),r=zf(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},_u=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Bi())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Bi());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var $u=require("idiomorph"),Ha=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;$u.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Uu=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function qu(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ba}}}function zu(n,e){var t,r,o,s,a,i,d,c,m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re,X,ie;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(m=(c=n.llmContent)==null?void 0:c.length)!=null?m:0,(g=(f=n.approval)==null?void 0:f.status)!=null?g:"",(v=(u=n.toolCall)==null?void 0:u.status)!=null?v:"",(I=(x=n.toolCall)==null?void 0:x.name)!=null?I:"",(F=(E=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:E.length)!=null?F:0,(W=(A=(R=(L=n.toolCall)==null?void 0:L.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?W:"",typeof((N=n.toolCall)==null?void 0:N.args)=="string"?n.toolCall.args.length:(D=n.toolCall)!=null&&D.args?JSON.stringify(n.toolCall.args).length:0,(V=(j=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:j.length)!=null?V:0,(xe=(Ue=(Re=(ne=n.reasoning)==null?void 0:ne.chunks)==null?void 0:Re[n.reasoning.chunks.length-1])==null?void 0:Ue.length)!=null?xe:0,(ve=(Se=(_e=(Ie=n.reasoning)==null?void 0:Ie.chunks)==null?void 0:_e[n.reasoning.chunks.length-1])==null?void 0:Se.slice(-32))!=null?ve:"",(X=(re=n.contentParts)==null?void 0:re.length)!=null?X:0,(ie=n.stopReason)!=null?ie:"",e].join("\0")}function ju(){return new Map}function Vu(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Ku(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Gu(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Da(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function zr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Ro(n,e){return zr(n)-n.scrollTop<=e}function Na(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,m=t-r;return a||Math.abs(m)<s?{action:"none",delta:m,nextLastScrollTop:t}:!e&&o&&(!c||m>0)?{action:"resume",delta:m,nextLastScrollTop:t}:e&&i&&m<0?{action:"pause",delta:m,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:m,nextLastScrollTop:t}:{action:"none",delta:m,nextLastScrollTop:t}}function Fa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function Qu(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Xu(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Ju(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,co=wn+1;var qs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},jf=["pre","code","a","script","style"],Oa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:qs.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:qs.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:qs.speed,duration:(o=n==null?void 0:n.duration)!=null?o:qs.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:qs.buffer}},Vf=[{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"}],Zu=new Map;for(let n of Vf)Zu.set(n.name,n);var zs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Zu.get(n))!=null?r:null},_a=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
17
|
-
`);return s<0?"":n.slice(0,s)}return n},Kf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Gf=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Di=/\s/,Qf=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Xf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Di.test(s[i])){let c=i;for(;c<s.length&&Di.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let m=i;for(;m<s.length&&!Di.test(s[m]);)c.appendChild(Kf(r,s[m],e,t.value)),t.value+=1,m+=1;a.appendChild(c),i=m}o.replaceChild(a,n)},Jf=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Gf(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},js=(n,e,t,r)=>{var f,g;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:jf).map(u=>u.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Qf(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},m=e==="char"?Xf:Jf;for(let u of i)m(u,t,c);return o.innerHTML},$a=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Vs=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Yu=new WeakMap,Yf=(n,e)=>{var s;if(!n.styles)return;let t=Yu.get(e);if(t||(t=new Set,Yu.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Ni=new WeakMap,Zf=(n,e)=>{if(!n.onAttach)return;let t=Ni.get(e);if(t||(t=new Map,Ni.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},em=n=>{let e=Ni.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Fi=(n,e)=>{Yf(n,e),Zf(n,e)};function Oi(n,e=wn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var Ks=0,po=null;function _i(n=document){var t;if(Ks++,Ks===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;po={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,Ks=Math.max(0,Ks-1),Ks===0&&po)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=po.originalOverflow,o.style.position=po.originalPosition,o.style.top=po.originalTop,o.style.width=po.originalWidth,s.scrollTo(0,po.scrollY),po=null}}}var Gs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},gn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},Qs=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},gr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Gs.side,width:(o=e==null?void 0:e.width)!=null?o:Gs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Gs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Gs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Gs.maxHeight}};var fr={"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 eh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ua=(n,e={})=>{var I,M,E,F,L,R;let{showClose:t=!0,wrapperClassName:r=eh,buttonSize:o,iconSize:s="28px"}=e,a=(I=n==null?void 0:n.launcher)!=null?I:{},i=(M=o!=null?o:a.closeButtonSize)!=null?M:"32px",d=b("div",r),c=(E=a.closeButtonTooltipText)!=null?E:"Close chat",m=(F=a.closeButtonShowTooltip)!=null?F:!0,f=(L=a.closeButtonIconName)!=null?L:"x",g=(R=a.closeButtonIconText)!=null?R:"\xD7",u=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!u&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||Pn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:u?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=Ae(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),m&&c){let A=null,W=()=>{if(A)return;let D=v.ownerDocument,k=D.body;if(!k)return;A=Lr(D,"div","persona-clear-chat-tooltip"),A.textContent=c;let j=Lr(D,"div");j.className="persona-clear-chat-tooltip-arrow",A.appendChild(j);let V=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(co),A.style.left=`${V.left+V.width/2}px`,A.style.top=`${V.top-8}px`,A.style.transform="translate(-50%, -100%)",k.appendChild(A)},N=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",W),d.addEventListener("mouseleave",N),v.addEventListener("focus",W),v.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",W),d.removeEventListener("mouseleave",N),v.removeEventListener("focus",W),v.removeEventListener("blur",N)}}return{button:v,wrapper:d}},th="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qa=(n,e={})=>{var A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e;let{wrapperClassName:t=th,buttonSize:r,iconSize:o="20px"}=e,a=(W=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?W:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(D=a.iconName)!=null?D:"refresh-cw",c=(k=a.iconColor)!=null?k:"",m=(j=a.backgroundColor)!=null?j:"",f=(V=a.borderWidth)!=null?V:"",g=(ne=a.borderColor)!=null?ne:"",u=(Re=a.borderRadius)!=null?Re:"",v=(Ue=a.paddingX)!=null?Ue:"",x=(xe=a.paddingY)!=null?xe:"",I=(Ie=a.tooltipText)!=null?Ie:"Clear chat",M=(_e=a.showTooltip)!=null?_e:!0,E=b("div",t),F=!!(f||g),L=Mt("button",{className:Ls("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!m&&"hover:persona-bg-gray-100",!F&&"persona-border-none",!u&&"persona-rounded-full"),attrs:{type:"button","aria-label":I},style:{height:i,width:i,color:c||Pn.actionIconColor,backgroundColor:m||void 0,border:F?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:u||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Ae(d,o,"currentColor",1);if(R&&(R.style.display="block",L.appendChild(R)),E.appendChild(L),M&&I){let Se=null,ve=()=>{if(Se)return;let X=L.ownerDocument,ie=X.body;if(!ie)return;Se=Lr(X,"div","persona-clear-chat-tooltip"),Se.textContent=I;let he=Lr(X,"div");he.className="persona-clear-chat-tooltip-arrow",Se.appendChild(he);let oe=L.getBoundingClientRect();Se.style.position="fixed",Se.style.zIndex=String(co),Se.style.left=`${oe.left+oe.width/2}px`,Se.style.top=`${oe.top-8}px`,Se.style.transform="translate(-50%, -100%)",ie.appendChild(Se)},re=()=>{Se&&Se.parentNode&&(Se.parentNode.removeChild(Se),Se=null)};E.addEventListener("mouseenter",ve),E.addEventListener("mouseleave",re),L.addEventListener("focus",ve),L.addEventListener("blur",re),E._cleanupTooltip=()=>{re(),E.removeEventListener("mouseenter",ve),E.removeEventListener("mouseleave",re),L.removeEventListener("focus",ve),L.removeEventListener("blur",re)}}return{button:L,wrapper:E}};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))"},Ho=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve;let{config:e,showClose:t=!0}=n,r=Mt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(R=e==null?void 0:e.launcher)!=null?R:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(W=o.closeButtonPlacement)!=null?W:"inline",i=(N=o.headerIconHidden)!=null?N:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,X=Ae(d,re*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(k=(D=e==null?void 0:e.launcher)==null?void 0:D.agentIconText)!=null?k:"\u{1F4AC}"}else if((j=e==null?void 0:e.launcher)!=null&&j.iconUrl){let re=b("img");re.src=e.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(ne=(V=e==null?void 0:e.launcher)==null?void 0:V.agentIconText)!=null?ne:"\u{1F4AC}";let m=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Mt("span",{className:"persona-text-base persona-font-semibold",text:(Ue=(Re=e==null?void 0:e.launcher)==null?void 0:Re.title)!=null?Ue:"Chat Assistant",style:{color:Pn.titleColor}}),g=Mt("span",{className:"persona-text-xs",text:(Ie=(xe=e==null?void 0:e.launcher)==null?void 0:xe.subtitle)!=null?Ie:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});m.append(f,g),i?r.append(m):r.append(c,m);let u=(_e=o.clearChat)!=null?_e:{},v=(Se=u.enabled)!=null?Se:!0,x=(ve=u.placement)!=null?ve:"inline",I=null,M=null;if(v){let X=qa(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=X.button,M=X.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&r.appendChild(M)}let E=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:F,wrapper:L}=Ua(e,{showClose:t,wrapperClassName:E});return a!=="top-right"&&r.appendChild(L),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:F,closeButtonWrapper:L,clearChatButton:I,clearChatButtonWrapper:M}},Xs=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function cs(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("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(co)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let u of e){if(u.dividerBefore){let I=document.createElement("hr");a.appendChild(I)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",u.id),u.destructive&&v.setAttribute("data-destructive",""),u.icon){let I=Ae(u.icon,16,"currentColor",1.5);I&&v.appendChild(I)}let x=document.createElement("span");x.textContent=u.label,v.appendChild(x),v.addEventListener("click",I=>{I.stopPropagation(),m(),t(u.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let u=r.getBoundingClientRect();a.style.top=`${u.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-u.right}px`,a.style.left="auto"):(a.style.left=`${u.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let u=v=>{!a.contains(v.target)&&!r.contains(v.target)&&m()};document.addEventListener("click",u,!0),i=()=>document.removeEventListener("click",u,!0)})}function m(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():m()}function g(){m(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:m,toggle:f,destroy:g}}function Cn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=Ae(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[m,f]of Object.entries(i))d.setAttribute(m,f);return d}function $i(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let m=b("button",c);if(m.type="button",m.setAttribute("aria-label",t),e){let g=Ae(e,s!=null?s:14,"currentColor",2);g&&m.appendChild(g)}let f=b("span");if(f.textContent=t,m.appendChild(f),i&&m.addEventListener("click",i),d)for(let[g,u]of Object.entries(d))m.setAttribute(g,u);return m}function tm(n){var u,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let m=b("span","persona-combo-btn-label");m.textContent=e,c.appendChild(m);let f=Ae(t,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(u=d.borderRadius)!=null?u:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var x,I;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(I=d.border)!=null?I:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=cs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",x=>{x.stopPropagation();let I=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",I?"false":"true"),g.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{m.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var nh=n=>{var r;let e=Ho({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function rh(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Ae(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=cs({items:a.menuItems,onSelect:m=>t==null?void 0:t(m),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",m=>{m.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var oh=n=>{var E,F,L,R,A,W,N,D,k;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,m;if(d)c=tm({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,m=(L=c.querySelector(".persona-combo-btn-label"))!=null?L:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),m=b("span","persona-text-base persona-font-semibold persona-truncate"),m.style.color=Pn.titleColor,m.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(m),rh(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let V=o.onTitleClick;c.addEventListener("click",ne=>{ne.target.closest("button")||V()}),c.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),V())})}let j=o==null?void 0:o.titleRowHover;j&&(c.style.borderRadius=(W=j.borderRadius)!=null?W:"10px",c.style.padding=(N=j.padding)!=null?N:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var V,ne;c.style.backgroundColor=(V=j.background)!=null?V:"",c.style.borderColor=(ne=j.border)!=null?ne:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(D=a.closeButtonSize)!=null?D:"32px",g=b("div",""),u=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");u.style.height=f,u.style.width=f,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=t?"":"none",u.style.color=a.closeButtonColor||Pn.actionIconColor;let v=(k=a.closeButtonIconName)!=null?k:"x",x=Ae(v,"28px","currentColor",1);x?u.appendChild(x):u.textContent="\xD7",r&&u.addEventListener("click",r),g.appendChild(u),i.appendChild(g);let I=b("div");I.style.display="none";let M=b("span");return M.style.display="none",{header:i,iconHolder:I,headerTitle:m,headerSubtitle:M,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},nm={default:nh,minimal:oh},sh=n=>{var e;return(e=nm[n])!=null?e:nm.default},za=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),m=b("div");m.style.display="none";let f=b("span"),g=b("span"),u=b("button");u.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:m,headerTitle:f,headerSubtitle:g,closeButton:u,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=sh(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ja=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Va=n=>{var R,A,W,N,D,k,j,V,ne,Re,Ue,xe;let e=(R=n==null?void 0:n.sendButton)!=null?R:{},t=(A=e.useIcon)!=null?A:!1,r=(W=e.iconText)!=null?W:"\u2191",o=e.iconName,s=(N=e.stopIconName)!=null?N:"square",a=(D=e.tooltipText)!=null?D:"Send message",i=(k=e.stopTooltipText)!=null?k:"Stop generating",d=(V=(j=n==null?void 0:n.copy)==null?void 0:j.sendButtonLabel)!=null?V:"Send",c=(Re=(ne=n==null?void 0:n.copy)==null?void 0:ne.stopButtonLabel)!=null?Re:"Stop",m=(Ue=e.showTooltip)!=null?Ue:!1,f=(xe=e.size)!=null?xe:"40px",g=e.backgroundColor,u=e.textColor,v=b("div","persona-send-button-wrapper"),x=Mt("button",{className:Ls("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!g&&"persona-bg-persona-primary",!t&&!u&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?f:void 0,height:t?f:void 0,minWidth:t?f:void 0,minHeight:t?f:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?u||"var(--persona-button-primary-fg, #ffffff)":u||void 0,backgroundColor:t&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),I=null,M=null;if(t){let Ie=parseFloat(f)||24,_e=(u==null?void 0:u.trim())||"currentColor";o?(I=Ae(o,Ie,_e,2),I?x.appendChild(I):x.textContent=r):x.textContent=r,M=Ae(s,Ie,_e,2)}else x.textContent=d;let E=null;m&&a&&(E=b("div","persona-send-button-tooltip"),E.textContent=a,v.appendChild(E)),x.setAttribute("aria-label",a),v.appendChild(x);let F="send";return{button:x,wrapper:v,setMode:Ie=>{if(Ie===F)return;F=Ie;let _e=Ie==="stop"?i:a;if(x.setAttribute("aria-label",_e),E&&(E.textContent=_e),t){if(I&&M){let Se=Ie==="stop"?M:I;x.replaceChildren(Se)}}else x.textContent=Ie==="stop"?c:d}}},Ka=n=>{var E,F,L,R,A,W,N,D,k,j,V,ne;let e=(E=n==null?void 0:n.voiceRecognition)!=null?E:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((F=e.provider)==null?void 0:F.type)==="runtype";if(!(r||o))return null;let a=(R=(L=n==null?void 0:n.sendButton)==null?void 0:L.size)!=null?R:"40px",i=(A=e.iconName)!=null?A:"mic",d=(W=e.iconSize)!=null?W:a,c=parseFloat(d)||24,m=(D=e.backgroundColor)!=null?D:(N=n==null?void 0:n.sendButton)==null?void 0:N.backgroundColor,f=(j=e.iconColor)!=null?j:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,g=b("div","persona-send-button-wrapper"),u=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:m||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),x=Ae(i,c,f||"currentColor",1.5);x?u.appendChild(x):u.textContent="\u{1F3A4}",g.appendChild(u);let I=(V=e.tooltipText)!=null?V:"Start voice recognition";if(((ne=e.showTooltip)!=null?ne:!1)&&I){let Re=b("div","persona-send-button-tooltip");Re.textContent=I,g.appendChild(Re)}return{button:u,wrapper:g}},Ga=n=>{var v,x,I,M,E,F,L,R;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(I=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?I:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((M=e.allowedTypes)!=null?M:Ur).join(","),o.multiple=((E=e.maxFiles)!=null?E:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(F=e.buttonIconName)!=null?F:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),m=Mt("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":(L=e.buttonTooltipText)!=null?L:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});m.addEventListener("mouseenter",()=>{m.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),m.addEventListener("mouseleave",()=>{m.style.backgroundColor="transparent"});let f=Ae(s,d,"currentColor",1.5);f?m.appendChild(f):m.textContent="\u{1F4CE}",m.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(m);let g=(R=e.buttonTooltipText)!=null?R:"Attach file",u=b("div","persona-send-button-tooltip");return u.textContent=g,c.appendChild(u),{button:m,wrapper:c,input:o,previewsContainer:r}},Qa=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Xa=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ja=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ja(e);a();let i=Va(e),d=Ka(e),c=Ga(e),m=Qa(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),u=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&u.append(d.wrapper),u.append(i.wrapper),f.append(g,u),o.append(f),o.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,m),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:m,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:f,leftActions:g,rightActions:u,setSendButtonMode:i.setMode}};var rm=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=Ae("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=Ae("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},om=n=>{var v,x,I,M,E,F;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Xa();r.style.display="none";let o=Qa(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let i=Va(e),d=Ka(e),c=Ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let m=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),m.addEventListener("click",L=>{L.target!==i.button&&L.target!==i.wrapper&&L.target!==(d==null?void 0:d.button)&&L.target!==(d==null?void 0:d.wrapper)&&L.target!==(c==null?void 0:c.button)&&L.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&m.append(c.input),m.append(f,s,g),c&&t.append(c.previewsContainer),t.append(m,r,o);let u=m;return{footer:t,suggestions:r,composerForm:m,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(I=c==null?void 0:c.button)!=null?I:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(F=c==null?void 0:c.previewsContainer)!=null?F:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var sm=n=>{var m,f,g,u,v,x,I,M,E,F,L,R,A,W,N,D,k;let e=(f=(m=n==null?void 0:n.launcher)==null?void 0:m.enabled)!=null?f:!0,t=gn(n);if(Qs(n)){let j=(u=(g=n==null?void 0:n.launcher)==null?void 0:g.composerBar)!=null?u:{},V=b("div","persona-widget-wrapper persona-fixed persona-transition");V.setAttribute("data-persona-composer-bar",""),V.dataset.state="collapsed",V.dataset.expandedSize=(v=j.expandedSize)!=null?v:"anchored",V.style.zIndex=String((I=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?I:wn);let ne=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ne.style.width="100%",V.appendChild(ne);let Re=b("div","persona-widget-pill-root");return Re.setAttribute("data-persona-composer-bar",""),Re.dataset.state="collapsed",Re.dataset.expandedSize=(M=j.expandedSize)!=null?M:"anchored",Re.style.zIndex=String((F=(E=n==null?void 0:n.launcher)==null?void 0:E.zIndex)!=null?F:wn),{wrapper:V,panel:ne,pillRoot:Re}}if(t){let j=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),V=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return j.appendChild(V),{wrapper:j,panel:V}}if(!e){let j=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),V=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ne=(R=(L=n==null?void 0:n.launcher)==null?void 0:L.width)!=null?R:"100%";return j.style.width=ne,V.style.width="100%",j.appendChild(V),{wrapper:j,panel:V}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((N=(W=n==null?void 0:n.launcher)==null?void 0:W.zIndex)!=null?N:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(D=n==null?void 0:n.launcher)==null?void 0:D.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:qr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},ah=(n,e)=>{var L,R,A,W,N,D,k,j,V;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Ua(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(R=(L=n==null?void 0:n.launcher)==null?void 0:L.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let ne=qa(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ne.button,i=ne.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let m=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(W=n==null?void 0:n.copy)==null?void 0:W.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),f=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(D=n==null?void 0:n.copy)==null?void 0:D.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),g=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},m,f),u=b("div","persona-flex persona-flex-col persona-gap-3"),v=(j=n==null?void 0:n.layout)==null?void 0:j.contentMaxWidth;v&&(u.style.maxWidth=v,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((V=n==null?void 0:n.copy)==null?void 0:V.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,u);let I=Mt("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"}}),M=om({config:n}),{root:E,textNode:F}=rm();return t.append(d,o,c,I),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:u,composerOverlay:I,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,introTitle:m,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:M.footer,attachmentButton:M.attachmentButton,attachmentButtonWrapper:M.attachmentButtonWrapper,attachmentInput:M.attachmentInput,attachmentPreviewsContainer:M.attachmentPreviewsContainer,actionsRow:M.actionsRow,leftActions:M.leftActions,rightActions:M.rightActions,setSendButtonMode:M.setSendButtonMode,peekBanner:E,peekTextNode:F}},am=(n,e=!0)=>{var I,M,E,F,L,R,A,W,N;if(Qs(n))return ah(n,e);let t=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(I=n==null?void 0:n.layout)==null?void 0:I.header,o=((M=n==null?void 0:n.layout)==null?void 0:M.showHeader)!==!1,s=r?za(n,r,{showClose:e}):Ho({config:n,showClose:e}),a=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(E=n==null?void 0:n.copy)==null?void 0:E.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:gn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),m=b("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(m.style.maxWidth=f,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((W=n==null?void 0:n.copy)==null?void 0:W.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,m);let u=Ja({config:n}),v=((N=n==null?void 0:n.layout)==null?void 0:N.showFooter)!==!1;o?Xs(t,s,n):(s.header.style.display="none",Xs(t,s,n)),t.append(a);let x=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(u.footer.style.display="none"),t.append(u.footer),t.append(x),{container:t,body:a,messagesWrapper:m,composerOverlay:x,suggestions:u.suggestions,textarea:u.textarea,sendButton:u.sendButton,sendButtonWrapper:u.sendButtonWrapper,micButton:u.micButton,micButtonWrapper:u.micButtonWrapper,composerForm:u.composerForm,statusText:u.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:u.footer,attachmentButton:u.attachmentButton,attachmentButtonWrapper:u.attachmentButtonWrapper,attachmentInput:u.attachmentInput,attachmentPreviewsContainer:u.attachmentPreviewsContainer,actionsRow:u.actionsRow,leftActions:u.leftActions,rightActions:u.rightActions,setSendButtonMode:u.setSendButtonMode}};var Ui=(n,e)=>{let t=b("button");t.type="button",t.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]}),Nu=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Fu=t=>rs(t)||t===qr,Ha=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new qs(()=>this.createSpeechEngine());this.handleEvent=e=>{var n,r,o,s,a,i,d,c,u,f;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,m=!!(g!=null&&g.name)&&(rs(g.name)||g.name===qr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(u=this.callbacks).onError)==null||f.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new $s(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let n=(o=e.host)!=null?o:this.config.apiUrl,r=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!n||!r||!this.config.clientToken||Di().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Hi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,n,r;return(r=(n=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:n.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let n=ps.isSupported()?new ps({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let d=(r=e.host)!=null?r:this.config.apiUrl,c=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,u=this.config.clientToken,f=e.browserFallback!==!1;if(d&&c&&u)return Di().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:m})=>{let x=new g({host:d,agentId:c,clientToken:u,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return f&&n?new m(x,n,{onFallback:v=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${v.message}`)}):x});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){var n,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ds(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,u,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=e.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=e.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=e.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=e.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=e.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=e.browser)==null?void 0:u.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(e=this.callbacks).onError)==null||n.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!qf(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new $s(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:f}=e,m={id:a!=null?a:n==="user"?ka():n==="assistant"?Us():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:f=!1,voiceProcessing:g,rawContent:m}=r,v={id:d!=null?d:o==="user"?ka():o==="assistant"?Us():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,n){var c,u,f,g,m;let r=e.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=ka(),s=Us(),a={id:o,role:"user",content:r||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(x){let v=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!v){let M=Du(x,this.config.errorMessage);if(M){let R={id:s,role:"assistant",createdAt:new Date().toISOString(),content:M,sequence:this.nextSequence()};this.appendMessage(R)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(x instanceof Error?(f=(u=this.callbacks).onError)==null||f.call(u,x):(m=(g=this.callbacks).onError)==null||m.call(g,new Error(String(x))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Us();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let f=Du(c,this.config.errorMessage);if(f){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,n){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(e,n,r){var u,f,g,m,x;let o=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,r):v=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),v){let M=null;if(v instanceof Response){if(!v.ok){let R=await v.json().catch(()=>null);throw new Error((g=R==null?void 0:R.error)!=null?g:`Approval request failed: ${v.status}`)}M=v.body}else v instanceof ReadableStream&&(M=v);M?await this.connectStream(M,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(x=(m=this.callbacks).onError)==null||x.call(m,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){var u,f,g,m,x,v,M,R,T,k,E,I;let r=this.messages.find(A=>A.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(f=e.agentMetadata)==null?void 0:f.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let A=(v=e.toolCall)==null?void 0:v.args,L=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(L.length===1){let O=typeof((M=L[0])==null?void 0:M.question)=="string"?L[0].question:"";O&&(a={[O]:n})}}this.markAskUserQuestionResolved(e,a),(R=this.abortController)==null||R.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([L,O])=>`${L}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((L,O)=>{let _=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!_)return;let H=A[_],U=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:n});if(!A.ok){let L=await A.json().catch(()=>null);throw new Error((k=L==null?void 0:L.error)!=null?k:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let L=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(I=(E=this.callbacks).onError)==null||I.call(E,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let n=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let n=this.messages.find(a=>a.id===e.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==qr)return!1;let n=this.messages.find(s=>s.id===e.id);return((o=(n!=null?n:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){var d,c,u,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var I,A,L,O,_,H,U;let m=(I=g.toolCall)==null?void 0:I.name,x=(A=g.toolCall)==null?void 0:A.id;if(!m||!x)return null;let v=`${e}:${x}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let M=this.markWebMcpToolRunning(g),R=(O=(L=g.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?O:m;if(m===qr)return{dedupeKey:v,resumeKey:R,output:Mi(),toolMessage:g,startedAt:M,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let k=this.client.executeWebMcpToolCall(m,(_=g.toolCall)==null?void 0:_.args,T.signal),E;if(!k)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await k}catch(F){let ee=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return ee||(U=(H=this.callbacks).onError)==null||U.call(H,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(g,js(ee?"Aborted by cancel()":Nu(F)),M),this.webMcpInflightKeys.delete(v),null}return T.signal.aborted?(this.markWebMcpToolComplete(g,js("Aborted by cancel()"),M),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:R,output:E,toolMessage:g,startedAt:M,completedAt:Date.now()}})),i=[];try{if(i=a.filter(x=>x!==null),i.length===0)return;let g={};for(let x of i)g[x.resumeKey]=x.output;let m=await this.client.resumeFlow(e,g,{signal:s.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((d=x==null?void 0:x.error)!=null?d:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((c=x.toolMessage.toolCall)==null?void 0:c.name)===qr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(f=(u=this.callbacks).onError)==null||f.call(u,g instanceof Error?g:new Error(String(g)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,js("Aborted by cancel()"),x.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var x,v,M,R,T,k,E,I,A,L,O,_;let n=(x=e.agentMetadata)==null?void 0:x.executionId,r=(v=e.toolCall)==null?void 0:v.name,o=(M=e.toolCall)==null?void 0:M.id;if(!n){(T=(R=this.callbacks).onError)==null||T.call(R,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let H=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(H)||this.webMcpResolvedKeys.has(H))return;this.webMcpInflightKeys.add(H);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(H)}catch(U){(E=(k=this.callbacks).onError)==null||E.call(k,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(H)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===qr,u=(I=e.toolCall)==null?void 0:I.args,f=c?null:this.client.executeWebMcpToolCall(r,u,d),g="execute",m=a;try{let H;if(c?H=Mi():f?H=await f:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,js("Aborted by cancel()"),a);return}let U=(L=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?L:r;g="resume",await this.resumeWithToolOutput(n,U,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,H,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let U=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(e,js(U||d.aborted?"Aborted by cancel()":Nu(H)),a),U||(_=(O=this.callbacks).onError)==null||_.call(O,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,r,o){var a,i;let s=await this.client.resumeFlow(e,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,n;(n=(e=this.callbacks).onArtifactsState)==null||n.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var n,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(n=e.component)!=null?n:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Bi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ia(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let r=Bi(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var u,f,g,m,x,v,M,R,T,k,E,I,A,L,O;if(s!==r)return o;let a={...o,...n};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let _=o.approval,H=n.approval;a.approval={..._,...H,executionId:H.executionId||_.executionId,toolName:H.toolName||_.toolName,description:H.description||_.description,toolType:(m=H.toolType)!=null?m:_.toolType,reason:(x=H.reason)!=null?x:_.reason,parameters:(v=H.parameters)!=null?v:_.parameters}}let i=(M=n.toolCall)==null?void 0:M.name,d=(R=n.agentMetadata)==null?void 0:R.executionId,c=(T=n.toolCall)==null?void 0:T.id;if(i&&Fu(i)&&d&&c&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let _=`${d}:${c}`,H=this.webMcpInflightKeys.has(_),U=this.webMcpResolvedKeys.has(_),F=(E=o.toolCall)==null?void 0:E.name,ee=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&F!==void 0&&Fu(F)&&((L=o.toolCall)==null?void 0:L.status)==="complete";(H||U||ee)&&(a.agentMetadata={...(O=a.agentMetadata)!=null?O:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var C=require("lucide"),jf={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},he=(t,e=24,n="currentColor",r=2)=>{let o=jf[t];return o?Vf(o,e,n,r):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Vf(t,e,n,r){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Ba={allowedTypes:jr,maxFileSize:10*1024*1024,maxFiles:4};function Kf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Gf(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var Vs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=e.allowedTypes)!=null?n:Ba.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ba.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ba.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ba.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var n,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let u=Eu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let f=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Tu(c),g=Pa(c)?URL.createObjectURL(c):null,m={id:Kf(),file:c,previewUrl:g,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let n=this.attachments.findIndex(d=>d.id===e);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(e=this.config).onAttachmentsChange)==null||n.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Pa(e.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",n&&e.previewUrl){let a=y("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Gf(e.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Mu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:n})}};var Ou=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ks(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];Ou(s)&&Ou(o)?n[r]=Ks(s,o):n[r]=o}return n}var Vr="min(440px, calc(100vw - 24px))",$u="440px",Qf={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:Vr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Nt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Qf,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function _u(t,e){if(!(!t&&!e))return t?e?Ks(t,e):t:e}function Uu(t){var e,n,r,o,s,a,i,d,c,u,f,g,m,x,v,M,R,T,k,E,I;return t?{...Nt,...t,theme:_u(Nt.theme,t.theme),darkTheme:_u(Nt.darkTheme,t.darkTheme),launcher:{...Nt.launcher,...t.launcher,dock:{...(e=Nt.launcher)==null?void 0:e.dock,...(n=t.launcher)==null?void 0:n.dock},clearChat:{...(r=Nt.launcher)==null?void 0:r.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...Nt.copy,...t.copy},sendButton:{...Nt.sendButton,...t.sendButton},statusIndicator:{...Nt.statusIndicator,...t.statusIndicator},voiceRecognition:{...Nt.voiceRecognition,...t.voiceRecognition},features:(()=>{var re,oe,de,ze,Fe,G,X,ve,Y,ie;let A=(re=Nt.features)==null?void 0:re.artifacts,L=(oe=t.features)==null?void 0:oe.artifacts,O=(de=Nt.features)==null?void 0:de.scrollToBottom,_=(ze=t.features)==null?void 0:ze.scrollToBottom,H=(Fe=Nt.features)==null?void 0:Fe.scrollBehavior,U=(G=t.features)==null?void 0:G.scrollBehavior,F=(X=Nt.features)==null?void 0:X.streamAnimation,ee=(ve=t.features)==null?void 0:ve.streamAnimation,Ae=(Y=Nt.features)==null?void 0:Y.askUserQuestion,pe=(ie=t.features)==null?void 0:ie.askUserQuestion,te=A===void 0&&L===void 0?void 0:{...A,...L,layout:{...A==null?void 0:A.layout,...L==null?void 0:L.layout}},xe=O===void 0&&_===void 0?void 0:{...O,..._},We=H===void 0&&U===void 0?void 0:{...H,...U},le=F===void 0&&ee===void 0?void 0:{...F,...ee},me=Ae===void 0&&pe===void 0?void 0:{...Ae,...pe,styles:{...Ae==null?void 0:Ae.styles,...pe==null?void 0:pe.styles}};return{...Nt.features,...t.features,...xe!==void 0?{scrollToBottom:xe}:{},...We!==void 0?{scrollBehavior:We}:{},...te!==void 0?{artifacts:te}:{},...le!==void 0?{streamAnimation:le}:{},...me!==void 0?{askUserQuestion:me}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:Nt.suggestionChips,suggestionChipsConfig:{...Nt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Nt.layout,...t.layout,header:{...(a=Nt.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=Nt.layout)==null?void 0:d.messages,...(c=t.layout)==null?void 0:c.messages,avatar:{...(f=(u=Nt.layout)==null?void 0:u.messages)==null?void 0:f.avatar,...(m=(g=t.layout)==null?void 0:g.messages)==null?void 0:m.avatar},timestamp:{...(v=(x=Nt.layout)==null?void 0:x.messages)==null?void 0:v.timestamp,...(R=(M=t.layout)==null?void 0:M.messages)==null?void 0:R.timestamp}},slots:{...(T=Nt.layout)==null?void 0:T.slots,...(k=t.layout)==null?void 0:k.slots}},markdown:{...Nt.markdown,...t.markdown,options:{...(E=Nt.markdown)==null?void 0:E.options,...(I=t.markdown)==null?void 0:I.options}},messageActions:{...Nt.messageActions,...t.messageActions}}:Nt}var Xf={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"}},Jf={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"}},Yf={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Vr,maxWidth:$u,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function us(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),r=t;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?us(t,r):r}function zu(t){let e={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=us(t,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Zf(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function qu(t,e){let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=qu(s,o):n[r]=o}return n}function eh(t,e){return e?qu(t,e):t}function Bo(t,e={}){var o,s,a,i,d,c,u,f,g,m,x,v,M;let n={palette:Xf,semantic:Jf,components:Yf},r={palette:{...n.palette,...t==null?void 0:t.palette,colors:{...n.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=t==null?void 0:t.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...t==null?void 0:t.semantic,colors:{...n.semantic.colors,...(u=t==null?void 0:t.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(x=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...n.semantic.spacing,...(v=t==null?void 0:t.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(M=t==null?void 0:t.semantic)==null?void 0:M.typography}},components:eh(n.components,t==null?void 0:t.components)};if(e.validate!==!1){let R=Zf(r);if(!R.valid)throw new Error(`Theme validation failed: ${R.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let R of e.plugins)r=R.transform(r);return r}function ju(t){var v,M,R,T,k,E,I,A,L,O,_,H,U,F,ee,Ae,pe,te,xe,We,le,me,re,oe,de,ze,Fe,G,X,ve,Y,ie,Ee,Je,nt,wt,dt,tt,He,Q,Ve,je,we,Se,Ye,Qe,Te,_e,pn,Ft,Yt,Rr,B,K,ue,Be,$e,De,Le,it,Wt,yt,Rt,P,ce,Me,Mt,Ze,qt,yn,vt,xt,Ht,Ct,un,Ut,On,En,Mn,vn,kn,lr,At,br,vr,Hr,cr,ut,yo,xr,bo,Bn,Uo,Gr,Br,Qr,Xr,vo,xo,Jr,bt,_n,$n,Ln,St,Yn,Zn,Un,Yr,Dr,Zr,zn,Bt,Pn,er,eo,Nr,to;let e=zu(t),n={};for(let[ye,Dn]of Object.entries(e)){let wr=ye.replace(/\./g,"-");n[`--persona-${wr}`]=Dn.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(M=n["--persona-semantic-colors-secondary"])!=null?M:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(R=n["--persona-semantic-colors-accent"])!=null?R:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(T=n["--persona-semantic-colors-surface"])!=null?T:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(L=n["--persona-semantic-colors-text-inverse"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(O=n["--persona-semantic-colors-border"])!=null?O:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(_=n["--persona-semantic-colors-divider"])!=null?_:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(F=n["--persona-components-voice-processing-icon"])!=null?F:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ee=n["--persona-components-voice-speaking-icon"])!=null?ee:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ae=n["--persona-components-approval-requested-background"])!=null?Ae:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(te=n["--persona-components-approval-requested-text"])!=null?te:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(xe=n["--persona-components-approval-requested-shadow"])!=null?xe:"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"]=(We=n["--persona-components-approval-approve-background"])!=null?We:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(le=n["--persona-components-approval-deny-background"])!=null?le:n["--persona-container"],n["--persona-attachment-image-bg"]=(me=n["--persona-components-attachment-image-background"])!=null?me:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(oe=n["--persona-semantic-typography-fontFamily"])!=null?oe:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(de=n["--persona-semantic-typography-fontSize"])!=null?de:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ze=n["--persona-semantic-typography-fontWeight"])!=null?ze:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Fe=n["--persona-semantic-typography-lineHeight"])!=null?Fe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(G=n["--persona-palette-radius-sm"])!=null?G:"0.125rem",n["--persona-radius-md"]=(X=n["--persona-palette-radius-md"])!=null?X:"0.375rem",n["--persona-radius-lg"]=(ve=n["--persona-palette-radius-lg"])!=null?ve:"0.5rem",n["--persona-radius-xl"]=(Y=n["--persona-palette-radius-xl"])!=null?Y:"0.75rem",n["--persona-radius-full"]=(ie=n["--persona-palette-radius-full"])!=null?ie:"9999px",n["--persona-launcher-radius"]=(Je=(Ee=n["--persona-components-launcher-borderRadius"])!=null?Ee:n["--persona-palette-radius-full"])!=null?Je:"9999px",n["--persona-launcher-bg"]=(nt=n["--persona-components-launcher-background"])!=null?nt:n["--persona-primary"],n["--persona-launcher-fg"]=(wt=n["--persona-components-launcher-foreground"])!=null?wt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(dt=n["--persona-components-launcher-border"])!=null?dt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(He=n["--persona-components-button-primary-foreground"])!=null?He:n["--persona-text-inverse"],n["--persona-button-radius"]=(Ve=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?Ve:"9999px",n["--persona-panel-radius"]=(we=(je=n["--persona-components-panel-borderRadius"])!=null?je:n["--persona-radius-xl"])!=null?we:"0.75rem",n["--persona-panel-border"]=(Se=n["--persona-components-panel-border"])!=null?Se:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Qe=(Ye=n["--persona-components-panel-shadow"])!=null?Ye:n["--persona-palette-shadows-xl"])!=null?Qe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(Te=n["--persona-components-launcher-shadow"])!=null?Te:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(pn=(_e=n["--persona-components-input-borderRadius"])!=null?_e:n["--persona-radius-lg"])!=null?pn:"0.5rem",n["--persona-message-user-radius"]=(Yt=(Ft=n["--persona-components-message-user-borderRadius"])!=null?Ft:n["--persona-radius-lg"])!=null?Yt:"0.5rem",n["--persona-message-assistant-radius"]=(B=(Rr=n["--persona-components-message-assistant-borderRadius"])!=null?Rr:n["--persona-radius-lg"])!=null?B:"0.5rem",n["--persona-header-bg"]=(K=n["--persona-components-header-background"])!=null?K:n["--persona-surface"],n["--persona-header-border"]=(ue=n["--persona-components-header-border"])!=null?ue:n["--persona-divider"],n["--persona-header-icon-bg"]=(Be=n["--persona-components-header-iconBackground"])!=null?Be:n["--persona-primary"],n["--persona-header-icon-fg"]=($e=n["--persona-components-header-iconForeground"])!=null?$e:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(De=n["--persona-components-header-titleForeground"])!=null?De:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Le=n["--persona-components-header-subtitleForeground"])!=null?Le:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(it=n["--persona-components-header-actionIconForeground"])!=null?it:n["--persona-muted"];let r=(Wt=t.components)==null?void 0:Wt.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=t.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(Rt=n["--persona-components-introCard-background"])!=null?Rt:n["--persona-surface"],n["--persona-intro-card-radius"]=(P=n["--persona-components-introCard-borderRadius"])!=null?P:"1rem",n["--persona-intro-card-padding"]=(ce=n["--persona-components-introCard-padding"])!=null?ce:"1.5rem",n["--persona-intro-card-shadow"]=(Mt=(Me=o==null?void 0:o.shadow)!=null?Me:n["--persona-components-introCard-shadow"])!=null?Mt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ze=n["--persona-components-input-background"])!=null?Ze:n["--persona-surface"],n["--persona-input-placeholder"]=(qt=n["--persona-components-input-placeholder"])!=null?qt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(yn=n["--persona-components-message-user-background"])!=null?yn:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(xt=n["--persona-components-message-user-shadow"])!=null?xt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Ht=n["--persona-components-message-assistant-background"])!=null?Ht:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ct=n["--persona-components-message-assistant-text"])!=null?Ct:n["--persona-text"],n["--persona-message-assistant-border"]=(un=n["--persona-components-message-assistant-border"])!=null?un:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ut=n["--persona-components-message-assistant-shadow"])!=null?Ut:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(En=(On=n["--persona-components-scrollToBottom-background"])!=null?On:n["--persona-button-primary-bg"])!=null?En:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(vn=(Mn=n["--persona-components-scrollToBottom-foreground"])!=null?Mn:n["--persona-button-primary-fg"])!=null?vn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(kn=n["--persona-components-scrollToBottom-border"])!=null?kn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(vr=(br=(At=n["--persona-components-scrollToBottom-borderRadius"])!=null?At:n["--persona-button-radius"])!=null?br:n["--persona-radius-full"])!=null?vr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Hr=n["--persona-components-scrollToBottom-shadow"])!=null?Hr:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(yo=n["--persona-components-scrollToBottom-gap"])!=null?yo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(bo=(xr=n["--persona-components-scrollToBottom-fontSize"])!=null?xr:n["--persona-palette-typography-fontSize-sm"])!=null?bo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Bn=n["--persona-components-scrollToBottom-iconSize"])!=null?Bn:"14px",n["--persona-tool-bubble-shadow"]=(Uo=n["--persona-components-toolBubble-shadow"])!=null?Uo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Gr=n["--persona-components-reasoningBubble-shadow"])!=null?Gr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Br=n["--persona-components-composer-shadow"])!=null?Br:"none",n["--persona-md-inline-code-bg"]=(Qr=n["--persona-components-markdown-inlineCode-background"])!=null?Qr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Xr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Xr:n["--persona-text"],n["--persona-md-link-color"]=(xo=(vo=n["--persona-components-markdown-link-foreground"])!=null?vo:n["--persona-accent"])!=null?xo:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Jr=n["--persona-components-markdown-codeBlock-background"])!=null?Jr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(bt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?bt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(_n=n["--persona-components-markdown-codeBlock-textColor"])!=null?_n:"inherit",n["--persona-md-table-header-bg"]=($n=n["--persona-components-markdown-table-headerBackground"])!=null?$n:n["--persona-container"],n["--persona-md-table-border-color"]=(Ln=n["--persona-components-markdown-table-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-hr-color"]=(St=n["--persona-components-markdown-hr-color"])!=null?St:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Yn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Yn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Zn=n["--persona-components-markdown-blockquote-background"])!=null?Zn:"transparent",n["--persona-md-blockquote-text-color"]=(Un=n["--persona-components-markdown-blockquote-textColor"])!=null?Un:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Yr=n["--persona-components-collapsibleWidget-container"])!=null?Yr:n["--persona-surface"],n["--cw-surface"]=(Dr=n["--persona-components-collapsibleWidget-surface"])!=null?Dr:n["--persona-surface"],n["--cw-border"]=(Zr=n["--persona-components-collapsibleWidget-border"])!=null?Zr:n["--persona-border"],n["--persona-message-border"]=(zn=n["--persona-components-message-border"])!=null?zn:n["--persona-border"];let u=t.components,f=u==null?void 0:u.iconButton;f&&(f.background&&(n["--persona-icon-btn-bg"]=f.background),f.border&&(n["--persona-icon-btn-border"]=f.border),f.color&&(n["--persona-icon-btn-color"]=f.color),f.padding&&(n["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(n["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(n["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(n["--persona-icon-btn-active-border"]=f.activeBorder));let g=u==null?void 0:u.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(n["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(n["--persona-toggle-group-radius"]=m.borderRadius));let x=u==null?void 0:u.artifact;if(x!=null&&x.toolbar){let ye=x.toolbar;ye.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,n["--persona-dropdown-bg"]=(Bt=n["--persona-dropdown-bg"])!=null?Bt:ye.copyMenuBackground),ye.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,n["--persona-dropdown-border"]=(Pn=n["--persona-dropdown-border"])!=null?Pn:ye.copyMenuBorder),ye.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,n["--persona-dropdown-shadow"]=(er=n["--persona-dropdown-shadow"])!=null?er:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(eo=n["--persona-dropdown-radius"])!=null?eo:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Nr=n["--persona-dropdown-item-hover-bg"])!=null?Nr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(x!=null&&x.tab){let ye=x.tab;ye.background&&(n["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(n["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(n["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(n["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(n["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(n["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(x!=null&&x.pane){let ye=x.pane;if(ye.toolbarBackground){let Dn=(to=us(t,ye.toolbarBackground))!=null?to:ye.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Dn}}return n}var th={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"}}},Vu=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ni=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},nh=t=>{var n;let e=(n=t==null?void 0:t.colorScheme)!=null?n:"light";return e==="light"?"light":e==="dark"?"dark":Ni()},rh=t=>nh(t),oh=t=>Bo(t),sh=t=>{var n;let e=Bo(void 0,{validate:!1});return Bo({...t,palette:{...e.palette,colors:{...th.colors,...(n=t==null?void 0:t.palette)==null?void 0:n.colors}}},{validate:!1})},Da=t=>{let e=rh(t),n=Vu(t==null?void 0:t.theme),r=Vu(t==null?void 0:t.darkTheme);return e==="dark"?sh(Ks(n!=null?n:{},r!=null?r:{})):oh(n)},ah=t=>ju(t),ms=(t,e)=>{let n=Da(e),r=ah(n);for(let[o,s]of Object.entries(r))t.style.setProperty(o,s)},Ku=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{t(Ni())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>t(Ni());n.addEventListener?(n.addEventListener("change",r),e.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),e.push(()=>n.removeListener(r)))}return()=>{e.forEach(n=>n())}};var Gu=require("idiomorph"),Na=(t,e,n={})=>{let{preserveTypingAnimation:r=!0}=n;Gu.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Qu=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Fa={index:-1,draft:""};function Xu(t){let{direction:e,history:n,currentValue:r,atStart:o,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Fa}}}function Ju(t,e){var n,r,o,s,a,i,d,c,u,f,g,m,x,v,M,R,T,k,E,I,A,L,O,_,H,U,F,ee,Ae,pe,te,xe,We,le,me,re,oe,de;return[t.id,t.role,(r=(n=t.content)==null?void 0:n.length)!=null?r:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=t.llmContent)==null?void 0:c.length)!=null?u:0,(g=(f=t.approval)==null?void 0:f.status)!=null?g:"",(x=(m=t.toolCall)==null?void 0:m.status)!=null?x:"",(M=(v=t.toolCall)==null?void 0:v.name)!=null?M:"",(k=(T=(R=t.toolCall)==null?void 0:R.chunks)==null?void 0:T.length)!=null?k:0,(L=(A=(I=(E=t.toolCall)==null?void 0:E.chunks)==null?void 0:I[t.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?L:"",typeof((O=t.toolCall)==null?void 0:O.args)=="string"?t.toolCall.args.length:(_=t.toolCall)!=null&&_.args?JSON.stringify(t.toolCall.args).length:0,(F=(U=(H=t.reasoning)==null?void 0:H.chunks)==null?void 0:U.length)!=null?F:0,(te=(pe=(Ae=(ee=t.reasoning)==null?void 0:ee.chunks)==null?void 0:Ae[t.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?te:0,(me=(le=(We=(xe=t.reasoning)==null?void 0:xe.chunks)==null?void 0:We[t.reasoning.chunks.length-1])==null?void 0:le.slice(-32))!=null?me:"",(oe=(re=t.contentParts)==null?void 0:re.length)!=null?oe:0,(de=t.stopReason)!=null?de:"",e].join("\0")}function Yu(){return new Map}function Zu(t,e,n){let r=t.get(e);return r&&r.fingerprint===n?r.wrapper:null}function em(t,e,n,r){t.set(e,{fingerprint:n,wrapper:r})}function tm(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Oa(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Kr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Do(t,e){return Kr(t)-t.scrollTop<=e}function _a(t){let{following:e,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=t,u=n-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function $a(t){let{following:e,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=t;return e&&n<0?"pause":!e&&o&&n>0&&r?"resume":"none"}function nm(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function rm(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function om(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var An={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Sn=1e5,fo=Sn+1;var Gs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ih=["pre","code","a","script","style"],Ua=t=>{var e,n,r,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Gs.type,placeholder:(n=t==null?void 0:t.placeholder)!=null?n:Gs.placeholder,speed:(r=t==null?void 0:t.speed)!=null?r:Gs.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Gs.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Gs.buffer}},lh=[{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"}],am=new Map;for(let t of lh)am.set(t.name,t);var Qs=(t,e)=>{var n,r;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(n=e[t])!=null?n:null:(r=am.get(t))!=null?r:null},za=(t,e,n,r,o)=>{if(!o)return t;if(n!=null&&n.bufferContent)return n.bufferContent(t,r);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
19
|
+
`);return s<0?"":t.slice(0,s)}return t},ch=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},dh=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Fi=/\s/,ph=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(e.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},uh=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Fi.test(s[i])){let c=i;for(;c<s.length&&Fi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Fi.test(s[u]);)c.appendChild(ch(r,s[u],e,n.value)),n.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,t)},mh=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(dh(r,c,e,n.value)),n.value+=1));o.replaceChild(a,t)},Xs=(t,e,n,r)=>{var f,g;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((f=r==null?void 0:r.skipTags)!=null?f:ih).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)ph(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},u=e==="char"?uh:mh;for(let m of i)u(m,n,c);return o.innerHTML},qa=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Js=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},sm=new WeakMap,gh=(t,e)=>{var s;if(!t.styles)return;let n=sm.get(e);if(n||(n=new Set,sm.set(e,n)),n.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(t.name)}n.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},Oi=new WeakMap,fh=(t,e)=>{if(!t.onAttach)return;let n=Oi.get(e);if(n||(n=new Map,Oi.set(e,n)),n.has(t.name))return;let r=t.onAttach(e);n.set(t.name,r)},im=t=>{let e=Oi.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},_i=(t,e)=>{gh(t,e),fh(t,e)};function $i(t,e=Sn){let n=t.style.position,r=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=r,t.style.isolation=o}}var Ys=0,ho=null;function Ui(t=document){var n;if(Ys++,Ys===1){let r=t.body,s=((n=t.defaultView)!=null?n:window).scrollY||t.documentElement.scrollTop;ho={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,Ys=Math.max(0,Ys-1),Ys===0&&ho)){let o=t.body,s=(r=t.defaultView)!=null?r:window;o.style.overflow=ho.originalOverflow,o.style.position=ho.originalPosition,o.style.top=ho.originalTop,o.style.width=ho.originalWidth,s.scrollTo(0,ho.scrollY),ho=null}}}var Zs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},bn=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="docked"},ea=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="composer-bar"},hr=t=>{var n,r,o,s,a,i;let e=(n=t==null?void 0:t.launcher)==null?void 0:n.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Zs.side,width:(o=e==null?void 0:e.width)!=null?o:Zs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Zs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Zs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Zs.maxHeight}};var yr={"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 hh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ja=(t,e={})=>{var M,R,T,k,E,I;let{showClose:n=!0,wrapperClassName:r=hh,buttonSize:o,iconSize:s="28px"}=e,a=(M=t==null?void 0:t.launcher)!=null?M:{},i=(R=o!=null?o:a.closeButtonSize)!=null?R:"32px",d=y("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",u=(k=a.closeButtonShowTooltip)!=null?k:!0,f=(E=a.closeButtonIconName)!=null?E:"x",g=(I=a.closeButtonIconText)!=null?I:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=Et("button",{className:Hs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Hn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=he(f,s,"currentColor",1);if(v?(v.style.display="block",x.appendChild(v)):x.textContent=g,d.appendChild(x),u&&c){let A=null,L=()=>{if(A)return;let _=x.ownerDocument,H=_.body;if(!H)return;A=Wr(_,"div","persona-clear-chat-tooltip"),A.textContent=c;let U=Wr(_,"div");U.className="persona-clear-chat-tooltip-arrow",A.appendChild(U);let F=x.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(fo),A.style.left=`${F.left+F.width/2}px`,A.style.top=`${F.top-8}px`,A.style.transform="translate(-50%, -100%)",H.appendChild(A)},O=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",L),d.addEventListener("mouseleave",O),x.addEventListener("focus",L),x.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",O),x.removeEventListener("focus",L),x.removeEventListener("blur",O)}}return{button:x,wrapper:d}},yh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Va=(t,e={})=>{var A,L,O,_,H,U,F,ee,Ae,pe,te,xe,We;let{wrapperClassName:n=yh,buttonSize:r,iconSize:o="20px"}=e,a=(L=((A=t==null?void 0:t.launcher)!=null?A:{}).clearChat)!=null?L:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(H=a.iconColor)!=null?H:"",u=(U=a.backgroundColor)!=null?U:"",f=(F=a.borderWidth)!=null?F:"",g=(ee=a.borderColor)!=null?ee:"",m=(Ae=a.borderRadius)!=null?Ae:"",x=(pe=a.paddingX)!=null?pe:"",v=(te=a.paddingY)!=null?te:"",M=(xe=a.tooltipText)!=null?xe:"Clear chat",R=(We=a.showTooltip)!=null?We:!0,T=y("div",n),k=!!(f||g),E=Et("button",{className:Hs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:c||Hn.actionIconColor,backgroundColor:u||void 0,border:k?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),I=he(d,o,"currentColor",1);if(I&&(I.style.display="block",E.appendChild(I)),T.appendChild(E),R&&M){let le=null,me=()=>{if(le)return;let oe=E.ownerDocument,de=oe.body;if(!de)return;le=Wr(oe,"div","persona-clear-chat-tooltip"),le.textContent=M;let ze=Wr(oe,"div");ze.className="persona-clear-chat-tooltip-arrow",le.appendChild(ze);let Fe=E.getBoundingClientRect();le.style.position="fixed",le.style.zIndex=String(fo),le.style.left=`${Fe.left+Fe.width/2}px`,le.style.top=`${Fe.top-8}px`,le.style.transform="translate(-50%, -100%)",de.appendChild(le)},re=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};T.addEventListener("mouseenter",me),T.addEventListener("mouseleave",re),E.addEventListener("focus",me),E.addEventListener("blur",re),T._cleanupTooltip=()=>{re(),T.removeEventListener("mouseenter",me),T.removeEventListener("mouseleave",re),E.removeEventListener("focus",me),E.removeEventListener("blur",re)}}return{button:E,wrapper:T}};var Hn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},No=t=>{var I,A,L,O,_,H,U,F,ee,Ae,pe,te,xe,We,le,me;let{config:e,showClose:n=!0}=t,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(I=e==null?void 0:e.launcher)!=null?I:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(O=o.headerIconHidden)!=null?O:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,oe=he(d,re*.6,"currentColor",1);oe?c.replaceChildren(oe):c.textContent=(H=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?H:"\u{1F4AC}"}else if((U=e==null?void 0:e.launcher)!=null&&U.iconUrl){let re=y("img");re.src=e.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(ee=(F=e==null?void 0:e.launcher)==null?void 0:F.agentIconText)!=null?ee:"\u{1F4AC}";let u=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Et("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Ae=e==null?void 0:e.launcher)==null?void 0:Ae.title)!=null?pe:"Chat Assistant",style:{color:Hn.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(xe=(te=e==null?void 0:e.launcher)==null?void 0:te.subtitle)!=null?xe:"Here to help you get answers fast",style:{color:Hn.subtitleColor}});u.append(f,g),i?r.append(u):r.append(c,u);let m=(We=o.clearChat)!=null?We:{},x=(le=m.enabled)!=null?le:!0,v=(me=m.placement)!=null?me:"inline",M=null,R=null;if(x){let oe=Va(e,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=oe.button,R=oe.wrapper,v==="top-right"&&(R.style.right="48px"),v==="inline"&&r.appendChild(R)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:E}=ja(e,{showClose:n,wrapperClassName:T});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:g,closeButton:k,closeButtonWrapper:E,clearChatButton:M,clearChatButtonWrapper:R}},ta=(t,e,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function gs(t){let{items:e,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=t,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(fo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let M=he(m.icon,16,"currentColor",1.5);M&&x.appendChild(M)}let v=document.createElement("span");v.textContent=m.label,x.appendChild(v),x.addEventListener("click",M=>{M.stopPropagation(),u(),n(m.id)}),a.appendChild(x)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!a.contains(x.target)&&!r.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:f,destroy:g}}function Tn(t){let{icon:e,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=he(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,f]of Object.entries(i))d.setAttribute(u,f);return d}function zi(t){let{icon:e,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=y("button",c);if(u.type="button",u.setAttribute("aria-label",n),e){let g=he(e,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let f=y("span");if(f.textContent=n,u.appendChild(f),i&&u.addEventListener("click",i),d)for(let[g,m]of Object.entries(d))u.setAttribute(g,m);return u}function lm(t){var m,x;let{label:e,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=y("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let f=he(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",c.appendChild(f)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(x=d.padding)!=null?x:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,M;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(M=d.border)!=null?M:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=gs({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let M=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{u.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var bh=t=>{var r;let e=No({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=(r=t.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function vh(t,e,n){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=gs({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),t.appendChild(i)}}var xh=t=>{var T,k,E,I,A,L,O,_,H;let{config:e,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=lm({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Hn.titleColor,u=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=y("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Hn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),vh(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let F=o.onTitleClick;c.addEventListener("click",ee=>{ee.target.closest("button")||F()}),c.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),F())})}let U=o==null?void 0:o.titleRowHover;U&&(c.style.borderRadius=(L=U.borderRadius)!=null?L:"10px",c.style.padding=(O=U.padding)!=null?O:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,ee;c.style.backgroundColor=(F=U.background)!=null?F:"",c.style.borderColor=(ee=U.border)!=null?ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(_=a.closeButtonSize)!=null?_:"32px",g=y("div",""),m=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");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=a.closeButtonColor||Hn.actionIconColor;let x=(H=a.closeButtonIconName)!=null?H:"x",v=he(x,"28px","currentColor",1);v?m.appendChild(v):m.textContent="\xD7",r&&m.addEventListener("click",r),g.appendChild(m),i.appendChild(g);let M=y("div");M.style.display="none";let R=y("span");return R.style.display="none",{header:i,iconHolder:M,headerTitle:u,headerSubtitle:R,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},cm={default:bh,minimal:xh},wh=t=>{var e;return(e=cm[t])!=null?e:cm.default},Ka=(t,e,n)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:t,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=y("div");u.style.display="none";let f=y("span"),g=y("span"),m=y("button");m.style.display="none";let x=y("div");return x.style.display="none",{header:c,iconHolder:u,headerTitle:f,headerSubtitle:g,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=wh(r)({config:t,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ga=t=>{var a,i;let e=y("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;e.style.maxHeight=`${n*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Qa=t=>{var I,A,L,O,_,H,U,F,ee,Ae,pe,te;let e=(I=t==null?void 0:t.sendButton)!=null?I:{},n=(A=e.useIcon)!=null?A:!1,r=(L=e.iconText)!=null?L:"\u2191",o=e.iconName,s=(O=e.stopIconName)!=null?O:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(H=e.stopTooltipText)!=null?H:"Stop generating",d=(F=(U=t==null?void 0:t.copy)==null?void 0:U.sendButtonLabel)!=null?F:"Send",c=(Ae=(ee=t==null?void 0:t.copy)==null?void 0:ee.stopButtonLabel)!=null?Ae:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,f=(te=e.size)!=null?te:"40px",g=e.backgroundColor,m=e.textColor,x=y("div","persona-send-button-wrapper"),v=Et("button",{className:Hs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f: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&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),M=null,R=null;if(n){let xe=parseFloat(f)||24,We=(m==null?void 0:m.trim())||"currentColor";o?(M=he(o,xe,We,2),M?v.appendChild(M):v.textContent=r):v.textContent=r,R=he(s,xe,We,2)}else v.textContent=d;let T=null;u&&a&&(T=y("div","persona-send-button-tooltip"),T.textContent=a,x.appendChild(T)),v.setAttribute("aria-label",a),x.appendChild(v);let k="send";return{button:v,wrapper:x,setMode:xe=>{if(xe===k)return;k=xe;let We=xe==="stop"?i:a;if(v.setAttribute("aria-label",We),T&&(T.textContent=We),n){if(M&&R){let le=xe==="stop"?R:M;v.replaceChildren(le)}}else v.textContent=xe==="stop"?c:d}}},Xa=t=>{var T,k,E,I,A,L,O,_,H,U,F,ee;let e=(T=t==null?void 0:t.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=e.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(I=(E=t==null?void 0:t.sendButton)==null?void 0:E.size)!=null?I:"40px",i=(A=e.iconName)!=null?A:"mic",d=(L=e.iconSize)!=null?L:a,c=parseFloat(d)||24,u=(_=e.backgroundColor)!=null?_:(O=t==null?void 0:t.sendButton)==null?void 0:O.backgroundColor,f=(U=e.iconColor)!=null?U:(H=t==null?void 0:t.sendButton)==null?void 0:H.textColor,g=y("div","persona-send-button-wrapper"),m=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),v=he(i,c,f||"currentColor",1.5);v?m.appendChild(v):m.textContent="\u{1F3A4}",g.appendChild(m);let M=(F=e.tooltipText)!=null?F:"Start voice recognition";if(((ee=e.showTooltip)!=null?ee:!1)&&M){let Ae=y("div","persona-send-button-tooltip");Ae.textContent=M,g.appendChild(Ae)}return{button:m,wrapper:g}},Ja=t=>{var x,v,M,R,T,k,E,I;let e=(x=t==null?void 0:t.attachments)!=null?x:{};if(e.enabled!==!0)return null;let n=(M=(v=t==null?void 0:t.sendButton)==null?void 0:v.size)!=null?M:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((R=e.allowedTypes)!=null?R:jr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=e.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),u=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=e.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let f=he(s,d,"currentColor",1.5);f?u.appendChild(f):u.textContent="\u{1F4CE}",u.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(u);let g=(I=e.buttonTooltipText)!=null?I:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=g,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},Ya=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=y("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Za=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ei=t=>{var x,v,M,R,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Za(),o=Et("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Ga(e);a();let i=Qa(e),d=Xa(e),c=Ja(e),u=Ya(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(g,m),o.append(f),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,u),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(R=c==null?void 0:c.wrapper)!=null?R:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:f,leftActions:g,rightActions:m,setSendButtonMode:i.setMode}};var dm=()=>{let t=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=y("span","persona-pill-peek__icon"),n=he("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,r,o),{root:t,textNode:r}},pm=t=>{var x,v,M,R,T,k;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Za();r.style.display="none";let o=Ya(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ga(e);s.style.maxHeight="100px",a();let i=Qa(e),d=Xa(e),c=Ja(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),f=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&f.append(c.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(f,s,g),c&&n.append(c.previewsContainer),n.append(u,r,o);let m=u;return{footer:n,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=d==null?void 0:d.button)!=null?x:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(M=c==null?void 0:c.button)!=null?M:null,attachmentButtonWrapper:(R=c==null?void 0:c.wrapper)!=null?R:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(k=c==null?void 0:c.previewsContainer)!=null?k:null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var um=t=>{var u,f,g,m,x,v,M,R,T,k,E,I,A,L,O,_,H;let e=(f=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?f:!0,n=bn(t);if(ea(t)){let U=(m=(g=t==null?void 0:t.launcher)==null?void 0:g.composerBar)!=null?m:{},F=y("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(x=U.expandedSize)!=null?x:"anchored",F.style.zIndex=String((M=(v=t==null?void 0:t.launcher)==null?void 0:v.zIndex)!=null?M:Sn);let ee=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ee.style.width="100%",F.appendChild(ee);let Ae=y("div","persona-widget-pill-root");return Ae.setAttribute("data-persona-composer-bar",""),Ae.dataset.state="collapsed",Ae.dataset.expandedSize=(R=U.expandedSize)!=null?R:"anchored",Ae.style.zIndex=String((k=(T=t==null?void 0:t.launcher)==null?void 0:T.zIndex)!=null?k:Sn),{wrapper:F,panel:ee,pillRoot:Ae}}if(n){let U=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return U.appendChild(F),{wrapper:U,panel:F}}if(!e){let U=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ee=(I=(E=t==null?void 0:t.launcher)==null?void 0:E.width)!=null?I:"100%";return U.style.width=ee,F.style.width="100%",U.appendChild(F),{wrapper:U,panel:F}}let o=(A=t==null?void 0:t.launcher)!=null?A:{},s=o.position&&yr[o.position]?yr[o.position]:yr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((O=(L=t==null?void 0:t.launcher)==null?void 0:L.zIndex)!=null?O:Sn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(_=t==null?void 0:t.launcher)==null?void 0:_.width)!=null?H:t==null?void 0:t.launcherWidth,c=d!=null?d:Vr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Ch=(t,e)=>{var E,I,A,L,O,_,H,U,F;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ja(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(A=(I=(E=t==null?void 0:t.launcher)==null?void 0:E.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(s){let ee=Va(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ee.button,i=ee.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let u=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(O=(L=t==null?void 0:t.copy)==null?void 0:L.welcomeTitle)!=null?O:"Hello \u{1F44B}"}),f=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(_=t==null?void 0:t.copy)==null?void 0:_.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,f),m=y("div","persona-flex persona-flex-col persona-gap-3"),x=(U=t==null?void 0:t.layout)==null?void 0:U.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((F=t==null?void 0:t.copy)==null?void 0:F.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,m);let M=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),R=pm({config:t}),{root:T,textNode:k}=dm();return n.append(d,o,c,M),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:m,composerOverlay:M,suggestions:R.suggestions,textarea:R.textarea,sendButton:R.sendButton,sendButtonWrapper:R.sendButtonWrapper,micButton:R.micButton,micButtonWrapper:R.micButtonWrapper,composerForm:R.composerForm,statusText:R.statusText,introTitle:u,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:R.footer,attachmentButton:R.attachmentButton,attachmentButtonWrapper:R.attachmentButtonWrapper,attachmentInput:R.attachmentInput,attachmentPreviewsContainer:R.attachmentPreviewsContainer,actionsRow:R.actionsRow,leftActions:R.leftActions,rightActions:R.rightActions,setSendButtonMode:R.setSendButtonMode,peekBanner:T,peekTextNode:k}},mm=(t,e=!0)=>{var M,R,T,k,E,I,A,L,O;if(ea(t))return Ch(t,e);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(M=t==null?void 0:t.layout)==null?void 0:M.header,o=((R=t==null?void 0:t.layout)==null?void 0:R.showHeader)!==!1,s=r?Ka(t,r,{showClose:e}):No({config:t,showClose:e}),a=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(T=t==null?void 0:t.copy)==null?void 0:T.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:bn(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=y("div","persona-flex persona-flex-col persona-gap-3"),f=(A=t==null?void 0:t.layout)==null?void 0:A.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((L=t==null?void 0:t.copy)==null?void 0:L.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=ei({config:t}),x=((O=t==null?void 0:t.layout)==null?void 0:O.showFooter)!==!1;o?ta(n,s,t):(s.header.style.display="none",ta(n,s,t)),n.append(a);let v=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return x||(m.footer.style.display="none"),n.append(m.footer),n.append(v),{container:n,body:a,messagesWrapper:u,composerOverlay:v,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var qi=(t,e)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
18
20
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
19
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
20
22
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -22,14 +24,14 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
22
24
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
23
25
|
</span>
|
|
24
26
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
25
|
-
`,t.addEventListener("click",e);let r=s=>{var F,L,R,A,W,N,D,k,j,V,ne,Re,Ue;let a=(F=s.launcher)!=null?F:{},i=gn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let xe=(L=a.title)!=null?L:"Chat Assistant";d.textContent=xe,d.setAttribute("title",xe)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let xe=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=xe,c.setAttribute("title",xe)}let m=t.querySelector(".persona-flex-col");m&&(a.textHidden||i?m.style.display="none":m.style.display="");let f=t.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let xe=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=xe,f.style.width=xe,f.innerHTML="",a.agentIconName){let Ie=parseFloat(xe)||24,_e=Ae(a.agentIconName,Ie*.6,"var(--persona-text-inverse, #ffffff)",2);_e?(f.appendChild(_e),f.style.display=""):(f.textContent=(W=a.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}let g=t.querySelector("[data-role='launcher-image']");if(g){let xe=(D=a.agentIconSize)!=null?D:"40px";g.style.height=xe,g.style.width=xe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let u=t.querySelector("[data-role='launcher-call-to-action-icon']");if(u){let xe=(k=a.callToActionIconSize)!=null?k:"32px";u.style.height=xe,u.style.width=xe,a.callToActionIconBackgroundColor?(u.style.backgroundColor=a.callToActionIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(u.style.color=a.callToActionIconColor,u.classList.remove("persona-text-persona-call-to-action")):(u.style.color="",u.classList.add("persona-text-persona-call-to-action"));let Ie=0;if(a.callToActionIconPadding?(u.style.boxSizing="border-box",u.style.padding=a.callToActionIconPadding,Ie=(parseFloat(a.callToActionIconPadding)||0)*2):(u.style.boxSizing="",u.style.padding=""),a.callToActionIconHidden)u.style.display="none";else if(u.style.display=i?"none":"",u.innerHTML="",a.callToActionIconName){let _e=parseFloat(xe)||24,Se=Math.max(_e-Ie,8),ve=Ae(a.callToActionIconName,Se,"currentColor",2);ve?u.appendChild(ve):u.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}else u.textContent=(V=a.callToActionIconText)!=null?V:"\u2197"}let v=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",I="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?I:`${x} ${v}`,i||(t.style.zIndex=String((ne=a.zIndex)!=null?ne:wn));let M="1px solid var(--persona-border, #e5e7eb)",E="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Re=a.border)!=null?Re:M,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Ue=a.collapsedMaxWidth)!=null?Ue:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var im=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=sm(n),s=am(n,e),a={wrapper:t,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},qi=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>Ui(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Ui(n,t);return{instance:o,element:o.element}};var ih=n=>{switch(n){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}},lh=(n,e)=>{if(!n)return null;let t=ih(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},ch=(n,e)=>{let t=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},dh=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},zi=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},ji=320,cm=320,ph=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),uh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),mh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),gh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),fh=(n,e,t)=>{if(n.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var f;let c=b("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${ji}px`,c.style.maxHeight=`${cm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let m=!1;o+=1,c.addEventListener("error",()=>{m||(m=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{m=!0}),dh(i.image)?(c.src=i.image,r.appendChild(c)):(m=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},hh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!zi(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${ji}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},yh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!zi(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${ji}px`,o.style.maxHeight=`${cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},bh=n=>{if(n.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!zi(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Js=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";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="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},vh=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:Js};if(e){let o=e(r);if(o!==null)return o}return Js()},xh=(n,e)=>{let t=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},lm=(n,e,t="div")=>{let r=b(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},wh=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Ch=(n,e,t)=>{var v,x,I,M,E,F,L;let r=(v=e.showCopy)!=null?v:!0,o=(x=e.showUpvote)!=null?x:!0,s=(I=e.showDownvote)!=null?I:!0,a=(M=e.showReadAloud)!=null?M:!1;if(!r&&!o&&!s&&!a){let R=b("div");return R.style.display="none",R.id=`actions-${n.id}`,R.setAttribute("data-actions-for",n.id),R}let i=(E=e.visibility)!=null?E:"hover",d=(F=e.align)!=null?F:"right",c=(L=e.layout)!=null?L:"pill-inside",m={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${m} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${n.id}`,g.setAttribute("data-actions-for",n.id);let u=(R,A,W)=>{let N=Cn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",W),N};return r&&g.appendChild(u("copy","Copy message","copy")),a&&g.appendChild(u("volume-2","Read aloud","read-aloud")),o&&g.appendChild(u("thumbs-up","Upvote","upvote")),s&&g.appendChild(u("thumbs-down","Downvote","downvote")),g},Vi=(n,e,t,r,o,s)=>{var re,X,ie,he,oe,K,te,qe,Y,le,Pe,it,lt,rt,Ee,pe,Xe;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,m=(X=d==null?void 0:d.show)!=null?X:!1,f=(ie=c==null?void 0:c.show)!=null?ie:!1,g=(he=d==null?void 0:d.position)!=null?he:"left",u=(oe=c==null?void 0:c.position)!=null?oe:"below",v=wh(n.role,i),x=b("div",v.join(" "));x.id=`bubble-${n.id}`,x.setAttribute("data-message-id",n.id),x.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let I=ph(n),M=(te=(K=n.content)==null?void 0:K.trim())!=null?te:"",F=I.length>0&&M===Ma,L=Oa((Y=(qe=s==null?void 0:s.widgetConfig)==null?void 0:qe.features)==null?void 0:Y.streamAnimation),R=(it=(Pe=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Pe.streamAnimation)==null?void 0:it.plugins,A=n.role==="assistant"&&L.type!=="none"?zs(L.type,R):null,W=n.role==="assistant"&&((lt=A==null?void 0:A.isAnimating)==null?void 0:lt.call(A,n))===!0,N=n.role==="assistant"&&A!==null&&(!!n.streaming||W);N&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let D=document.createElement("div");D.classList.add("persona-message-content"),N&&A&&(A.containerClass&&D.classList.add(A.containerClass),D.style.setProperty("--persona-stream-step",`${L.speed}ms`),D.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let k=N?_a((rt=n.content)!=null?rt:"",L.buffer,A,n,!!n.streaming):(Ee=n.content)!=null?Ee:"",j=e({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),V=j;N&&(A==null?void 0:A.wrap)==="char"?V=js(j,"char",n.id,{skipTags:A.skipTags}):N&&(A==null?void 0:A.wrap)==="word"&&(V=js(j,"word",n.id,{skipTags:A.skipTags}));let ne=null;if(F?(ne=document.createElement("div"),ne.innerHTML=V,ne.style.display="none",D.appendChild(ne)):D.innerHTML=V,N&&(A!=null&&A.useCaret)&&!F&&M){let J=$a(),ce=D.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ce[ce.length-1];if(we!=null&&we.parentNode)we.parentNode.insertBefore(J,we.nextSibling);else{let je=D.lastElementChild;je?je.appendChild(J):D.appendChild(J)}}if(f&&u==="inline"&&n.createdAt){let J=lm(n,c,"span");J.classList.add("persona-timestamp-inline");let ce=D.lastElementChild;ce?ce.appendChild(J):D.appendChild(J)}if(I.length>0){let J=fh(I,!F&&!!M,()=>{F&&ne&&(ne.style.display="")});J?x.appendChild(J):F&&ne&&(ne.style.display="")}let Re=uh(n);if(Re.length>0){let J=hh(Re);J&&x.appendChild(J)}let Ue=mh(n);if(Ue.length>0){let J=yh(Ue);J&&x.appendChild(J)}let xe=gh(n);if(xe.length>0){let J=bh(xe);J&&x.appendChild(J)}if(x.appendChild(D),f&&u==="below"&&n.createdAt){let J=lm(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ie=n.role==="assistant"?lh(n.stopReason,(Xe=(pe=s==null?void 0:s.widgetConfig)==null?void 0:pe.copy)==null?void 0:Xe.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(k&&k.trim()),ce=L.placeholder==="skeleton",we=ce&&L.buffer==="line"&&J;if(J)we&&x.appendChild(Vs());else if(ce)x.appendChild(Vs());else{let je=vh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);je&&x.appendChild(je)}}if(Ie&&n.stopReason&&!n.streaming&&(M||(D.style.display="none"),x.appendChild(ch(n.stopReason,Ie))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Ch(n,r,o);x.appendChild(J)}if(!m||n.role==="system")return x;let Se=b("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),ve=xh(d,n.role);return g==="right"||g==="left"&&n.role==="user"?Se.append(x,ve):Se.append(ve,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Se};var ds=new Set,Ah=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Sh=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
26
|
-
`):""},
|
|
27
|
-
`);let o=
|
|
28
|
-
`):""},Gi=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Eh=(n,e)=>{var m,f,g,u,v;let t=n.toolCall,r=(m=e==null?void 0:e.features)==null?void 0:m.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Mh(n,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?du(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(u=e==null?void 0:e.toolCall)!=null?u:{},c=a;return o==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ki(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ki(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},pm=(n,e,t)=>{var m;let r=ps.has(n),o=(m=t==null?void 0:t.toolCall)!=null?m:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=Ae(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Qi=(n,e)=>{var V,ne,Re,Ue,xe,Ie,_e,Se,ve;let t=n.toolCall,r=(V=e==null?void 0:e.toolCall)!=null?V:{},o=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return o;let s=(Re=(ne=e==null?void 0:e.features)==null?void 0:ne.toolCallDisplay)!=null?Re:{},a=s.expandable!==!1,i=a&&ps.has(n.id),{summary:d,previewText:c,isActive:m}=Eh(n,e),f=b("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");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(u.style.color=r.headerTextColor);let v=String((Ue=t.startedAt)!=null?Ue:Date.now()),x=()=>{let re=b("span","");return re.setAttribute("data-tool-elapsed",v),re.textContent=Rs(t),re},I=(Ie=r.renderCollapsedSummary)==null?void 0:Ie.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(xe=s.collapsedMode)!=null?xe:"tool-call",isActive:m,config:e!=null?e:{},elapsed:Rs(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(u.textContent=I,g.appendChild(u)):I instanceof HTMLElement?g.appendChild(I):(u.textContent=d,g.appendChild(u));let M=(_e=s.loadingAnimation)!=null?_e:"none",E=r.activeTextTemplate,F=r.completeTextTemplate,L=m?E:F,R=I instanceof HTMLElement,A=(re,X,ie)=>{let he=ie;for(let oe of X){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(he)),K.textContent=oe===" "?"\xA0":oe,re.appendChild(K),he++}return he},W=(re,X)=>{var K;u.textContent="";let ie=((K=t.name)==null?void 0:K.trim())||"tool",he=Aa(re,ie),oe=0;for(let te of he){let qe=te.styles.length>0?(()=>{let Y=b("span",te.styles.map(le=>`persona-tool-text-${le}`).join(" "));return u.appendChild(Y),Y})():u;if(te.isDuration&&m)qe.appendChild(x());else{let Y=te.isDuration?Rs(t):te.text;X?oe=A(qe,Y,oe):qe.appendChild(document.createTextNode(Y))}}};if(!R)if(m&&M!=="none"){let re=(Se=r.loadingAnimationDuration)!=null?Se:2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),L&&W(L,!1);else if(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${re}ms`),M==="shimmer-color"&&(r.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),L)W(L,!0);else{let X=u.textContent||d;u.textContent="",A(u,X,0)}}else L&&W(L,!1);let N=null;if(a){N=b("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show";let ie=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(N),f.append(g,ie)}else f.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!i&&m&&s.activePreview&&c){let re=(ve=r.renderCollapsedPreview)==null?void 0:ve.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:m,config:e!=null?e:{}});Th(D,re)||(D.textContent=c),D.style.display=""}if(!i&&m&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,D),o;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",r.contentBackgroundColor&&(k.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(k.style.color=r.contentTextColor),r.contentPaddingX&&(k.style.paddingLeft=r.contentPaddingX,k.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(k.style.paddingTop=r.contentPaddingY,k.style.paddingBottom=r.contentPaddingY),t.name){let re=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=t.name,k.appendChild(re)}if(t.args!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.args),re.append(X,ie),k.appendChild(re)}if(t.chunks&&t.chunks.length){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=t.chunks.join(""),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=b("div","persona-space-y-1"),X=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let ie=b("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Gi(ie,r),ie.textContent=rs(t.result),re.append(X,ie),k.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${t.duration}ms`,k.appendChild(re)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",X=Ae(i?"chevron-up":"chevron-down",16,re,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",D.style.display=i?"none":D.textContent||D.childNodes.length?"":"none"})(),o.append(f,D,k),o};var Ya=new Map,kh=n=>{let t=(n.startsWith(ko)?n.slice(ko.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},um=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,mm=(n,e)=>{var r,o,s;let t=(o=(r=um(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ya.get(n))!=null?s:t==="expanded"},gm=(n,e,t)=>{var a,i;let r=um(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Ae(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},fm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=mm(n,t);gm(r,s,t),o.style.display=s?"":"none"};var Za=(n,e)=>{var W,N,D,k,j,V,ne,Re,Ue,xe,Ie,_e,Se,ve,re;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(W=r==null?void 0:r.backgroundColor)!=null?W:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(N=r==null?void 0:r.borderColor)!=null?N:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!t)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(D=r==null?void 0:r.titleColor)!=null?D:"currentColor",m=Ae(d,20,c,2);m&&i.appendChild(m);let f=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),u=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(u.style.color=r.titleColor),u.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",g.appendChild(u),!o){let X=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",t.status),t.status==="approved"?(X.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",X.style.color="var(--persona-palette-colors-success-700, #15803d)",X.textContent="Approved"):t.status==="denied"?(X.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",X.style.color="var(--persona-palette-colors-error-700, #b91c1c)",X.textContent="Denied"):t.status==="timeout"&&(X.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",X.style.color="var(--persona-palette-colors-warning-700, #b45309)",X.textContent="Timeout"),g.appendChild(X)}f.appendChild(g);let x=t.toolType==="webmcp"||t.toolName.startsWith(ko)?yi(t.toolName):void 0,I=(j=r==null?void 0:r.formatDescription)==null?void 0:j.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...x?{displayTitle:x}:{},...t.reason?{reason:t.reason}:{}}),M=!t.toolName,E=I||(M?t.description:`The assistant wants to use \u201C${x!=null?x:kh(t.toolName)}\u201D.`),F=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(F.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(F.style.color=r.descriptionColor),F.textContent=E,f.appendChild(F),t.reason){let X=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let ie=b("span","persona-font-medium");ie.textContent=`${(V=r==null?void 0:r.reasonLabel)!=null?V:"Agent's stated reason:"} `,X.appendChild(ie),X.appendChild(document.createTextNode(t.reason)),f.appendChild(X)}let L=(ne=r==null?void 0:r.detailsDisplay)!=null?ne:"collapsed",R=!!t.description&&!M,A=R||!!t.parameters;if(L!=="hidden"&&A){let X=mm(n.id,e),ie=b("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");ie.type="button",ie.setAttribute("data-expand-header","true"),ie.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let he=b("span");he.setAttribute("data-approval-details-label","true");let oe=b("span","persona-inline-flex persona-items-center");oe.setAttribute("data-approval-details-chevron","true"),ie.append(he,oe),gm(ie,X,e),f.appendChild(ie);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let te=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=t.description,K.appendChild(te)}if(t.parameters){let te=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(te.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.style.fontSize="0.75rem",te.style.lineHeight="1rem",te.textContent=rs(t.parameters),K.appendChild(te)}f.appendChild(K)}if(o){let X=b("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let ie=b("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");ie.type="button",ie.style.backgroundColor=(Re=r==null?void 0:r.approveButtonColor)!=null?Re:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(Ue=r==null?void 0:r.approveButtonTextColor)!=null?Ue:"#ffffff",ie.setAttribute("data-approval-action","approve");let he=Ae("shield-check",14,(xe=r==null?void 0:r.approveButtonTextColor)!=null?xe:"#ffffff",2);he&&(he.style.marginRight="4px",ie.appendChild(he));let oe=document.createTextNode((Ie=r==null?void 0:r.approveLabel)!=null?Ie:"Approve");ie.appendChild(oe);let K=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(_e=r==null?void 0:r.denyButtonColor)!=null?_e:"transparent",K.style.color=(Se=r==null?void 0:r.denyButtonTextColor)!=null?Se:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let te=Ae("shield-x",14,(ve=r==null?void 0:r.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);te&&(te.style.marginRight="4px",K.appendChild(te));let qe=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");K.appendChild(qe),X.append(ie,K),f.appendChild(X)}return a.append(i,f),s.appendChild(a),s};var hm=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let m=(c==null?void 0:c.agentPushed)===!0;if(m||(t=null),!o||!o.length||!m&&(i!=null?i:s?s.getMessages():[]).some(I=>I.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,u=v=>{switch(v){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(v=>{let x=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=u(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",m&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),e.push(x)}),n.appendChild(f),m){let v=JSON.stringify(o);v!==t&&(t=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Ys=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Zs=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Lh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Ph=new Set(["step_start","execution_start"]),Ih=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Wh=new Set(["step_complete","agent_turn_complete"]),Rh=new Set(["flow_complete","agent_complete"]),ym=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),vm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Xn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Bo=(n,e)=>{let t=n[e];return vm(t)?t:void 0};function Xi(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ei(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Hh(n,e){return typeof e.type=="string"?e.type:n}function Bh(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function Dh(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function bm(n){var r,o,s,a,i;let e=Bo(n,"result"),t=[Bo(n,"tokens"),Bo(n,"totalTokens"),e?Bo(e,"tokens"):void 0,Bo(n,"usage"),e?Bo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=Xn(d.output))!=null?r:Xn(d.outputTokens))!=null?o:Xn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Xn(n.outputTokens))!=null?s:Xn(n.completionTokens))!=null?i:e?(a=Xn(e.outputTokens))!=null?a:Xn(e.completionTokens):void 0}function Nh(n){var t,r,o,s,a;let e=Bo(n,"result");return(a=(o=(r=(t=Xn(n.executionTime))!=null?t:Xn(n.executionTimeMs))!=null?r:Xn(n.execution_time))!=null?o:Xn(n.duration))!=null?a:e?(s=Xn(e.executionTime))!=null?s:Xn(e.executionTimeMs):void 0}function Fh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ea=class{constructor(e=Fh){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:ei(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!vm(t)){ym.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Hh(e,t),o=this.now();if(Lh.has(r)){this.startRun(o);return}if(Ph.has(r)){this.run||this.startRun(o);return}if(Ih.has(r)){if(!Dh(r,t))return;let a=Bh(t);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Xi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ei(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Wh.has(r)){if(!this.run)return;let a=this.run,i=bm(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Xi(a.visibleCharCount),m=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:ei(c,m),outputTokens:c,durationMs:m,source:d?"usage":"estimate"};return}if(Rh.has(r)){if(!this.run)return;let a=this.run,i=bm(t),d=i!=null?i:a.exactOutputTokens+Xi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",m=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:ei(d,m),outputTokens:d,durationMs:m,source:c},this.run=null;return}if(ym.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Nh(t);return s!=null?s:r-e.startedAt}};function us(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Oh={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)"}},_h={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},$h=["flowName","stepName","reasoningText","text","name","tool","toolName"],Uh=100;function qh(n,e){let t={...Oh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return _h}function zh(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function jh(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Vh(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Kh(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Gh(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Qh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Xh(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function Jh(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Ji(n,e,t,r,o,s,a,i){var g;let d=o.has(n.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");us(c,(g=r.classNames)==null?void 0:g.eventRow);let m=a.find(u=>u.renderEventStreamRow);if(m!=null&&m.renderEventStreamRow&&i){let u=m.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(u)return c.appendChild(u),c}return c.appendChild(f()),c;function f(){var V,ne;let u=b("div",""),v=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",n.id);let x=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),I=Ae(d?"chevron-down":"chevron-right","14px","currentColor",2);I&&x.appendChild(I);let M=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(V=r.timestampFormat)!=null?V:"relative";M.textContent=E==="relative"?zh(n.timestamp,t):jh(n.timestamp);let F=null;r.showSequenceNumbers!==!1&&(F=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(e+1));let L=qh(n.type,r.badgeColors),R=b("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");R.style.backgroundColor=L.bg,R.style.color=L.text,R.style.borderColor=L.text+"50",R.textContent=n.type;let A=(ne=r.descriptionFields)!=null?ne:$h,W=Vh(n.payload,A),N=null;W&&(N=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),k=b("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"),j=Ae("clipboard","12px","currentColor",1.5);return j&&k.appendChild(j),k.addEventListener("click",async Re=>{Re.stopPropagation(),await Kh(Gh(n)),k.innerHTML="";let Ue=Ae("check","12px","currentColor",1.5);Ue&&k.appendChild(Ue),setTimeout(()=>{k.innerHTML="";let xe=Ae("clipboard","12px","currentColor",1.5);xe&&k.appendChild(xe)},1500)}),v.appendChild(x),v.appendChild(M),F&&v.appendChild(F),v.appendChild(R),N&&v.appendChild(N),v.appendChild(D),v.appendChild(k),u.appendChild(v),d&&u.appendChild(Jh(n,a,i)),u}}function xm(n){var v,x,I,M,E;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",m=(I=i==null?void 0:i.label)!=null?I:"",f=(E=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?E:{},g=s.find(F=>F.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let F=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>u().element,onClose:r});if(F)return{element:F,update:()=>{},destroy:()=>{}}}return u();function u(){let F=f.classNames,L=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");us(L,F==null?void 0:F.panel);let R=[],A="",W="",N=null,D=[],k={},j=0,V=Da(),ne=0,Re=0,Ue=!1,xe=null,Ie=!1,_e=0,Se=new Set,ve=new Map,re="",X="",ie=null,he,oe,K,te,qe,Y=null,le=null,Pe=null;function it(){let G=b("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),de=b("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");us(de,F==null?void 0:F.headerBar);let ke=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(ke.textContent="Events",he=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),he.textContent="0",a){le=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Jn=b("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Jn.textContent="Throughput",Y=b("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"),Y.textContent="-- tok/s",Pe=b("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"),Pe.style.display="none",Pe.style.pointerEvents="none";let An=le,en=Pe,In=()=>{if(!en.textContent)return;let xt=An.getBoundingClientRect(),Nn=G.getBoundingClientRect();en.style.left=`${xt.left-Nn.left}px`,en.style.top=`${xt.bottom-Nn.top+4}px`,en.style.display="block"},yr=()=>{en.style.display="none"};le.addEventListener("mouseenter",In),le.addEventListener("mouseleave",yr),le.appendChild(Jn),le.appendChild(Y)}let vt=b("div","persona-flex-1");oe=b("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 Yt=b("option","");Yt.value="",Yt.textContent="All events",oe.appendChild(Yt),K=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),K.type="button",K.title="Copy All";let pn=Ae("clipboard-copy","12px","currentColor",1.5);pn&&K.appendChild(pn);let Ht=b("span","persona-text-xs");Ht.textContent="Copy All",K.appendChild(Ht),de.appendChild(ke),de.appendChild(he),le&&de.appendChild(le),de.appendChild(vt),de.appendChild(oe),de.appendChild(K);let et=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");us(et,F==null?void 0:F.searchBar);let Rt=Ae("search","14px","var(--persona-muted, #9ca3af)",1.5),ct=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Rt&&ct.appendChild(Rt),te=b("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"),us(te,F==null?void 0:F.searchInput),te.type="text",te.placeholder="Search event payloads...",qe=b("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"),qe.type="button",qe.style.display="none";let Kt=Ae("x","12px","currentColor",2);return Kt&&qe.appendChild(Kt),et.appendChild(ct),et.appendChild(te),et.appendChild(qe),G.appendChild(de),G.appendChild(et),Pe&&G.appendChild(Pe),G}let lt,rt=s.find(G=>G.renderEventStreamToolbar);if(rt!=null&&rt.renderEventStreamToolbar&&o){let G=rt.renderEventStreamToolbar({config:o,defaultRenderer:()=>it(),eventCount:e.getSize(),filteredCount:0,onFilterChange:de=>{A=de,It(),hn()},onSearchChange:de=>{W=de,It(),hn()}});lt=G!=null?G:it()}else lt=it();let Ee=b("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");Ee.style.display="none";function pe(){if(!a||!Y||!le)return;let G=a();Y.textContent=Qh(G);let de=Xh(G);Pe&&(Pe.textContent=de,de||(Pe.style.display="none")),de?le.setAttribute("aria-label",de):le.removeAttribute("aria-label")}let Xe=b("div","persona-flex-1 persona-min-h-0 persona-relative"),J=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=b("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");us(ce,F==null?void 0:F.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",m?"true":"false");let we=Ae(c,"14px","currentColor",2);we&&ce.appendChild(we);let je=b("span","");je.textContent=m,ce.appendChild(je);let Pt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Pt.style.display="none",Xe.appendChild(J),Xe.appendChild(Pt),Xe.appendChild(ce),L.setAttribute("tabindex","0"),L.appendChild(lt),L.appendChild(Ee),L.appendChild(Xe);function Te(){let G=e.getAll(),de={};for(let Ht of G)de[Ht.type]=(de[Ht.type]||0)+1;let ke=Object.keys(de).sort(),vt=ke.length!==D.length||!ke.every((Ht,et)=>Ht===D[et]),Yt=!vt&&ke.some(Ht=>de[Ht]!==k[Ht]),Zt=G.length!==Object.values(k).reduce((Ht,et)=>Ht+et,0);if(!vt&&!Yt&&!Zt||(D=ke,k=de,!oe))return;let pn=oe.value;if(oe.options[0].textContent="All events",vt){for(;oe.options.length>1;)oe.remove(1);for(let Ht of ke){let et=b("option","");et.value=Ht,et.textContent=`${Ht} (${de[Ht]||0})`,oe.appendChild(et)}pn&&ke.includes(pn)?oe.value=pn:pn&&(oe.value="",A="")}else for(let Ht=1;Ht<oe.options.length;Ht++){let et=oe.options[Ht];et.textContent=`${et.value} (${de[et.value]||0})`}}function me(){let G=e.getAll();if(A&&(G=G.filter(de=>de.type===A)),W){let de=W.toLowerCase();G=G.filter(ke=>ke.type.toLowerCase().includes(de)||ke.payload.toLowerCase().includes(de))}return G}function fn(){return A!==""||W!==""}function It(){j=0,ne=0,V.resume(),ce.style.display="none"}function rn(G){Se.has(G)?Se.delete(G):Se.add(G),ie=G;let de=J.scrollTop,ke=V.isFollowing();Ie=!0,V.pause(),hn(),J.scrollTop=de,ke&&V.resume(),Ie=!1}function hr(){return Ro(J,50)}function hn(){Re=Date.now(),Ue=!1,pe(),Te();let G=e.getEvictedCount();G>0?(Ee.textContent=`${G.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",R=me();let de=R.length,ke=e.getSize()>0;he&&(he.textContent=String(e.getSize())),de===0&&ke&&fn()?(Pt.textContent=W?`No events matching '${W}'`:"No events matching filter",Pt.style.display="",J.style.display="none"):(Pt.style.display="none",J.style.display=""),K&&(K.title=fn()?`Copy Filtered (${de})`:"Copy All"),d&&!V.isFollowing()&&de>j&&(ne+=de-j,je.textContent=m?`${m}${ne>0?` (${ne})`:""}`:"",ce.style.display=""),j=de;let vt=e.getAll(),Yt=vt.length>0?vt[0].timestamp:0,Zt=new Set(R.map(et=>et.id));for(let et of Se)Zt.has(et)||Se.delete(et);let pn=A!==re||W!==X,Ht=ve.size===0&&R.length>0;if(pn||Ht||R.length===0){J.innerHTML="",ve.clear();let et=document.createDocumentFragment();for(let Rt=0;Rt<R.length;Rt++){let ct=Ji(R[Rt],Rt,Yt,f,Se,rn,s,o);ve.set(R[Rt].id,ct),et.appendChild(ct)}J.appendChild(et),re=A,X=W,ie=null}else{if(ie!==null){let Rt=ve.get(ie);if(Rt&&Rt.parentNode===J){let ct=R.findIndex(Kt=>Kt.id===ie);if(ct>=0){let Kt=Ji(R[ct],ct,Yt,f,Se,rn,s,o);J.insertBefore(Kt,Rt),Rt.remove(),ve.set(ie,Kt)}}ie=null}let et=new Set(R.map(Rt=>Rt.id));for(let[Rt,ct]of ve)et.has(Rt)||(ct.remove(),ve.delete(Rt));for(let Rt=0;Rt<R.length;Rt++){let ct=R[Rt];if(!ve.has(ct.id)){let Kt=Ji(ct,Rt,Yt,f,Se,rn,s,o);ve.set(ct.id,Kt),J.appendChild(Kt)}}}V.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ve(){if(Date.now()-Re>=Uh){xe!==null&&(cancelAnimationFrame(xe),xe=null),hn();return}Ue||(Ue=!0,xe=requestAnimationFrame(()=>{xe=null,hn()}))}let T=(G,de)=>{if(!K)return;K.innerHTML="";let ke=Ae(G,"12px","currentColor",1.5);ke&&K.appendChild(ke);let vt=b("span","persona-text-xs");vt.textContent="Copy All",K.appendChild(vt),setTimeout(()=>{K.innerHTML="";let Yt=Ae("clipboard-copy","12px","currentColor",1.5);Yt&&K.appendChild(Yt);let Zt=b("span","persona-text-xs");Zt.textContent="Copy All",K.appendChild(Zt),K.disabled=!1},de)},ue=async()=>{if(K){K.disabled=!0;try{let G;fn()?G=R:t?(G=await t(),G.length===0&&(G=e.getAll())):G=e.getAll();let de=G.map(ke=>{try{return JSON.parse(ke.payload)}catch{return ke.payload}});await navigator.clipboard.writeText(JSON.stringify(de,null,2)),T("check",1500)}catch{T("x",1500)}}},Le=()=>{oe&&(A=oe.value,It(),hn())},Me=()=>{!te||!qe||(qe.style.display=te.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{W=te.value,It(),hn()},150))},He=()=>{!te||!qe||(te.value="",W="",qe.style.display="none",N&&clearTimeout(N),It(),hn())},Ze=()=>{if(Ie)return;let G=J.scrollTop,{action:de,nextLastScrollTop:ke}=Na({following:V.isFollowing(),currentScrollTop:G,lastScrollTop:_e,nearBottom:hr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});_e=ke,de==="resume"?(V.resume(),ne=0,ce.style.display="none"):de==="pause"&&(V.pause(),d&&(je.textContent=m,ce.style.display=""))},Ge=G=>{let de=Fa({following:V.isFollowing(),deltaY:G.deltaY,nearBottom:hr(),resumeWhenNearBottom:!0});de==="pause"?(V.pause(),d&&(je.textContent=m,ce.style.display="")):de==="resume"&&(V.resume(),ne=0,ce.style.display="none")},ut=()=>{d&&(J.scrollTop=J.scrollHeight,V.resume(),ne=0,ce.style.display="none")},Wt=G=>{let de=G.target;if(!de||de.closest("button"))return;let ke=de.closest("[data-event-id]");if(!ke)return;let vt=ke.getAttribute("data-event-id");vt&&rn(vt)},q=G=>{if((G.metaKey||G.ctrlKey)&&G.key==="f"){G.preventDefault(),te==null||te.focus(),te==null||te.select();return}G.key==="Escape"&&(te&&document.activeElement===te?(He(),te.blur(),L.focus()):r&&r())};K&&K.addEventListener("click",ue),oe&&oe.addEventListener("change",Le),te&&te.addEventListener("input",Me),qe&&qe.addEventListener("click",He),J.addEventListener("scroll",Ze),J.addEventListener("wheel",Ge,{passive:!0}),J.addEventListener("click",Wt),ce.addEventListener("click",ut),L.addEventListener("keydown",q);function ot(){N&&clearTimeout(N),xe!==null&&(cancelAnimationFrame(xe),xe=null),Ue=!1,ve.clear(),K&&K.removeEventListener("click",ue),oe&&oe.removeEventListener("change",Le),te&&te.removeEventListener("input",Me),qe&&qe.removeEventListener("click",He),J.removeEventListener("scroll",Ze),J.removeEventListener("wheel",Ge),J.removeEventListener("click",Wt),ce.removeEventListener("click",ut),L.removeEventListener("keydown",q)}return{element:L,update:Ve,destroy:ot}}}function wm(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=t;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let u=document.createElement("span");u.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(u)}else f.textContent=a;if(c.append(m,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${t}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Cm=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",m=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>wm(n,e)});if(m)return m}return wm(n,e)};var Yi=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Do=new Yi;Do.register("PersonaArtifactCard",Cm);function Yh(n){var o;let e=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=b("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function Am(n,e){var oe,K,te,qe;let t=(K=(oe=n.features)==null?void 0:oe.artifacts)==null?void 0:K.layout,o=((te=t==null?void 0:t.toolbarPreset)!=null?te:"default")==="document",s=(qe=t==null?void 0:t.panePadding)==null?void 0:qe.trim(),a=n.markdown?ga(n.markdown):null,i=fa(n.sanitize),d=Y=>{let le=a?a(Y):so(Y);return i?i(le):le},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),j==null||j.hide()};c&&c.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let f=b("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");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let u=b("span","persona-text-xs persona-font-medium persona-truncate");u.textContent="Artifacts";let v=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let x="rendered",I=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),E=o?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),F=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),L=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,R=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,A=t==null?void 0:t.documentToolbarCopyMenuItems,W=!!(R&&A&&A.length>0),N=null,D,k=null,j=null;if(o&&(L||R)&&!W){if(D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let Y=Ae("chevron-down",14,"currentColor",2);Y&&D.appendChild(Y)}}else o&&W?(N=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),D=L?$i({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Cn({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"}}),N.append(D,k)):o?D=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):D=Cn({icon:"copy",label:"Copy"});let V=o?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),ne=o?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),Re=()=>{var lt,rt,Ee;let Y=(lt=ve.find(pe=>pe.id===re))!=null?lt:ve[ve.length-1],le=(rt=Y==null?void 0:Y.id)!=null?rt:null,Pe=(Y==null?void 0:Y.artifactType)==="markdown"&&(Ee=Y.markdown)!=null?Ee:"",it=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Pe,jsonPayload:it,id:le}},Ue=async()=>{var lt;let{markdown:Y,jsonPayload:le}=Re(),Pe=(lt=ve.find(rt=>rt.id===re))!=null?lt:ve[ve.length-1],it=(Pe==null?void 0:Pe.artifactType)==="markdown"?Y:Pe?le:"";try{await navigator.clipboard.writeText(it)}catch{}};if(D.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&W){let{markdown:le,jsonPayload:Pe,id:it}=Re();try{await Y({actionId:"primary",artifactId:it,markdown:le,jsonPayload:Pe})}catch{}return}await Ue()}),k&&(A!=null&&A.length)){let Y=()=>{var Pe;return(Pe=f.closest("[data-persona-root]"))!=null?Pe:document.body},le=()=>{j=cs({items:A.map(Pe=>({id:Pe.id,label:Pe.label})),onSelect:async Pe=>{let{markdown:it,jsonPayload:lt,id:rt}=Re(),Ee=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Ee?await Ee({actionId:Pe,artifactId:rt,markdown:it,jsonPayload:lt}):Pe==="markdown"||Pe==="md"?await navigator.clipboard.writeText(it):Pe==="json"||Pe==="source"?await navigator.clipboard.writeText(lt):await navigator.clipboard.writeText(it||lt)}catch{}},anchor:N!=null?N:k,position:"bottom-right",portal:Y()})};f.isConnected?le():requestAnimationFrame(le),k.addEventListener("click",Pe=>{Pe.stopPropagation(),j==null||j.toggle()})}V.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}ie()}),ne.addEventListener("click",()=>{var Y;m(),(Y=e.onDismiss)==null||Y.call(e)});let xe=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),E.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",xe(),ie()}),E.addEventListener("click",()=>{x="source",xe(),ie()});let Ie=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),I.append(M,E),N?F.append(N,V,ne):F.append(D,V,ne),g.append(I,Ie,F),xe()):(g.appendChild(u),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let _e=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Se=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(_e.style.paddingLeft=s,_e.style.paddingRight=s,Se.style.padding=s),f.appendChild(g),f.appendChild(_e),f.appendChild(Se);let ve=[],re=null,X=!1,ie=()=>{var it,lt,rt,Ee;let Y=o&&ve.length<=1;_e.classList.toggle("persona-hidden",Y),_e.replaceChildren();for(let pe of ve){let Xe=b("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");Xe.type="button",Xe.textContent=pe.title||pe.id.slice(0,8),pe.id===re&&Xe.classList.add("persona-bg-persona-container","persona-border-persona-border"),Xe.addEventListener("click",()=>e.onSelect(pe.id)),_e.appendChild(Xe)}Se.replaceChildren();let le=re&&ve.find(pe=>pe.id===re)||ve[ve.length-1];if(!le)return;if(o){let pe=le.artifactType==="markdown"?"MD":(it=le.component)!=null?it:"Component",J=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ie.textContent=`${J} \xB7 ${pe}`}else u.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&x==="source"){let Xe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Xe.textContent=(lt=le.markdown)!=null?lt:"",Se.appendChild(Xe);return}let pe=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");pe.innerHTML=d((rt=le.markdown)!=null?rt:""),Se.appendChild(pe);return}let Pe=le.component?Do.get(le.component):void 0;if(Pe){let Xe={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=Pe((Ee=le.props)!=null?Ee:{},Xe);if(J){Se.appendChild(J);return}}catch{}}Se.appendChild(Yh(le))},he=()=>{var le;let Y=ve.length>0;if(f.classList.toggle("persona-hidden",!Y),c){let Pe=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,lt=((le=Pe==null?void 0:Pe.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&<&&X?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(Y){var le,Pe,it;ve=Y.artifacts,re=(it=(Pe=Y.selectedId)!=null?Pe:(le=Y.artifacts[Y.artifacts.length-1])==null?void 0:le.id)!=null?it:null,ve.length>0&&(X=!0),ie(),he()},setMobileOpen(Y){X=Y,!Y&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):he()}}}function ar(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function Sm(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!ar(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function Zh(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ti(n,e){var d,c,m,f,g,u,v,x,I,M;if(!ar(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),Zh(n),Sm(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(m=t==null?void 0:t.splitGap)!=null?m:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=t==null?void 0:t.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(g=t==null?void 0:t.paneMaxWidth)!=null?g:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(u=t==null?void 0:t.paneBackground)==null?void 0:u.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(x=t==null?void 0:t.documentToolbarIconColor)==null?void 0:x.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(I=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:I.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:M.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Sm(n,e)}var Tm=["panel","seamless"];function ni(n,e){var i,d,c,m,f,g;for(let u of Tm)n.classList.remove(`persona-artifact-appearance-${u}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!ar(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Tm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(m=t==null?void 0:t.paneBorderRadius)==null?void 0:m.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=t==null?void 0:t.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let u=((g=t.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;u&&n.style.setProperty("--persona-artifact-unified-outer-radius",u)}}function Mm(n,e){var t,r,o;return!e||!ar(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function ey(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function ty(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function ny(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function ry(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Em(n,e){var a;let r=(a=(e.getComputedStyle(n).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function km(n,e,t,r,o,s){let a=ey(o,200),i=ry(e,t,r,200);i=Math.max(a,i);let d=ty(s);return d!==null&&(i=Math.min(i,d)),ny(n,a,i)}var Lm={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"}},Zi=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,I;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Lm[a])!=null?x:Lm.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let M=b("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let m=document.createElement("form");m.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var A,W;let E=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${M.name}`;let F=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=M.label,E.appendChild(F);let L=(A=M.type)!=null?A:"text",R;L==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=L),R.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",R.id=`${e.id}-${a}-${M.name}`,R.name=M.name,R.placeholder=(W=M.placeholder)!=null?W:"",M.required&&(R.required=!0),E.appendChild(R),m.appendChild(E)});let f=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),u=b("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");u.type="submit",u.textContent=(I=i.submitLabel)!=null?I:"Submit",f.appendChild(g),f.appendChild(u),m.appendChild(f),s.replaceChildren(d,m),m.addEventListener("submit",async M=>{var R,A;M.preventDefault();let E=(R=t.formEndpoint)!=null?R:"/form",F=new FormData(m),L={};F.forEach((W,N)=>{L[N]=W}),L.type=a,u.disabled=!0,g.textContent="Submitting\u2026";try{let W=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!W.ok)throw new Error(`Form submission failed (${W.status})`);let N=await W.json();g.textContent=(A=N.message)!=null?A:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(W){g.textContent=W instanceof Error?W.message:"Something went wrong. Please try again."}finally{u.disabled=!1}})})};var el=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},tl=new el;var Pm=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var oy=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},sy=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},rl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=oy(n),t=sy(e);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},nl=n=>typeof n=="string"?n:n==null?"":String(n),ta={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:nl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=nl(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:nl(t.text)}}},Im=n=>Array.isArray(n)?n.map(e=>String(e)):[],ol=n=>{let e=new Set(Im(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Im(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,m)=>c||(m==null?void 0:m({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let m=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:m});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",m)}return{text:"",persist:!0}},syncFromMetadata:t}};var ay=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},iy=n=>n.map(e=>({...e,streaming:!1})),ly=n=>n.map(e=>({...e,status:"complete"})),Wm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?ay(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?iy(t.messages):void 0,artifacts:t.artifacts?ly(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var sl=require("partial-json");function Rm(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Do.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function Hm(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function Bm(n){let e=Hm(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Dm(n){let e=Hm(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var cy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Nm(n){let{onSubmit:e,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=cy}=n,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-csat",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let u=document.createElement("div");u.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,u.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,u.appendChild(x),g.appendChild(u);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];for(let A=1;A<=5;A++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),W.title=c[A-1],W.dataset.rating=String(A),W.innerHTML=`
|
|
27
|
+
`,n.addEventListener("click",e);let r=s=>{var k,E,I,A,L,O,_,H,U,F,ee,Ae,pe;let a=(k=s.launcher)!=null?k:{},i=bn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let te=(E=a.title)!=null?E:"Chat Assistant";d.textContent=te,d.setAttribute("title",te)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let te=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=te,c.setAttribute("title",te)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let te=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=te,f.style.width=te,f.innerHTML="",a.agentIconName){let xe=parseFloat(te)||24,We=he(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);We?(f.appendChild(We),f.style.display=""):(f.textContent=(L=a.agentIconText)!=null?L:"\u{1F4AC}",f.style.display="")}else a.iconUrl?f.style.display="none":(f.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",f.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let te=(_=a.agentIconSize)!=null?_:"40px";g.style.height=te,g.style.width=te,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let te=(H=a.callToActionIconSize)!=null?H:"32px";m.style.height=te,m.style.width=te,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let We=parseFloat(te)||24,le=Math.max(We-xe,8),me=he(a.callToActionIconName,le,"currentColor",2);me?m.appendChild(me):m.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else m.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let x=a.position&&yr[a.position]?yr[a.position]:yr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${v} ${x}`,i||(n.style.zIndex=String((ee=a.zIndex)!=null?ee:Sn));let R="1px solid var(--persona-border, #e5e7eb)",T="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=(Ae=a.border)!=null?Ae:R,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",e),n.remove()};return t&&r(t),{element:n,update:r,destroy:o}};var gm=({config:t,showClose:e})=>{let{wrapper:n,panel:r,pillRoot:o}=um(t),s=mm(t,e),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},ji=({config:t,plugins:e,onToggle:n})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:t,defaultRenderer:()=>qi(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=qi(t,n);return{instance:o,element:o.element}};var Ah=t=>{switch(t){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}},Sh=(t,e)=>{if(!t)return null;let n=Ah(t);if(n===null)return null;let r=e==null?void 0:e[t],o=r!==void 0?r:n;return o||null},Th=(t,e)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Eh=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Vi=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Ki=320,hm=320,Mh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),kh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Lh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Ph=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Ih=(t,e,n)=>{if(t.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return t.forEach((i,d)=>{var f;let c=y("img");c.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ki}px`,c.style.maxHeight=`${hm}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Eh(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Wh=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(r=>{if(!Vi(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ki}px`,e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Rh=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(r=>{if(!Vi(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ki}px`,o.style.maxHeight=`${hm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Hh=t=>{if(t.length===0)return null;try{let e=y("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(r=>{if(!Vi(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},na=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(r),t.appendChild(o),t},Bh=(t,e,n)=>{let r={config:n!=null?n:{},streaming:!0,location:t,defaultRenderer:na};if(e){let o=e(r);if(o!==null)return o}return na()},Dh=(t,e)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?t.userAvatar:t.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},fm=(t,e,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(t.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Nh=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Fh=(t,e,n)=>{var x,v,M,R,T,k,E;let r=(x=e.showCopy)!=null?x:!0,o=(v=e.showUpvote)!=null?v:!0,s=(M=e.showDownvote)!=null?M:!0,a=(R=e.showReadAloud)!=null?R:!1;if(!r&&!o&&!s&&!a){let I=y("div");return I.style.display="none",I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id),I}let i=(T=e.visibility)!=null?T:"hover",d=(k=e.align)!=null?k:"right",c=(E=e.layout)!=null?E:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${t.id}`,g.setAttribute("data-actions-for",t.id);let m=(I,A,L)=>{let O=Tn({icon:I,label:A,size:14,className:"persona-message-action-btn"});return O.setAttribute("data-action",L),O};return r&&g.appendChild(m("copy","Copy message","copy")),a&&g.appendChild(m("volume-2","Read aloud","read-aloud")),o&&g.appendChild(m("thumbs-up","Upvote","upvote")),s&&g.appendChild(m("thumbs-down","Downvote","downvote")),g},Gi=(t,e,n,r,o,s)=>{var re,oe,de,ze,Fe,G,X,ve,Y,ie,Ee,Je,nt,wt,dt,tt,He;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,u=(oe=d==null?void 0:d.show)!=null?oe:!1,f=(de=c==null?void 0:c.show)!=null?de:!1,g=(ze=d==null?void 0:d.position)!=null?ze:"left",m=(Fe=c==null?void 0:c.position)!=null?Fe:"below",x=Nh(t.role,i),v=y("div",x.join(" "));v.id=`bubble-${t.id}`,v.setAttribute("data-message-id",t.id),v.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Mh(t),R=(X=(G=t.content)==null?void 0:G.trim())!=null?X:"",k=M.length>0&&R===La,E=Ua((Y=(ve=s==null?void 0:s.widgetConfig)==null?void 0:ve.features)==null?void 0:Y.streamAnimation),I=(Je=(Ee=(ie=s==null?void 0:s.widgetConfig)==null?void 0:ie.features)==null?void 0:Ee.streamAnimation)==null?void 0:Je.plugins,A=t.role==="assistant"&&E.type!=="none"?Qs(E.type,I):null,L=t.role==="assistant"&&((nt=A==null?void 0:A.isAnimating)==null?void 0:nt.call(A,t))===!0,O=t.role==="assistant"&&A!==null&&(!!t.streaming||L);O&&(A!=null&&A.bubbleClass)&&v.classList.add(A.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),t.streaming&&_.classList.add("persona-content-streaming"),O&&A&&(A.containerClass&&_.classList.add(A.containerClass),_.style.setProperty("--persona-stream-step",`${E.speed}ms`),_.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let H=O?za((wt=t.content)!=null?wt:"",E.buffer,A,t,!!t.streaming):(dt=t.content)!=null?dt:"",U=e({text:H,message:t,streaming:!!t.streaming,raw:t.rawContent}),F=U;O&&(A==null?void 0:A.wrap)==="char"?F=Xs(U,"char",t.id,{skipTags:A.skipTags}):O&&(A==null?void 0:A.wrap)==="word"&&(F=Xs(U,"word",t.id,{skipTags:A.skipTags}));let ee=null;if(k?(ee=document.createElement("div"),ee.innerHTML=F,ee.style.display="none",_.appendChild(ee)):_.innerHTML=F,O&&(A!=null&&A.useCaret)&&!k&&R){let Q=qa(),Ve=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),je=Ve[Ve.length-1];if(je!=null&&je.parentNode)je.parentNode.insertBefore(Q,je.nextSibling);else{let we=_.lastElementChild;we?we.appendChild(Q):_.appendChild(Q)}}if(f&&m==="inline"&&t.createdAt){let Q=fm(t,c,"span");Q.classList.add("persona-timestamp-inline");let Ve=_.lastElementChild;Ve?Ve.appendChild(Q):_.appendChild(Q)}if(M.length>0){let Q=Ih(M,!k&&!!R,()=>{k&&ee&&(ee.style.display="")});Q?v.appendChild(Q):k&&ee&&(ee.style.display="")}let Ae=kh(t);if(Ae.length>0){let Q=Wh(Ae);Q&&v.appendChild(Q)}let pe=Lh(t);if(pe.length>0){let Q=Rh(pe);Q&&v.appendChild(Q)}let te=Ph(t);if(te.length>0){let Q=Hh(te);Q&&v.appendChild(Q)}if(v.appendChild(_),f&&m==="below"&&t.createdAt){let Q=fm(t,c);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let xe=t.role==="assistant"?Sh(t.stopReason,(He=(tt=s==null?void 0:s.widgetConfig)==null?void 0:tt.copy)==null?void 0:He.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Q=!!(H&&H.trim()),Ve=E.placeholder==="skeleton",je=Ve&&E.buffer==="line"&&Q;if(Q)je&&v.appendChild(Js());else if(Ve)v.appendChild(Js());else{let we=Bh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&v.appendChild(we)}}if(xe&&t.stopReason&&!t.streaming&&(R||(_.style.display="none"),v.appendChild(Th(t.stopReason,xe))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=Fh(t,r,o);v.appendChild(Q)}if(!u||t.role==="system")return v;let le=y("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),me=Dh(d,t.role);return g==="right"||g==="left"&&t.role==="user"?le.append(v,me):le.append(me,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),le};var fs=new Set,Oh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),_h=(t,e)=>{var r,o;let n=(o=(r=t.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
+
`):""},ym=(t,e)=>{let n=fs.has(t),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=he(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Qi=(t,e)=>{var pe,te,xe,We,le,me,re,oe,de,ze,Fe;let n=t.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let o=(te=(pe=e==null?void 0:e.features)==null?void 0:pe.reasoningDisplay)!=null?te:{},s=o.expandable!==!1,a=s&&fs.has(t.id),i=n.status!=="complete",d=_h(t,(xe=o.previewMaxLines)!=null?xe:3),c=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let u=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=(We=e==null?void 0:e.reasoning)!=null?We:{},x=String((le=n.startedAt)!=null?le:Date.now()),v=()=>{let G=y("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=Ta(n),G},M=(me=m.renderCollapsedSummary)==null?void 0:me.call(m,{message:t,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ta(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(f.textContent=M,u.appendChild(f)):M instanceof HTMLElement?u.appendChild(M):(f.textContent=g,u.appendChild(f));let R=y("span","persona-text-xs persona-text-persona-primary");R.textContent=hu(n),u.appendChild(R);let T=(re=o.loadingAnimation)!=null?re:"none",k=m.activeTextTemplate,E=m.completeTextTemplate,I=i?k:E,A=M instanceof HTMLElement,L=(G,X,ve)=>{let Y=ve;for(let ie of X){let Ee=y("span","persona-tool-char");Ee.style.setProperty("--char-index",String(Y)),Ee.textContent=ie===" "?"\xA0":ie,G.appendChild(Ee),Y++}return Y},O=(G,X)=>{f.textContent="";let ve=Ea(G,""),Y=0;for(let ie of ve){let Ee=ie.styles.length>0?(()=>{let Je=y("span",ie.styles.map(nt=>`persona-tool-text-${nt}`).join(" "));return f.appendChild(Je),Je})():f;if(ie.isDuration&&i)Ee.appendChild(v());else{let Je=ie.isDuration?Ta(n):ie.text;X?Y=L(Ee,Je,Y):Ee.appendChild(document.createTextNode(Je))}}};if(!A&&I)if(R.style.display="none",f.style.display="",i&&T!=="none"){let G=(oe=m.loadingAnimationDuration)!=null?oe:2e3;f.setAttribute("data-preserve-animation","true"),T==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),O(I,!1)):(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),O(I,!0))}else O(I,!1);else if(!A&&i&&T!=="none"){f.style.display="";let G=(de=m.loadingAnimationDuration)!=null?de:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let X=f.textContent||g;f.textContent="",L(f,X,0)}n.status==="complete"&&(f.style.display="none")}else A||(n.status==="complete"?f.style.display="none":f.style.display="");let _=null;if(s){_=y("div","persona-flex persona-items-center");let X=he(a?"chevron-up":"chevron-down",16,"currentColor",2);X?_.appendChild(X):_.textContent=a?"Hide":"Show";let ve=y("div","persona-flex persona-items-center persona-ml-auto");ve.append(_),c.append(u,ve)}else c.append(u);let H=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let G=(Fe=(ze=e==null?void 0:e.reasoning)==null?void 0:ze.renderCollapsedPreview)==null?void 0:Fe.call(ze,{message:t,reasoning:n,defaultPreview:d,isActive:i,config:e!=null?e:{}});Oh(H,G)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,H),r;let U=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");U.style.display=a?"":"none";let F=n.chunks.join(""),ee=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ee.textContent=F||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),U.appendChild(ee),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let X=he(a?"chevron-up":"chevron-down",16,"currentColor",2);X?_.appendChild(X):_.textContent=a?"Hide":"Show"}U.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(c,H,U),r};var hs=new Set,$h=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Uh=(t,e)=>{var s;let n=t.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
|
|
29
|
+
`);let o=go(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
30
|
+
`):""},Xi=(t,e)=>{var n,r,o;t.style.backgroundColor=(n=e.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",t.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",t.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},zh=(t,e)=>{var u,f,g,m,x;let n=t.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=Uh(t,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?yu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((x=n.name)==null?void 0:x.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Pi(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Pi(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},bm=(t,e,n)=>{var u;let r=hs.has(t),o=(u=n==null?void 0:n.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let f=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=he(r?"chevron-up":"chevron-down",16,f,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Ji=(t,e)=>{var F,ee,Ae,pe,te,xe,We,le,me;let n=t.toolCall,r=(F=e==null?void 0:e.toolCall)!=null?F:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ae=(ee=e==null?void 0:e.features)==null?void 0:ee.toolCallDisplay)!=null?Ae:{},a=s.expandable!==!1,i=a&&hs.has(t.id),{summary:d,previewText:c,isActive:u}=zh(t,e),f=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");f.type="button",a&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(f.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(f.style.paddingLeft=r.headerPaddingX,f.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(f.style.paddingTop=r.headerPaddingY,f.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),m=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let x=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let re=y("span","");return re.setAttribute("data-tool-elapsed",x),re.textContent=Fs(n),re},M=(xe=r.renderCollapsedSummary)==null?void 0:xe.call(r,{message:t,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(te=s.collapsedMode)!=null?te:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Fs(n),createElapsedElement:v});typeof M=="string"&&M.trim()?(m.textContent=M,g.appendChild(m)):M instanceof HTMLElement?g.appendChild(M):(m.textContent=d,g.appendChild(m));let R=(We=s.loadingAnimation)!=null?We:"none",T=r.activeTextTemplate,k=r.completeTextTemplate,E=u?T:k,I=M instanceof HTMLElement,A=(re,oe,de)=>{let ze=de;for(let Fe of oe){let G=y("span","persona-tool-char");G.style.setProperty("--char-index",String(ze)),G.textContent=Fe===" "?"\xA0":Fe,re.appendChild(G),ze++}return ze},L=(re,oe)=>{var G;m.textContent="";let de=((G=n.name)==null?void 0:G.trim())||"tool",ze=Ea(re,de),Fe=0;for(let X of ze){let ve=X.styles.length>0?(()=>{let Y=y("span",X.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(Y),Y})():m;if(X.isDuration&&u)ve.appendChild(v());else{let Y=X.isDuration?Fs(n):X.text;oe?Fe=A(ve,Y,Fe):ve.appendChild(document.createTextNode(Y))}}};if(!I)if(u&&R!=="none"){let re=(le=r.loadingAnimationDuration)!=null?le:2e3;if(m.setAttribute("data-preserve-animation","true"),R==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),E&&L(E,!1);else if(m.classList.add(`persona-tool-loading-${R}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),R==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)L(E,!0);else{let oe=m.textContent||d;m.textContent="",A(m,oe,0)}}else E&&L(E,!1);let O=null;if(a){O=y("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=he(i?"chevron-up":"chevron-down",16,re,2);oe?O.appendChild(oe):O.textContent=i?"Hide":"Show";let de=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(O),f.append(g,de)}else f.append(g);let _=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&u&&s.activePreview&&c){let re=(me=r.renderCollapsedPreview)==null?void 0:me.call(r,{message:t,toolCall:n,defaultPreview:c,isActive:u,config:e!=null?e:{}});$h(_,re)||(_.textContent=c),_.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,_),o;let H=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let re=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,H.appendChild(re)}if(n.args!==void 0){let re=y("div","persona-space-y-1"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Arguments";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Xi(de,r),de.textContent=go(n.args),re.append(oe,de),H.appendChild(re)}if(n.chunks&&n.chunks.length){let re=y("div","persona-space-y-1"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Activity";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Xi(de,r),de.textContent=n.chunks.join(""),re.append(oe,de),H.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=y("div","persona-space-y-1"),oe=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Result";let de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Xi(de,r),de.textContent=go(n.result),re.append(oe,de),H.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,H.appendChild(re)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=he(i?"chevron-up":"chevron-down",16,re,2);oe?O.appendChild(oe):O.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),o.append(f,_,H),o};var Fo=new Map,ti=t=>{let n=(t.startsWith(zr)?t.slice(zr.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},vm=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,xm=(t,e)=>{var r,o,s;let n=(o=(r=vm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Fo.get(t))!=null?s:n==="expanded"},wm=(t,e,n)=>{var a,i;let r=vm(n);t.setAttribute("aria-expanded",e?"true":"false");let o=t.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=he(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Cm=(t,e,n)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=xm(t,n);wm(r,s,n),o.style.display=s?"":"none"};var ni=(t,e)=>{var L,O,_,H,U,F,ee,Ae,pe,te,xe,We,le,me,re;let n=t.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(L=r==null?void 0:r.backgroundColor)!=null?L:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(O=r==null?void 0:r.borderColor)!=null?O:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(_=r==null?void 0:r.titleColor)!=null?_:"currentColor",u=he(d,20,c,2);u&&i.appendChild(u);let f=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),m=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(m),!o){let oe=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");oe.setAttribute("data-approval-status",n.status),n.status==="approved"?(oe.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",oe.style.color="var(--persona-palette-colors-success-700, #15803d)",oe.textContent="Approved"):n.status==="denied"?(oe.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",oe.style.color="var(--persona-palette-colors-error-700, #b91c1c)",oe.textContent="Denied"):n.status==="timeout"&&(oe.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",oe.style.color="var(--persona-palette-colors-warning-700, #b45309)",oe.textContent="Timeout"),g.appendChild(oe)}f.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(zr)?Rs(n.toolName):void 0,M=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),R=!n.toolName,T=M||(R?n.description:`The assistant wants to use \u201C${v!=null?v:ti(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=T,f.appendChild(k),n.reason){let oe=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");oe.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?oe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let de=y("span","persona-font-medium");de.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,oe.appendChild(de),oe.appendChild(document.createTextNode(n.reason)),f.appendChild(oe)}let E=(ee=r==null?void 0:r.detailsDisplay)!=null?ee:"collapsed",I=!!n.description&&!R,A=I||!!n.parameters;if(E!=="hidden"&&A){let oe=xm(t.id,e),de=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");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let ze=y("span");ze.setAttribute("data-approval-details-label","true");let Fe=y("span","persona-inline-flex persona-items-center");Fe.setAttribute("data-approval-details-chevron","true"),de.append(ze,Fe),wm(de,oe,e),f.appendChild(de);let G=y("div");if(G.setAttribute("data-approval-details","true"),G.style.display=oe?"":"none",I){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=n.description,G.appendChild(X)}if(n.parameters){let X=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=go(n.parameters),G.appendChild(X)}f.appendChild(G)}if(o){let oe=y("div","persona-flex persona-gap-2 persona-mt-2");oe.setAttribute("data-approval-buttons","true");let de=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");de.type="button",de.style.backgroundColor=(Ae=r==null?void 0:r.approveButtonColor)!=null?Ae:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let ze=he("shield-check",14,(te=r==null?void 0:r.approveButtonTextColor)!=null?te:"#ffffff",2);ze&&(ze.style.marginRight="4px",de.appendChild(ze));let Fe=document.createTextNode((xe=r==null?void 0:r.approveLabel)!=null?xe:"Approve");de.appendChild(Fe);let G=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");G.type="button",G.style.backgroundColor=(We=r==null?void 0:r.denyButtonColor)!=null?We:"transparent",G.style.color=(le=r==null?void 0:r.denyButtonTextColor)!=null?le:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let X=he("shield-x",14,(me=r==null?void 0:r.denyButtonTextColor)!=null?me:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",G.appendChild(X));let ve=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");G.appendChild(ve),oe.append(de,G),f.appendChild(oe)}return a.append(i,f),s.appendChild(a),s};function qh(t){var n,r;let e=(n=t.getRootNode)==null?void 0:n.call(t);return e instanceof ShadowRoot?e:((r=t.ownerDocument)!=null?r:document).body}function Am(t){var v;let{anchor:e,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=t,c=(v=t.container)!=null?v:qh(e),u=!1,f=null,g=()=>{if(!u)return;let M=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${M.width}px`);let R=r==="top-start"||r==="top-end"?M.top-o-n.getBoundingClientRect().height:M.bottom+o,T=r==="bottom-end"||r==="top-end"?M.right-n.getBoundingClientRect().width:M.left;n.style.top=`${R}px`,n.style.left=`${T}px`},m=()=>{u&&(u=!1,f&&(f(),f=null),n.remove())},x=()=>{var I,A,L;if(u)return;u=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),g();let M=(A=((I=e.ownerDocument)!=null?I:document).defaultView)!=null?A:window,R=(L=e.ownerDocument)!=null?L:document,T=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}g()},k=O=>{let _=typeof O.composedPath=="function"?O.composedPath():[];_.includes(n)||_.includes(e)||(m(),d==null||d("outside"))},E=M.setTimeout(()=>{R.addEventListener("pointerdown",k,!0)},0);M.addEventListener("scroll",T,!0),M.addEventListener("resize",T),f=()=>{M.clearTimeout(E),R.removeEventListener("pointerdown",k,!0),M.removeEventListener("scroll",T,!0),M.removeEventListener("resize",T)},i==null||i()};return{get isOpen(){return u},open:x,close:m,toggle:()=>u?m():x(),reposition:g,destroy:m}}function Sm(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var jh=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Tm=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let r=t.popovers.get(e);r&&(r.destroy(),t.popovers.delete(e))},Oo=(t,e)=>{Tm(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Vh=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Kh=(t,e)=>{var r,o;let n=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=Fo.get(t))!=null?o:n==="expanded"},Yi=t=>{let e=y("span","persona-approval-kbd");return e.textContent=t,e},Gh=(t,e)=>{var c,u;let n=y("span","persona-approval-title");e!=null&&e.titleColor&&(n.style.color=e.titleColor);let o=t.toolType==="webmcp"||t.toolName.startsWith(zr)?Rs(t.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:t.toolName,toolType:t.toolType,description:(c=t.description)!=null?c:"",parameters:t.parameters,...o?{displayTitle:o}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:ti(t.toolName),i=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let f=document.createElement("strong");f.textContent=i,n.appendChild(f)}return n},Qh=t=>{let e=y("div","persona-approval-resolved"),n=he("ban",15,"currentColor",2);n&&e.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=t.toolName?ti(t.toolName):"Tool",e.append(r,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Xh=(t,e,n,r,o,s,a)=>{var O,_,H,U,F,ee,Ae;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(O=r==null?void 0:r.detailsDisplay)!=null?O:"collapsed",c=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",f=c||u,g=f&&Kh(e.id,r),m=(_=r==null?void 0:r.showDetailsLabel)!=null?_:"Show details",x=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",v=y("button","persona-approval-head");v.type="button",f?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",g?"true":"false"),v.setAttribute("aria-label",g?x:m)):v.setAttribute("data-static","true");let M=y("span","persona-approval-logo"),R=he("shield-check",16,"currentColor",2);R&&M.appendChild(R),v.appendChild(M);let T=Gh(n,r);if(f){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let te=he("chevron-down",14,"currentColor",2);te&&pe.appendChild(te),T.append(" "),T.appendChild(pe)}v.appendChild(T),i.appendChild(v);let k=y("div","persona-approval-body");if(f){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,c){let te=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(te.style.color=r.descriptionColor),te.textContent=n.description,pe.appendChild(te)}if(u){let te=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(te.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(te.style.color=r.parameterTextColor),te.textContent=go(n.parameters),pe.appendChild(te)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let te=y("span","persona-approval-reason-label");te.textContent=`${(U=r==null?void 0:r.reasonLabel)!=null?U:"Agent's stated reason:"} `,pe.append(te,document.createTextNode(n.reason)),k.appendChild(pe)}let E=y("div","persona-approval-actions"),I=null,A=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},L=y("button","persona-approval-deny");if(L.type="button",L.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(L.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(L.style.color=r.denyButtonTextColor),L.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let pe=y("div","persona-approval-split"),te=y("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),A(te),te.append((ee=r==null?void 0:r.approveLabel)!=null?ee:"Always allow",Yi("\u23CE"));let xe=y("button","persona-approval-caret");xe.type="button",xe.setAttribute("data-action","toggle-menu"),xe.setAttribute("aria-label","More options"),A(xe);let We=he("chevron-down",15,"currentColor",2);We&&xe.appendChild(We),pe.append(te,xe),E.append(pe,L),L.append(Yi("Esc"));let le=y("div","persona-approval-menu"),me=y("button","persona-approval-menu-item");me.type="button",me.append("Allow once",Yi("\u2318\u23CE")),le.appendChild(me),I=Am({anchor:pe,content:le,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,I),me.addEventListener("click",()=>{Oo(t,e.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),A(pe),pe.append((Ae=r==null?void 0:r.approveLabel)!=null?Ae:"Allow"),E.append(pe,L)}return k.appendChild(E),i.appendChild(k),i.addEventListener("click",pe=>{let te=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!te)return;let xe=te.getAttribute("data-action");if(xe==="toggle-params"){let We=i.querySelector('[data-role="params"]');if(We){let le=We.hidden;We.hidden=!le,v.setAttribute("aria-expanded",le?"true":"false"),v.setAttribute("aria-label",le?x:m),Fo.set(e.id,le)}return}if(xe==="toggle-menu"){I==null||I.toggle();return}if(xe==="always"){Oo(t,e.id),o({remember:!0});return}if(xe==="allow"){Oo(t,e.id),o();return}if(xe==="deny"){Oo(t,e.id),s();return}}),i},Em=()=>{let t=jh();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Vh(a);if(i.status!=="pending"){if(Oo(t,r.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return Qh(i)}Tm(t,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=Xh(t,r,i,d,o,s,c);if(c){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let f=g=>{Sm(g)||r.id===t.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Oo(t,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};t.keyHandlers.set(r.id,f),document.addEventListener("keydown",f)}return u}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Oo(t,r);t.latestPendingApprovalId=null}}};var Mm=t=>{let e=[],n=null;return{buttons:e,render:(o,s,a,i,d,c)=>{t.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(n=null),!o||!o.length||!u&&(i!=null?i:s?s.getMessages():[]).some(M=>M.role==="user"))return;let f=document.createDocumentFragment(),g=s?s.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(x=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=x,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),s.sendMessage(x))}),f.appendChild(v),e.push(v)}),t.appendChild(f),u){let x=JSON.stringify(o);x!==n&&(n=x,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ra=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){var n;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(n=this.store)==null||n.put(e)}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 e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var oa=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Jh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Yh=new Set(["step_start","execution_start"]),Zh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),ey=new Set(["step_complete","agent_turn_complete"]),ty=new Set(["flow_complete","agent_complete"]),km=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Pm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Jn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,_o=(t,e)=>{let n=t[e];return Pm(n)?n:void 0};function Zi(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function ri(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function ny(t,e){return typeof e.type=="string"?e.type:t}function ry(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function oy(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Lm(t){var r,o,s,a,i;let e=_o(t,"result"),n=[_o(t,"tokens"),_o(t,"totalTokens"),e?_o(e,"tokens"):void 0,_o(t,"usage"),e?_o(e,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Jn(d.output))!=null?r:Jn(d.outputTokens))!=null?o:Jn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Jn(t.outputTokens))!=null?s:Jn(t.completionTokens))!=null?i:e?(a=Jn(e.outputTokens))!=null?a:Jn(e.completionTokens):void 0}function sy(t){var n,r,o,s,a;let e=_o(t,"result");return(a=(o=(r=(n=Jn(t.executionTime))!=null?n:Jn(t.executionTimeMs))!=null?r:Jn(t.execution_time))!=null?o:Jn(t.duration))!=null?a:e?(s=Jn(e.executionTime))!=null?s:Jn(e.executionTimeMs):void 0}function ay(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var sa=class{constructor(e=ay){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ri(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){var s;if(!Pm(n)){km.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=ny(e,n),o=this.now();if(Jh.has(r)){this.startRun(o);return}if(Yh.has(r)){this.run||this.startRun(o);return}if(Zh.has(r)){if(!oy(r,n))return;let a=ry(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Zi(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ri(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(ey.has(r)){if(!this.run)return;let a=this.run,i=Lm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Zi(a.visibleCharCount),u=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:ri(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(ty.has(r)){if(!this.run)return;let a=this.run,i=Lm(n),d=i!=null?i:a.exactOutputTokens+Zi(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:ri(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(km.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=sy(n);return s!=null?s:r-e.startedAt}};function ys(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var iy={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)"}},ly={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},cy=["flowName","stepName","reasoningText","text","name","tool","toolName"],dy=100;function py(t,e){let n={...iy,...e};if(n[t])return n[t];for(let r of Object.keys(n))if(r.endsWith("_")&&t.startsWith(r))return n[r];return ly}function uy(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function my(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function gy(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let r of e){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function fy(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(n=>{let r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function hy(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function yy(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function by(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function vy(t,e,n){let r,o;try{o=JSON.parse(t.payload),r=JSON.stringify(o,null,2)}catch{o=t.payload,r=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function el(t,e,n,r,o,s,a,i){var g;let d=o.has(t.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");ys(c,(g=r.classNames)==null?void 0:g.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var F,ee;let m=y("div",""),x=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",t.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),M=he(d?"chevron-down":"chevron-right","14px","currentColor",2);M&&v.appendChild(M);let R=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(F=r.timestampFormat)!=null?F:"relative";R.textContent=T==="relative"?uy(t.timestamp,n):my(t.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(e+1));let E=py(t.type,r.badgeColors),I=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=E.bg,I.style.color=E.text,I.style.borderColor=E.text+"50",I.textContent=t.type;let A=(ee=r.descriptionFields)!=null?ee:cy,L=gy(t.payload,A),O=null;L&&(O=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=L);let _=y("div","persona-flex-1 persona-min-w-0"),H=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),U=he("clipboard","12px","currentColor",1.5);return U&&H.appendChild(U),H.addEventListener("click",async Ae=>{Ae.stopPropagation(),await fy(hy(t)),H.innerHTML="";let pe=he("check","12px","currentColor",1.5);pe&&H.appendChild(pe),setTimeout(()=>{H.innerHTML="";let te=he("clipboard","12px","currentColor",1.5);te&&H.appendChild(te)},1500)}),x.appendChild(v),x.appendChild(R),k&&x.appendChild(k),x.appendChild(I),O&&x.appendChild(O),x.appendChild(_),x.appendChild(H),m.appendChild(x),d&&m.appendChild(vy(t,a,i)),m}}function Im(t){var x,v,M,R,T;let{buffer:e,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=t,i=(x=o==null?void 0:o.features)==null?void 0:x.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(M=i==null?void 0:i.label)!=null?M:"",f=(T=(R=o==null?void 0:o.features)==null?void 0:R.eventStream)!=null?T:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return m();function m(){let k=f.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ys(E,k==null?void 0:k.panel);let I=[],A="",L="",O=null,_=[],H={},U=0,F=Oa(),ee=0,Ae=0,pe=!1,te=null,xe=!1,We=0,le=new Set,me=new Map,re="",oe="",de=null,ze,Fe,G,X,ve,Y=null,ie=null,Ee=null;function Je(){let P=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ce=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");ys(ce,k==null?void 0:k.headerBar);let Me=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Me.textContent="Events",ze=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"),ze.textContent="0",a){ie=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ie.style.cursor="help";let Ut=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ut.textContent="Throughput",Y=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"),Y.textContent="-- tok/s",Ee=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"),Ee.style.display="none",Ee.style.pointerEvents="none";let On=ie,En=Ee,Mn=()=>{if(!En.textContent)return;let kn=On.getBoundingClientRect(),lr=P.getBoundingClientRect();En.style.left=`${kn.left-lr.left}px`,En.style.top=`${kn.bottom-lr.top+4}px`,En.style.display="block"},vn=()=>{En.style.display="none"};ie.addEventListener("mouseenter",Mn),ie.addEventListener("mouseleave",vn),ie.appendChild(Ut),ie.appendChild(Y)}let Mt=y("div","persona-flex-1");Fe=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ze=y("option","");Ze.value="",Ze.textContent="All events",Fe.appendChild(Ze),G=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"),G.type="button",G.title="Copy All";let yn=he("clipboard-copy","12px","currentColor",1.5);yn&&G.appendChild(yn);let vt=y("span","persona-text-xs");vt.textContent="Copy All",G.appendChild(vt),ce.appendChild(Me),ce.appendChild(ze),ie&&ce.appendChild(ie),ce.appendChild(Mt),ce.appendChild(Fe),ce.appendChild(G);let xt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ys(xt,k==null?void 0:k.searchBar);let Ht=he("search","14px","var(--persona-muted, #9ca3af)",1.5),Ct=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ht&&Ct.appendChild(Ht),X=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"),ys(X,k==null?void 0:k.searchInput),X.type="text",X.placeholder="Search event payloads...",ve=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"),ve.type="button",ve.style.display="none";let un=he("x","12px","currentColor",2);return un&&ve.appendChild(un),xt.appendChild(Ct),xt.appendChild(X),xt.appendChild(ve),P.appendChild(ce),P.appendChild(xt),Ee&&P.appendChild(Ee),P}let nt,wt=s.find(P=>P.renderEventStreamToolbar);if(wt!=null&&wt.renderEventStreamToolbar&&o){let P=wt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Je(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ce=>{A=ce,_e(),Yt()},onSearchChange:ce=>{L=ce,_e(),Yt()}});nt=P!=null?P:Je()}else nt=Je();let dt=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");dt.style.display="none";function tt(){if(!a||!Y||!ie)return;let P=a();Y.textContent=yy(P);let ce=by(P);Ee&&(Ee.textContent=ce,ce||(Ee.style.display="none")),ce?ie.setAttribute("aria-label",ce):ie.removeAttribute("aria-label")}let He=y("div","persona-flex-1 persona-min-h-0 persona-relative"),Q=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Q.style.height="100%";let Ve=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");ys(Ve,k==null?void 0:k.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let je=he(c,"14px","currentColor",2);je&&Ve.appendChild(je);let we=y("span","");we.textContent=u,Ve.appendChild(we);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",He.appendChild(Q),He.appendChild(Se),He.appendChild(Ve),E.setAttribute("tabindex","0"),E.appendChild(nt),E.appendChild(dt),E.appendChild(He);function Ye(){let P=e.getAll(),ce={};for(let vt of P)ce[vt.type]=(ce[vt.type]||0)+1;let Me=Object.keys(ce).sort(),Mt=Me.length!==_.length||!Me.every((vt,xt)=>vt===_[xt]),Ze=!Mt&&Me.some(vt=>ce[vt]!==H[vt]),qt=P.length!==Object.values(H).reduce((vt,xt)=>vt+xt,0);if(!Mt&&!Ze&&!qt||(_=Me,H=ce,!Fe))return;let yn=Fe.value;if(Fe.options[0].textContent="All events",Mt){for(;Fe.options.length>1;)Fe.remove(1);for(let vt of Me){let xt=y("option","");xt.value=vt,xt.textContent=`${vt} (${ce[vt]||0})`,Fe.appendChild(xt)}yn&&Me.includes(yn)?Fe.value=yn:yn&&(Fe.value="",A="")}else for(let vt=1;vt<Fe.options.length;vt++){let xt=Fe.options[vt];xt.textContent=`${xt.value} (${ce[xt.value]||0})`}}function Qe(){let P=e.getAll();if(A&&(P=P.filter(ce=>ce.type===A)),L){let ce=L.toLowerCase();P=P.filter(Me=>Me.type.toLowerCase().includes(ce)||Me.payload.toLowerCase().includes(ce))}return P}function Te(){return A!==""||L!==""}function _e(){U=0,ee=0,F.resume(),Ve.style.display="none"}function pn(P){le.has(P)?le.delete(P):le.add(P),de=P;let ce=Q.scrollTop,Me=F.isFollowing();xe=!0,F.pause(),Yt(),Q.scrollTop=ce,Me&&F.resume(),xe=!1}function Ft(){return Do(Q,50)}function Yt(){Ae=Date.now(),pe=!1,tt(),Ye();let P=e.getEvictedCount();P>0?(dt.textContent=`${P.toLocaleString()} older events truncated`,dt.style.display=""):dt.style.display="none",I=Qe();let ce=I.length,Me=e.getSize()>0;ze&&(ze.textContent=String(e.getSize())),ce===0&&Me&&Te()?(Se.textContent=L?`No events matching '${L}'`:"No events matching filter",Se.style.display="",Q.style.display="none"):(Se.style.display="none",Q.style.display=""),G&&(G.title=Te()?`Copy Filtered (${ce})`:"Copy All"),d&&!F.isFollowing()&&ce>U&&(ee+=ce-U,we.textContent=u?`${u}${ee>0?` (${ee})`:""}`:"",Ve.style.display=""),U=ce;let Mt=e.getAll(),Ze=Mt.length>0?Mt[0].timestamp:0,qt=new Set(I.map(xt=>xt.id));for(let xt of le)qt.has(xt)||le.delete(xt);let yn=A!==re||L!==oe,vt=me.size===0&&I.length>0;if(yn||vt||I.length===0){Q.innerHTML="",me.clear();let xt=document.createDocumentFragment();for(let Ht=0;Ht<I.length;Ht++){let Ct=el(I[Ht],Ht,Ze,f,le,pn,s,o);me.set(I[Ht].id,Ct),xt.appendChild(Ct)}Q.appendChild(xt),re=A,oe=L,de=null}else{if(de!==null){let Ht=me.get(de);if(Ht&&Ht.parentNode===Q){let Ct=I.findIndex(un=>un.id===de);if(Ct>=0){let un=el(I[Ct],Ct,Ze,f,le,pn,s,o);Q.insertBefore(un,Ht),Ht.remove(),me.set(de,un)}}de=null}let xt=new Set(I.map(Ht=>Ht.id));for(let[Ht,Ct]of me)xt.has(Ht)||(Ct.remove(),me.delete(Ht));for(let Ht=0;Ht<I.length;Ht++){let Ct=I[Ht];if(!me.has(Ct.id)){let un=el(Ct,Ht,Ze,f,le,pn,s,o);me.set(Ct.id,un),Q.appendChild(un)}}}F.isFollowing()&&(Q.scrollTop=Q.scrollHeight)}function Rr(){if(Date.now()-Ae>=dy){te!==null&&(cancelAnimationFrame(te),te=null),Yt();return}pe||(pe=!0,te=requestAnimationFrame(()=>{te=null,Yt()}))}let B=(P,ce)=>{if(!G)return;G.innerHTML="";let Me=he(P,"12px","currentColor",1.5);Me&&G.appendChild(Me);let Mt=y("span","persona-text-xs");Mt.textContent="Copy All",G.appendChild(Mt),setTimeout(()=>{G.innerHTML="";let Ze=he("clipboard-copy","12px","currentColor",1.5);Ze&&G.appendChild(Ze);let qt=y("span","persona-text-xs");qt.textContent="Copy All",G.appendChild(qt),G.disabled=!1},ce)},K=async()=>{if(G){G.disabled=!0;try{let P;Te()?P=I:n?(P=await n(),P.length===0&&(P=e.getAll())):P=e.getAll();let ce=P.map(Me=>{try{return JSON.parse(Me.payload)}catch{return Me.payload}});await navigator.clipboard.writeText(JSON.stringify(ce,null,2)),B("check",1500)}catch{B("x",1500)}}},ue=()=>{Fe&&(A=Fe.value,_e(),Yt())},Be=()=>{!X||!ve||(ve.style.display=X.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{L=X.value,_e(),Yt()},150))},$e=()=>{!X||!ve||(X.value="",L="",ve.style.display="none",O&&clearTimeout(O),_e(),Yt())},De=()=>{if(xe)return;let P=Q.scrollTop,{action:ce,nextLastScrollTop:Me}=_a({following:F.isFollowing(),currentScrollTop:P,lastScrollTop:We,nearBottom:Ft(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});We=Me,ce==="resume"?(F.resume(),ee=0,Ve.style.display="none"):ce==="pause"&&(F.pause(),d&&(we.textContent=u,Ve.style.display=""))},Le=P=>{let ce=$a({following:F.isFollowing(),deltaY:P.deltaY,nearBottom:Ft(),resumeWhenNearBottom:!0});ce==="pause"?(F.pause(),d&&(we.textContent=u,Ve.style.display="")):ce==="resume"&&(F.resume(),ee=0,Ve.style.display="none")},it=()=>{d&&(Q.scrollTop=Q.scrollHeight,F.resume(),ee=0,Ve.style.display="none")},Wt=P=>{let ce=P.target;if(!ce||ce.closest("button"))return;let Me=ce.closest("[data-event-id]");if(!Me)return;let Mt=Me.getAttribute("data-event-id");Mt&&pn(Mt)},yt=P=>{if((P.metaKey||P.ctrlKey)&&P.key==="f"){P.preventDefault(),X==null||X.focus(),X==null||X.select();return}P.key==="Escape"&&(X&&document.activeElement===X?($e(),X.blur(),E.focus()):r&&r())};G&&G.addEventListener("click",K),Fe&&Fe.addEventListener("change",ue),X&&X.addEventListener("input",Be),ve&&ve.addEventListener("click",$e),Q.addEventListener("scroll",De),Q.addEventListener("wheel",Le,{passive:!0}),Q.addEventListener("click",Wt),Ve.addEventListener("click",it),E.addEventListener("keydown",yt);function Rt(){O&&clearTimeout(O),te!==null&&(cancelAnimationFrame(te),te=null),pe=!1,me.clear(),G&&G.removeEventListener("click",K),Fe&&Fe.removeEventListener("change",ue),X&&X.removeEventListener("input",Be),ve&&ve.removeEventListener("click",$e),Q.removeEventListener("scroll",De),Q.removeEventListener("wheel",Le),Q.removeEventListener("click",Wt),Ve.removeEventListener("click",it),E.removeEventListener("keydown",yt)}return{element:E,update:Rr,destroy:Rt}}}function Wm(t,e){let n=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(g);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(u,f),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Rm=(t,e)=>{var r,o,s;let n=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",c=typeof t.artifactType=="string"?t.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Wm(t,e)});if(u)return u}return Wm(t,e)};var tl=class{constructor(){this.components=new Map}register(e,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([n,r])=>{this.register(n,r)})}},$o=new tl;$o.register("PersonaArtifactCard",Rm);function xy(t){var o;let e=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=t.component?`Component: ${t.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=t.props)!=null?o:{},null,2),e.appendChild(n),e.appendChild(r),e}function Hm(t,e){var Fe,G,X,ve;let n=(G=(Fe=t.features)==null?void 0:Fe.artifacts)==null?void 0:G.layout,o=((X=n==null?void 0:n.toolbarPreset)!=null?X:"default")==="document",s=(ve=n==null?void 0:n.panePadding)==null?void 0:ve.trim(),a=t.markdown?ya(t.markdown):null,i=ba(t.sanitize),d=Y=>{let ie=a?a(Y):co(Y);return i?i(ie):ie},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let f=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");f.setAttribute("data-persona-theme-zone","artifact-pane"),o&&f.classList.add("persona-artifact-pane-document");let g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let v="rendered",M=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),R=o?Tn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Tn({icon:"eye",label:"Rendered view"}),T=o?Tn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Tn({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,A=n==null?void 0:n.documentToolbarCopyMenuItems,L=!!(I&&A&&A.length>0),O=null,_,H=null,U=null;if(o&&(E||I)&&!L){if(_=E?zi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Y=he("chevron-down",14,"currentColor",2);Y&&_.appendChild(Y)}}else o&&L?(O=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=E?zi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Tn({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"}}),O.append(_,H)):o?_=Tn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=Tn({icon:"copy",label:"Copy"});let F=o?Tn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tn({icon:"refresh-cw",label:"Refresh"}),ee=o?Tn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Tn({icon:"x",label:"Close"}),Ae=()=>{var nt,wt,dt;let Y=(nt=me.find(tt=>tt.id===re))!=null?nt:me[me.length-1],ie=(wt=Y==null?void 0:Y.id)!=null?wt:null,Ee=(Y==null?void 0:Y.artifactType)==="markdown"&&(dt=Y.markdown)!=null?dt:"",Je=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Ee,jsonPayload:Je,id:ie}},pe=async()=>{var nt;let{markdown:Y,jsonPayload:ie}=Ae(),Ee=(nt=me.find(wt=>wt.id===re))!=null?nt:me[me.length-1],Je=(Ee==null?void 0:Ee.artifactType)==="markdown"?Y:Ee?ie:"";try{await navigator.clipboard.writeText(Je)}catch{}};if(_.addEventListener("click",async()=>{let Y=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(Y&&L){let{markdown:ie,jsonPayload:Ee,id:Je}=Ae();try{await Y({actionId:"primary",artifactId:Je,markdown:ie,jsonPayload:Ee})}catch{}return}await pe()}),H&&(A!=null&&A.length)){let Y=()=>{var Ee;return(Ee=f.closest("[data-persona-root]"))!=null?Ee:document.body},ie=()=>{U=gs({items:A.map(Ee=>({id:Ee.id,label:Ee.label})),onSelect:async Ee=>{let{markdown:Je,jsonPayload:nt,id:wt}=Ae(),dt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{dt?await dt({actionId:Ee,artifactId:wt,markdown:Je,jsonPayload:nt}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Je):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(nt):await navigator.clipboard.writeText(Je||nt)}catch{}},anchor:O!=null?O:H,position:"bottom-right",portal:Y()})};f.isConnected?ie():requestAnimationFrame(ie),H.addEventListener("click",Ee=>{Ee.stopPropagation(),U==null||U.toggle()})}F.addEventListener("click",async()=>{var Y;try{await((Y=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:Y.call(n))}catch{}de()}),ee.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let te=()=>{o&&(R.setAttribute("aria-pressed",v==="rendered"?"true":"false"),T.setAttribute("aria-pressed",v==="source"?"true":"false"))};R.addEventListener("click",()=>{v="rendered",te(),de()}),T.addEventListener("click",()=>{v="source",te(),de()});let xe=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),M.append(R,T),O?k.append(O,F,ee):k.append(_,F,ee),g.append(M,xe,k),te()):(g.appendChild(m),g.appendChild(x)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let We=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"),le=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(We.style.paddingLeft=s,We.style.paddingRight=s,le.style.padding=s),f.appendChild(g),f.appendChild(We),f.appendChild(le);let me=[],re=null,oe=!1,de=()=>{var Je,nt,wt,dt;let Y=o&&me.length<=1;We.classList.toggle("persona-hidden",Y),We.replaceChildren();for(let tt of me){let He=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");He.type="button",He.textContent=tt.title||tt.id.slice(0,8),tt.id===re&&He.classList.add("persona-bg-persona-container","persona-border-persona-border"),He.addEventListener("click",()=>e.onSelect(tt.id)),We.appendChild(He)}le.replaceChildren();let ie=re&&me.find(tt=>tt.id===re)||me[me.length-1];if(!ie)return;if(o){let tt=ie.artifactType==="markdown"?"MD":(Je=ie.component)!=null?Je:"Component",Q=(ie.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${Q} \xB7 ${tt}`}else m.textContent="Artifacts";if(ie.artifactType==="markdown"){if(o&&v==="source"){let He=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");He.textContent=(nt=ie.markdown)!=null?nt:"",le.appendChild(He);return}let tt=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");tt.innerHTML=d((wt=ie.markdown)!=null?wt:""),le.appendChild(tt);return}let Ee=ie.component?$o.get(ie.component):void 0;if(Ee){let He={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let Q=Ee((dt=ie.props)!=null?dt:{},He);if(Q){le.appendChild(Q);return}}catch{}}le.appendChild(xy(ie))},ze=()=>{var ie;let Y=me.length>0;if(f.classList.toggle("persona-hidden",!Y),c){let Ee=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,nt=((ie=Ee==null?void 0:Ee.classList.contains("persona-artifact-narrow-host"))!=null?ie:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&nt&&oe?(c.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:c,update(Y){var ie,Ee,Je;me=Y.artifacts,re=(Je=(Ee=Y.selectedId)!=null?Ee:(ie=Y.artifacts[Y.artifacts.length-1])==null?void 0:ie.id)!=null?Je:null,me.length>0&&(oe=!0),de(),ze()},setMobileOpen(Y){oe=Y,!Y&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):ze()}}}function ir(t){var e,n;return((n=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:n.enabled)===!0}function Bm(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!ir(e))return;let n=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",r)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function wy(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function oi(t,e){var d,c,u,f,g,m,x,v,M,R;if(!ir(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),wy(t),Bm(t,e);return}let n=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;t.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(f=n==null?void 0:n.paneWidth)!=null?f:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let o=(x=n==null?void 0:n.panePadding)==null?void 0:x.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(M=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:M.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(R=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:R.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Bm(t,e)}var Dm=["panel","seamless"];function si(t,e){var i,d,c,u,f,g;for(let m of Dm)t.classList.remove(`persona-artifact-appearance-${m}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!ir(e))return;let n=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Dm.includes(r)?r:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=n==null?void 0:n.paneShadow)==null?void 0:f.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let m=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;m&&t.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Nm(t,e){var n,r,o;return!e||!ir(t)?!1:((o=(r=(n=t.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Cy(t,e){if(!(t!=null&&t.trim()))return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Ay(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Sy(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ty(t,e,n,r){let o=t-r-2*e-n;return Math.max(0,o)}function Fm(t,e){var a;let r=(a=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Om(t,e,n,r,o,s){let a=Cy(o,200),i=Ty(e,n,r,200);i=Math.max(a,i);let d=Ay(s);return d!==null&&(i=Math.min(i,d)),Sy(t,a,i)}var _m={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"}},nl=(t,e,n,r)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var x,v,M;if(s.dataset.enhanced==="true")return;let a=(x=s.dataset.tvForm)!=null?x:"init";s.dataset.enhanced="true";let i=(v=_m[a])!=null?v:_m.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let R=y("p","persona-text-sm persona-text-persona-muted");R.textContent=i.description,d.appendChild(R)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(R=>{var A,L;let T=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${R.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=R.label,T.appendChild(k);let E=(A=R.type)!=null?A:"text",I;E==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=E),I.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",I.id=`${e.id}-${a}-${R.name}`,I.name=R.name,I.placeholder=(L=R.placeholder)!=null?L:"",R.required&&(I.required=!0),T.appendChild(I),u.appendChild(T)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=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");m.type="submit",m.textContent=(M=i.submitLabel)!=null?M:"Submit",f.appendChild(g),f.appendChild(m),u.appendChild(f),s.replaceChildren(d,u),u.addEventListener("submit",async R=>{var I,A;R.preventDefault();let T=(I=n.formEndpoint)!=null?I:"/form",k=new FormData(u),E={};k.forEach((L,O)=>{E[O]=L}),E.type=a,m.disabled=!0,g.textContent="Submitting\u2026";try{let L=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let O=await L.json();g.textContent=(A=O.message)!=null?A:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await r.sendMessage(String(O.nextPrompt))}catch(L){g.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var rl=class{constructor(){this.plugins=new Map}register(e){var n;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(n=e.onRegister)==null||n.call(e)}unregister(e){var r;let n=this.plugins.get(e);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let r=new Set(e.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var n;return(n=e.onUnregister)==null?void 0:n.call(e)}),this.plugins.clear()}},ol=new rl;var $m=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:n,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ey=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},My=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(n,o+1)}return null},al=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Ey(t),n=My(e);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},sl=t=>typeof t=="string"?t:t==null?"":String(t),aa={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:sl(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let n=t.payload,r=sl(n.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:sl(n.text)}}},Um=t=>Array.isArray(t)?t.map(e=>String(e)):[],il=t=>{let e=new Set(Um(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Um(t.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};t.emit("action:detected",d);for(let c of t.handlers)if(c)try{let u=()=>{t.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var ky=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Ly=t=>t.map(e=>({...e,streaming:!1})),Py=t=>t.map(e=>({...e,status:"complete"})),zm=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?ky(n.getItem(t)):null},save:n=>{let r=e();if(r)try{let o={...n,messages:n.messages?Ly(n.messages):void 0,artifacts:n.artifacts?Py(n.artifacts):void 0};r.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var ll=require("partial-json");function qm(t,e){let{config:n,message:r,onPropsUpdate:o}=e,s=$o.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function jm(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Vm(t){let e=jm(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Km(t){let e=jm(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var Iy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gm(t){let{onSubmit:e,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Iy}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,m.appendChild(x);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,m.appendChild(v),g.appendChild(m);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let R=[];for(let A=1;A<=5;A++){let L=document.createElement("button");L.type="button",L.className="persona-feedback-rating-btn persona-feedback-star-btn",L.setAttribute("role","radio"),L.setAttribute("aria-checked","false"),L.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),L.title=c[A-1],L.dataset.rating=String(A),L.innerHTML=`
|
|
29
31
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
30
32
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
31
33
|
</svg>
|
|
32
|
-
`,W.addEventListener("click",()=>{f=A,M.forEach((N,D)=>{let k=D<A;N.classList.toggle("selected",k),N.setAttribute("aria-checked",D===A-1?"true":"false")})}),M.push(W),I.appendChild(W)}g.appendChild(I);let E=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),A.appendChild(E),g.appendChild(A)}let F=document.createElement("div");F.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",()=>{t==null||t(),m.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(E==null?void 0:E.value.trim())||void 0;await e(f,A),m.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),F.appendChild(L),F.appendChild(R),g.appendChild(F),m.appendChild(g),m}function Fm(n){let{onSubmit:e,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:m="Very likely"}=n,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,u=document.createElement("div");u.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=o,v.appendChild(I),u.appendChild(v);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 E=document.createElement("div");E.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=m,E.appendChild(F),E.appendChild(L);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let j=0;j<=10;j++){let V=document.createElement("button");V.type="button",V.className="persona-feedback-rating-btn persona-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${j} out of 10`),V.textContent=String(j),V.dataset.rating=String(j),j<=6?V.classList.add("persona-feedback-detractor"):j<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{g=j,A.forEach((ne,Re)=>{ne.classList.toggle("selected",Re===j),ne.setAttribute("aria-checked",Re===j?"true":"false")})}),A.push(V),R.appendChild(V)}M.appendChild(E),M.appendChild(R),u.appendChild(M);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),u.appendChild(j)}let N=document.createElement("div");N.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=i,D.addEventListener("click",()=>{t==null||t(),f.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(g===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let j=(W==null?void 0:W.value.trim())||void 0;await e(g,j),f.remove()}catch(j){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",j)}}),N.appendChild(D),N.appendChild(k),u.appendChild(N),f.appendChild(u),f}var ms="persona-chat-history",dy=30*1e3,py={"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 uy(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=py[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function ri(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function my(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function gy(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var al=n=>!n||typeof n!="object"?{}:{...n},Om=n=>n.map(e=>({...e,streaming:!1})),_m=(n,e,t)=>{let r=n!=null&&n.markdown?ga(n.markdown):null,o=fa(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var m,f,g;let a=(m=s.text)!=null?m:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let u=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&t&&t())}let d=Eo()!==null,c;if(n!=null&&n.postprocessMessage){let u=n.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(u):u}else if(r){let u=r(a);c=o&&d?o(u):u}else c=so(a);return c}};function $m(n){var i,d,c,m;let e=b("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(m=n==null?void 0:n.iconStrokeWidth)!=null?m:.5,a=Ae(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let f=b("span","persona-drop-overlay-label");f.textContent=n.label,e.appendChild(f)}return e}var Um=(n,e,t)=>{var _l,$l,Ul,ql,zl,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Mc,Ec,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=Bu(e),o=tl.getForInstance(r.plugins);r.components&&Do.registerAll(r.components);let s=Pm(),i=r.persistState===!1?null:(_l=r.storageAdapter)!=null?_l:Wm(),d={},c=null,m=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(m=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")c=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(d=al(h.metadata)),($l=h.messages)!=null&&$l.length&&(r={...r,initialMessages:h.messages}),(Ul=h.artifacts)!=null&&Ul.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(ql=h.selectedArtifactId)!=null?ql:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(zl=l.messages)!=null&&zl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>d,u=l=>{var h;d=(h=l({...d}))!=null?h:{},Zr()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick],I=ol({parsers:v,handlers:x,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null});I.syncFromMetadata();let M=(Vl=(jl=r.launcher)==null?void 0:jl.enabled)!=null?Vl:!0,E=(Gl=(Kl=r.launcher)==null?void 0:Kl.autoExpand)!=null?Gl:!1,F=(Ql=r.autoFocusInput)!=null?Ql:!1,L=E,R=M,A=(Jl=(Xl=r.layout)==null?void 0:Xl.header)==null?void 0:Jl.layout,W=!1,N=()=>Qs(r),D=()=>M||N(),k=N()?!1:M?E:!0,j=!1,V=null,ne=()=>{j=!0,V&&clearTimeout(V),V=setTimeout(()=>{j&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),j=!1)},1e4)},Re=_m(r,I,ne),Ue=(Zl=(Yl=r.features)==null?void 0:Yl.showReasoning)!=null?Zl:!0,xe=(tc=(ec=r.features)==null?void 0:ec.showToolCalls)!=null?tc:!0,Ie=(rc=(nc=r.features)==null?void 0:nc.showEventStreamToggle)!=null?rc:!1,_e=(sc=(oc=r.features)==null?void 0:oc.scrollToBottom)!=null?sc:{},Se=(ic=(ac=r.features)==null?void 0:ac.scrollBehavior)!=null?ic:{},re=`${(cc=typeof r.persistState=="object"?(lc=r.persistState)==null?void 0:lc.keyPrefix:void 0)!=null?cc:"persona-"}event-stream`,X=Ie?new Zs(re):null,ie=(uc=(pc=(dc=r.features)==null?void 0:dc.eventStream)==null?void 0:pc.maxEvents)!=null?uc:2e3,he=Ie?new Ys(ie,X):null,oe=Ie?new ea:null,K=null,te=!1,qe=null,Y=0;X==null||X.open().then(()=>he==null?void 0:he.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let le={onCopy:l=>{var p,h;s.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},Pe=(mc=r.statusIndicator)!=null?mc:{},it=l=>{var p,h,y,S;return l==="idle"?(p=Pe.idleText)!=null?p:xn.idle:l==="connecting"?(h=Pe.connectingText)!=null?h:xn.connecting:l==="connected"?(y=Pe.connectedText)!=null?y:xn.connected:l==="error"?(S=Pe.errorText)!=null?S:xn.error:xn[l]};function lt(l,p,h,y){if(y==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=p,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=p}let rt=im({config:r,showClose:D()}),{wrapper:Ee,panel:pe,pillRoot:Xe}=rt.shell,J=rt.panelElements,{container:ce,body:we,messagesWrapper:je,suggestions:Pt,textarea:Te,sendButton:me,sendButtonWrapper:fn,composerForm:It,statusText:rn,introTitle:hr,introSubtitle:hn,closeButton:Ve,iconHolder:T,headerTitle:ue,headerSubtitle:Le,header:Me,footer:He,actionsRow:Ze,leftActions:Ge,rightActions:ut}=J,Wt=J.setSendButtonMode,q=J.micButton,ot=J.micButtonWrapper,G=J.attachmentButton,de=J.attachmentButtonWrapper,ke=J.attachmentInput,vt=J.attachmentPreviewsContainer;ce.classList.add("persona-relative"),we.classList.add("persona-relative");let Yt=12,Zt=()=>{var l;return(l=_e.label)!=null?l:""},pn=()=>{var l;return(l=_e.iconName)!=null?l:"arrow-down"},Ht=()=>_e.enabled!==!1,et=()=>{var l;return(l=Se.mode)!=null?l:"follow"},Rt=()=>{var l;return(l=Se.anchorTopOffset)!=null?l:16},ct=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");ct.type="button",ct.style.display="none",ct.setAttribute("data-persona-scroll-to-bottom","true");let Kt=b("span","persona-flex persona-items-center"),Jn=b("span",""),An=b("span","");An.setAttribute("data-persona-scroll-to-bottom-count",""),An.style.display="none",ct.append(Kt,Jn,An),ce.appendChild(ct);let en=b("div","persona-stream-anchor-spacer");en.setAttribute("aria-hidden","true"),en.setAttribute("data-persona-anchor-spacer",""),en.style.flexShrink="0",en.style.pointerEvents="none",en.style.height="0px",we.appendChild(en);let In=()=>{let p=He.style.display==="none"?0:He.offsetHeight;ct.style.bottom=`${p+Yt}px`};In();let yr=()=>{let l=!!Zt();ct.setAttribute("aria-label",Zt()||"Jump to latest"),ct.title=Zt(),ct.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Kt.innerHTML="";let p=Ae(pn(),"14px","currentColor",2);p?(Kt.appendChild(p),Kt.style.display=""):Kt.style.display="none",Jn.textContent=Zt(),Jn.style.display=l?"":"none"};yr();let xt=null,Nn=null,br=o.find(l=>l.renderHeader);if(br!=null&&br.renderHeader){let l=br.renderHeader({config:r,defaultRenderer:()=>{let p=Ho({config:r,showClose:D()});return Xs(ce,p,r),p.header},onClose:()=>$t(!1,"user")});if(l){let p=ce.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Me=l,rt.header.element=l)}}let Pr=()=>{var p,h,y,S;if(!he)return;if(te=!0,!K&&he&&(K=xm({buffer:he,getFullHistory:()=>he.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var H;return(H=oe==null?void 0:oe.getMetric())!=null?H:{status:"idle"}}})),K&&(we.style.display="none",(p=He.parentNode)==null||p.insertBefore(K.element,He),K.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let H=(S=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(z=>z&&yt.classList.add(z))}let l=()=>{if(!te)return;let H=Date.now();H-Y>=200&&(K==null||K.update(),Y=H),qe=requestAnimationFrame(l)};Y=0,qe=requestAnimationFrame(l),Je(),s.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,p,h;if(te){if(te=!1,K&&K.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(S=>S&&yt.classList.remove(S))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Je(),s.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(Ie){let l=(fc=(gc=r.features)==null?void 0:gc.eventStream)==null?void 0:fc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=b("button",p),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=Ae("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let y=J.clearChatButtonWrapper,S=J.closeButtonWrapper,H=y||S;H&&H.parentNode===Me?Me.insertBefore(yt,H):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}let uo=l=>{var S,H,z,O,B;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((H=l.querySelector("[data-persona-composer-attachment-input]"))!=null?H:l.querySelector('input[type="file"]'))){let se=b("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((z=p.allowedTypes)!=null?z:Ur).join(","),se.multiple=((O=p.maxFiles)!=null?O:4)>1,se.style.display="none",se.setAttribute("aria-label",(B=p.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(se)}},vr=o.find(l=>l.renderComposer);if(vr!=null&&vr.renderComposer){let l=r.composer,p=vr.renderComposer({config:r,defaultRenderer:()=>Ja({config:r}).footer,onSubmit:h=>{var z;if(!_||_.isStreaming())return;let y=h.trim(),S=(z=xt==null?void 0:xt.hasAttachments())!=null?z:!1;if(!y&&!S)return;yl();let H;S&&(H=[],H.push(...xt.getContentParts()),y&&H.push(Pi(y))),_.sendMessage(y,{contentParts:H}),S&&xt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke==null||ke.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((hc=r.voiceRecognition)==null?void 0:hc.enabled)===!0?()=>{Nn==null||Nn()}:void 0});p&&(rt.replaceComposer(p),He=rt.composer.footer)}let mo=l=>{let p=(...ae)=>{for(let Z of ae){let be=l.querySelector(Z);if(be)return be}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),H=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");h&&(It=h),y&&(Te=y),S&&(me=S),H&&(q=H,ot=H.parentElement),z&&(rn=z);let O=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");O&&(Pt=O);let B=p("[data-persona-composer-attachment-button]",".persona-attachment-button");B&&(G=B,de=B.parentElement),ke=p("[data-persona-composer-attachment-input]",'input[type="file"]'),vt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(Ze=se)};uo(He),mo(He);let Wn=(wc=(yc=r.layout)==null?void 0:yc.contentMaxWidth)!=null?wc:N()?(xc=(vc=(bc=r.launcher)==null?void 0:bc.composerBar)==null?void 0:vc.contentMaxWidth)!=null?xc:"720px":void 0;if(Wn&&(je.style.maxWidth=Wn,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%"),Wn&&It&&!N()&&(It.style.maxWidth=Wn,It.style.marginLeft="auto",It.style.marginRight="auto"),Wn&&Pt&&!N()&&(Pt.style.maxWidth=Wn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Wn&&vt&&!N()&&(vt.style.maxWidth=Wn,vt.style.marginLeft="auto",vt.style.marginRight="auto"),(Cc=r.attachments)!=null&&Cc.enabled&&ke&&vt){xt=$s.fromConfig(r.attachments),xt.setPreviewsContainer(vt),ke.addEventListener("change",h=>{let y=h.target;xt==null||xt.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=$m(l);ce.appendChild(p)}(()=>{var y,S;let l=(S=(y=r.layout)==null?void 0:y.slots)!=null?S:{},p=H=>{switch(H){case"body-top":return ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return je;case"footer-top":return Pt;case"composer":return It;case"footer-bottom":return rn;default:return null}},h=(H,z)=>{var O;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")Me.insertBefore(z,Me.firstChild);else if(H==="header-right")Me.appendChild(z);else{let B=Me.querySelector(".persona-flex-col");B?(O=B.parentNode)==null||O.insertBefore(z,B.nextSibling):Me.appendChild(z)}break;case"body-top":{let B=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(z):we.insertBefore(z,we.firstChild);break}case"body-bottom":we.appendChild(z);break;case"footer-top":Pt.replaceWith(z);break;case"footer-bottom":rn.replaceWith(z);break;default:break}};for(let[H,z]of Object.entries(l))if(z)try{let O=z({config:r,defaultContent:()=>p(H)});O&&h(H,O)}catch(O){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,O)}})();let jr=l=>{var z,O;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-bubble-type");if(H==="reasoning")ds.has(S)?ds.delete(S):ds.add(S),dm(S,y);else if(H==="tool")ps.has(S)?ps.delete(S):ps.add(S),pm(S,y,r);else if(H==="approval"){let B=r.approval!==!1?r.approval:void 0,se=((z=B==null?void 0:B.detailsDisplay)!=null?z:"collapsed")==="expanded",ae=(O=Ya.get(S))!=null?O:se;Ya.set(S,!ae),fm(S,y,r)}Sr.delete(S)};je.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),jr(l))}),je.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=je.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let S=y.toString(),H=Uu(S);!H||H===S||(p.setData("text/plain",H),l.preventDefault())});let Ir=new Map,Vr=null,Kr="idle",go={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},fo=(l,p)=>{let{icon:h,label:y}=go[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let S=Ae(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Gr=()=>{je.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var H;let h=p.closest("[data-actions-for]"),y=(H=h==null?void 0:h.getAttribute("data-actions-for"))!=null?H:null;fo(p,y&&y===Vr?Kr:"idle")})};je.addEventListener("click",l=>{var z;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let S=y.getAttribute("data-actions-for");if(!S)return;let H=h.getAttribute("data-action");if(H==="copy"){let B=_.getMessages().find(se=>se.id===S);if(B&&le.onCopy){let se=B.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=Ae("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=Ae("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),le.onCopy(B)}}else if(H==="read-aloud")_.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let B=((z=Ir.get(S))!=null?z:null)===H,se=H==="upvote"?"thumbs-up":"thumbs-down";if(B){Ir.delete(S),h.classList.remove("persona-message-action-active");let ae=Ae(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=H==="upvote"?"downvote":"upvote",Z=y.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let $e=Ae(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);$e&&(Z.innerHTML="",Z.appendChild($e))}Ir.set(S,H),h.classList.add("persona-message-action-active");let be=Ae(se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=_.getMessages().find(nt=>nt.id===S);Ce&&le.onFeedback&&le.onFeedback({type:H,messageId:Ce.id,message:Ce})}}}),je.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let S=y.getAttribute("data-message-id");if(!S)return;let H=h.getAttribute("data-approval-action");if(!H)return;let z=H==="approve"?"approved":"denied",B=_.getMessages().find(ae=>ae.id===S);if(!(B!=null&&B.approval))return;let se=y.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),B.approval.toolType==="webmcp"?_.resolveWebMcpApproval(S,z):_.resolveApproval(B.approval,z)});let Ct=null,Fn=null,On={artifacts:[],selectedId:null},Sn=!1,St={current:null};je.addEventListener("click",l=>{var Z,be,Fe,Ce,nt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Fe=(be=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Fe.call(be,{type:"download",artifactId:y}))===!0)return;let H=_.getArtifactById(y),z=H==null?void 0:H.markdown,O=(H==null?void 0:H.title)||"artifact";if(!z){let $e=h.closest("[data-open-artifact]"),gt=$e==null?void 0:$e.closest("[data-message-id]"),st=gt==null?void 0:gt.getAttribute("data-message-id");if(st){let We=_.getMessages().find(ze=>ze.id===st);if(We!=null&&We.rawContent)try{let ze=JSON.parse(We.rawContent);z=(Ce=ze==null?void 0:ze.props)==null?void 0:Ce.markdown,O=((nt=ze==null?void 0:ze.props)==null?void 0:nt.title)||O}catch{}}}if(!z)return;let B=new Blob([z],{type:"text/markdown"}),se=URL.createObjectURL(B),ae=document.createElement("a");ae.href=se,ae.download=`${O}.md`,ae.click(),URL.revokeObjectURL(se)}),je.addEventListener("click",l=>{var H,z,O;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||((O=(z=(H=r.features)==null?void 0:H.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:O.call(z,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,_.selectArtifact(y),Un())}),je.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Yn=J.composerOverlay,Zn=(l,p,h)=>{var O,B,se,ae;let y=p.trim();if(!y||!St.current)return;let S=(O=l.getAttribute("data-tool-call-id"))!=null?O:"",H=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:y,answers:h.structured,values:(B=h.values)!=null?B:h.source==="multi"?y.split(", "):[y],isFreeText:H,source:h.source},bubbles:!0,composed:!0})),ts(Yn,S);let z=St.current.getMessages().find(Z=>{var be;return((be=Z.toolCall)==null?void 0:be.id)===S});(se=z==null?void 0:z.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(z,(ae=h.structured)!=null?ae:y):St.current.sendMessage(y)},_n=l=>{var S;let p=St.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",y=p.getMessages().find(H=>{var z;return((z=H.toolCall)==null?void 0:z.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:ba(l,y),currentIndex:sr(l)})},Qr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Wr=l=>{var S,H,z;if(((H=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:H.groupedAutoAdvance)===!1)return;let p=sr(l),h=es(l);if(p>=h-1)return;let y=(z=St.current)==null?void 0:z.getMessages().find(O=>{var B;return((B=O.toolCall)==null?void 0:B.id)===l.getAttribute("data-tool-call-id")});y&&(xa(l,y,r,p+1),_n(l))};Yn.addEventListener("click",l=>{var H,z,O,B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Be=(H=y.getAttribute("data-tool-call-id"))!=null?H:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be);let We=(z=St.current)==null?void 0:z.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Be});(O=We==null?void 0:We.agentMetadata)!=null&&O.awaitingLocalTool&&((B=St.current)==null||B.markAskUserQuestionResolved(We),(se=St.current)==null||se.resolveAskUserQuestion(We,"(dismissed)"));return}if(S==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let We=y.getAttribute("data-multi-select")==="true",ze=io(y);if(ze&&We){let Ke=Po(y)[sr(y)],bt=new Set(Array.isArray(Ke)?Ke:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),lo(y,Array.from(bt)),_n(y);return}if(ze){lo(y,Be),_n(y),Wr(y);return}if(We){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let bt=y.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=Si(y).length===0);return}Zn(y,Be,{source:"pick",values:[Be]});return}if(S==="submit-multi"){let Be=Si(y);if(Be.length===0)return;Zn(y,Be.join(", "),{source:"multi",values:Be});return}if(S==="open-free-text"){let Be=y.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let We=Be.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(S==="focus-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(S==="submit-free-text"){let Be=y.querySelector('[data-ask-free-text-input="true"]'),We=(ae=Be==null?void 0:Be.value)!=null?ae:"";if(!We.trim())return;if(io(y)){lo(y,We.trim()),_n(y),Wr(y);return}Zn(y,We,{source:"free-text"});return}if(S==="next"||S==="back"){if(!St.current)return;let Be=(Z=y.getAttribute("data-tool-call-id"))!=null?Z:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(be=ze==null?void 0:ze.value)==null?void 0:be.trim())!=null?Fe:"";if(Ke){let Ne=Po(y)[sr(y)];(typeof Ne!="string"||Ne!==Ke)&&lo(y,Ke)}let bt=S==="next"?1:-1,P=sr(y)+bt;xa(y,We,r,P),_n(y);return}if(S==="submit-all"){if(!St.current)return;let Be=(Ce=y.getAttribute("data-tool-call-id"))!=null?Ce:"",We=St.current.getMessages().find(Ne=>{var De;return((De=Ne.toolCall)==null?void 0:De.id)===Be});if(!We)return;let ze=y.querySelector('[data-ask-free-text-input="true"]'),Ke=($e=(nt=ze==null?void 0:ze.value)==null?void 0:nt.trim())!=null?$e:"";Ke&&lo(y,Ke);let bt=ba(y,We);St.current.persistAskUserQuestionProgress(We,{answers:bt,currentIndex:sr(y)});let P=Qr(bt);Zn(y,P||"(submitted)",{source:"submit-all",structured:bt});return}if(S==="skip"){if(!St.current)return;let Be=(gt=y.getAttribute("data-tool-call-id"))!=null?gt:"",We=St.current.getMessages().find(De=>{var ge;return((ge=De.toolCall)==null?void 0:ge.id)===Be});if(!We)return;let ze=io(y),Ke=sr(y),bt=es(y),P=Ke>=bt-1;if(!ze){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ts(Yn,Be),(st=We.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(We),St.current.resolveAskUserQuestion(We,"(dismissed)"));return}lo(y,"");let Ne=y.querySelector('[data-ask-free-text-input="true"]');if(Ne&&(Ne.value=""),P){let De=ba(y,We),ge=Qr(De);Zn(y,ge||"(skipped)",{source:"submit-all",structured:De});return}xa(y,We,r,Ke+1),_n(y);return}}),Yn.addEventListener("keydown",l=>{var H;if(l.key!=="Enter")return;let h=l.target;if(!((H=h.matches)!=null&&H.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let S=h.value;if(S.trim()){if(io(y)){lo(y,S.trim()),_n(y),Wr(y);return}Zn(y,S,{source:"free-text"})}});let Xr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=Yn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),H=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];H&&(l.preventDefault(),H.click())};document.addEventListener("keydown",Xr);let $n=null,Bt=null,Tn=null,er=null,Jr=()=>{};function Rr(){er==null||er(),er=null}let Yr=()=>{var z;if(!$n||!Bt)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((z=n.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let y=$n.firstElementChild;if(!y||y===Bt)return;let S=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${S}px`,Bt.style.zIndex="5";let H=y.offsetWidth-S/2;Bt.style.left=`${Math.max(0,H)}px`},xr=()=>{},Un=()=>{var h,y,S,H,z;if(!Ct||!ar(r))return;ti(n,r),ni(n,r),xr();let l=(H=(S=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:S.narrowHostMaxWidth)!=null?H:520,p=pe.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Ct.update(On),Sn?(Ct.setMobileOpen(!1),Ct.element.classList.add("persona-hidden"),(z=Ct.backdrop)==null||z.classList.add("persona-hidden")):On.artifacts.length>0&&(Ct.element.classList.remove("persona-hidden"),Ct.setMobileOpen(!0)),Jr()};if(ar(r)){pe.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ce),Ct=Am(r,{onSelect:h=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Sn=!0,Un()}}),Ct.element.classList.add("persona-hidden"),$n=p,p.appendChild(l),p.appendChild(Ct.element),Ct.backdrop&&pe.appendChild(Ct.backdrop),pe.appendChild(p),Jr=()=>{var y,S,H,z;if(!$n||!Ct)return;if(!(((H=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:H.resizable)===!0)){Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct.element.style.removeProperty("width"),Ct.element.style.removeProperty("maxWidth");return}if(!Bt){let O=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");O.setAttribute("role","separator"),O.setAttribute("aria-orientation","vertical"),O.setAttribute("aria-label","Resize artifacts panel"),O.tabIndex=0;let B=n.ownerDocument,se=(z=B.defaultView)!=null?z:window,ae=Z=>{var gt,st;if(!Ct||Z.button!==0||n.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Rr();let be=Z.clientX,Fe=Ct.element.getBoundingClientRect().width,Ce=(st=(gt=r.features)==null?void 0:gt.artifacts)==null?void 0:st.layout,nt=Be=>{let We=$n.getBoundingClientRect().width,ze=n.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Em($n,se),bt=ze?0:O.getBoundingClientRect().width||6,P=Fe-(Be.clientX-be),Ne=km(P,We,Ke,bt,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);Ct.element.style.width=`${Ne}px`,Ct.element.style.maxWidth="none",Yr()},$e=()=>{B.removeEventListener("pointermove",nt),B.removeEventListener("pointerup",$e),B.removeEventListener("pointercancel",$e),er=null;try{O.releasePointerCapture(Z.pointerId)}catch{}};er=$e,B.addEventListener("pointermove",nt),B.addEventListener("pointerup",$e),B.addEventListener("pointercancel",$e);try{O.setPointerCapture(Z.pointerId)}catch{}};O.addEventListener("pointerdown",ae),Bt=O,$n.insertBefore(O,Ct.element),Tn=()=>{O.removeEventListener("pointerdown",ae)}}if(Bt){let O=On.artifacts.length>0&&!Sn;Bt.classList.toggle("persona-hidden",!O),Yr()}},xr=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke;if(!M||!Ct||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||gn(r)&&gr(r).reveal==="emerge")return;let y=(Z=n.ownerDocument.defaultView)!=null?Z:window,S=(Fe=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Fe:!0,H=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?nt:640;if(S&&y.innerWidth<=H||!Mm(r,M))return;let z=(st=(gt=($e=r.launcher)==null?void 0:$e.width)!=null?gt:r.launcherWidth)!=null?st:qr,O=(Ke=(ze=(We=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:We.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";On.artifacts.length>0&&!Sn?(pe.style.width=O,pe.style.maxWidth=O):(pe.style.width=z,pe.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Fn=new ResizeObserver(()=>{Un()}),Fn.observe(pe))}else pe.appendChild(ce),N()&&Xe&&(J.peekBanner&&Xe.appendChild(J.peekBanner),Xe.appendChild(He));n.appendChild(Ee),Xe&&n.appendChild(Xe);let ye=()=>{var Ne,De,ge,Ft,Dt,zt,wt,Ut,Kn,Jt,Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr,Ye,an;if(N()){pe.style.width="100%",pe.style.maxWidth="100%";let _t=(De=(Ne=r.launcher)==null?void 0:Ne.composerBar)!=null?De:{},Ot=Ee.dataset.state==="expanded",ft=(ge=_t.expandedSize)!=null?ge:"anchored";if(!(Ot&&ft!=="fullscreen")){ce.style.background="",ce.style.border="",ce.style.borderRadius="",ce.style.overflow="",ce.style.boxShadow="";return}let At=(Dt=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Dt.panel,bn=Ra(r),Mn=(kn,So)=>{var Ss;return kn==null||kn===""?So:(Ss=is(bn,kn))!=null?Ss:kn},kr="1px solid var(--persona-border)",dn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",En="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ce.style.background="var(--persona-surface, #ffffff)",ce.style.border=Mn(At==null?void 0:At.border,kr),ce.style.borderRadius=Mn(At==null?void 0:At.borderRadius,En),ce.style.boxShadow=Mn(At==null?void 0:At.shadow,dn),ce.style.overflow="hidden";return}let l=gn(r),p=(wt=(zt=r.launcher)==null?void 0:zt.sidebarMode)!=null?wt:!1,h=l||p||((Kn=(Ut=r.launcher)==null?void 0:Ut.fullHeight)!=null?Kn:!1),y=((Jt=r.launcher)==null?void 0:Jt.enabled)===!1,S=(kt=(Qe=r.theme)==null?void 0:Qe.components)==null?void 0:kt.panel,H=Ra(r),z=(_t,Ot)=>{var ft;return _t==null||_t===""?Ot:(ft=is(H,_t))!=null?ft:_t},O=(nn=n.ownerDocument.defaultView)!=null?nn:window,B=(Gn=(or=r.launcher)==null?void 0:or.mobileFullscreen)!=null?Gn:!0,se=(wo=(xo=r.launcher)==null?void 0:xo.mobileBreakpoint)!=null?wo:640,ae=O.innerWidth<=se,Z=B&&ae&&M,be=(Qo=(Go=r.launcher)==null?void 0:Go.position)!=null?Qo:"bottom-left",Fe=be==="bottom-left"||be==="top-left",Ce=(Co=(jt=r.launcher)==null?void 0:jt.zIndex)!=null?Co:wn,nt=p||Z?"none":"1px solid var(--persona-border)",$e=Z?"none":p?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&($e="none",nt="none");let gt=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=z(S==null?void 0:S.border,nt),Be=z(S==null?void 0:S.shadow,$e),We=z(S==null?void 0:S.borderRadius,gt),ze=we.scrollTop;n.style.cssText="",Ee.style.cssText="",pe.style.cssText="",ce.style.cssText="",we.style.cssText="",He.style.cssText="";let Ke=()=>{var Ot;if(ze<=0)return;((Ot=we.ownerDocument.defaultView)!=null?Ot:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let ft=we.scrollHeight-we.clientHeight;ft<=0||(we.scrollTop=Math.min(ze,ft))})};if(Z){Ee.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"),Ee.style.cssText=`
|
|
34
|
+
`,L.addEventListener("click",()=>{f=A,R.forEach((O,_)=>{let H=_<A;O.classList.toggle("selected",H),O.setAttribute("aria-checked",_===A-1?"true":"false")})}),R.push(L),M.appendChild(L)}g.appendChild(M);let T=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),A.appendChild(T),g.appendChild(A)}let k=document.createElement("div");k.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(f===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=(T==null?void 0:T.value.trim())||void 0;await e(f,A),u.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),k.appendChild(E),k.appendChild(I),g.appendChild(k),u.appendChild(g),u}function Qm(t){let{onSubmit:e,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=t,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,x.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=o,x.appendChild(M),m.appendChild(x);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-nps",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=u,T.appendChild(k),T.appendChild(E);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-number-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`Rating ${U} out of 10`),F.textContent=String(U),F.dataset.rating=String(U),U<=6?F.classList.add("persona-feedback-detractor"):U<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{g=U,A.forEach((ee,Ae)=>{ee.classList.toggle("selected",Ae===U),ee.setAttribute("aria-checked",Ae===U?"true":"false")})}),A.push(F),I.appendChild(F)}R.appendChild(T),R.appendChild(I),m.appendChild(R);let L=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),U.appendChild(L),m.appendChild(U)}let O=document.createElement("div");O.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{n==null||n(),f.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let U=(L==null?void 0:L.value.trim())||void 0;await e(g,U),f.remove()}catch(U){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),O.appendChild(_),O.appendChild(H),m.appendChild(O),f.appendChild(m),f}var bs="persona-chat-history",Wy=30*1e3,Ry={"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 Hy(t){var r,o,s;if(!t)return[];let e=[],n=Array.from((r=t.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=Ry[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function ai(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function By(t){var e,n,r,o,s,a,i,d,c;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(n=t.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=t.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=t.clearOnChatClear)!=null?c:!0}:null}function Dy(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var cl=t=>!t||typeof t!="object"?{}:{...t},Xm=t=>t.map(e=>({...e,streaming:!1})),Jm=(t,e,n)=>{let r=t!=null&&t.markdown?ya(t.markdown):null,o=ba(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var u,f,g;let a=(u=s.text)!=null?u:"",i=(f=s.message.rawContent)!=null?f:null;if(e){let m=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&n&&n())}let d=Io()!==null,c;if(t!=null&&t.postprocessMessage){let m=t.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(m):m}else if(r){let m=s.streaming?Qp(a):a,x=r(m);c=o&&d?o(x):x}else c=co(a);return c}};function Ym(t){var i,d,c,u;let e=y("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=(i=t==null?void 0:t.iconName)!=null?i:"upload",r=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(c=t==null?void 0:t.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(u=t==null?void 0:t.iconStrokeWidth)!=null?u:.5,a=he(n,r,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let f=y("span","persona-drop-overlay-label");f.textContent=t.label,e.appendChild(f)}return e}var Zm=(t,e,n)=>{var zl,ql,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,xc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let r=Uu(e),o=ol.getForInstance(r.plugins),{plugin:s,teardown:a}=Em();r.components&&$o.registerAll(r.components);let i=$m(),c=r.persistState===!1?null:(zl=r.storageAdapter)!=null?zl:zm(),u={},f=null,g=!1,m=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:b}=p;return b&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")f=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return m(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=m(p);h.metadata&&(u=cl(h.metadata)),(ql=h.messages)!=null&&ql.length&&(r={...r,initialMessages:h.messages}),(jl=h.artifacts)!=null&&jl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Vl=h.selectedArtifactId)!=null?Vl:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(Kl=l.messages)!=null&&Kl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let x=()=>u,v=l=>{var h;u=(h=l({...u}))!=null?h:{},w()},M=r.actionParsers&&r.actionParsers.length?r.actionParsers:[al],R=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[aa.message,aa.messageAndClick],T=il({parsers:M,handlers:R,getSessionMetadata:x,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let k=(Ql=(Gl=r.launcher)==null?void 0:Gl.enabled)!=null?Ql:!0,E=(Jl=(Xl=r.launcher)==null?void 0:Xl.autoExpand)!=null?Jl:!1,I=(Yl=r.autoFocusInput)!=null?Yl:!1,A=E,L=k,O=(ec=(Zl=r.layout)==null?void 0:Zl.header)==null?void 0:ec.layout,_=!1,H=()=>ea(r),U=()=>k||H(),F=H()?!1:k?E:!0,ee=!1,Ae=null,pe=()=>{ee=!0,Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{ee&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ee=!1)},1e4)},te=Jm(r,T,pe),xe=(nc=(tc=r.features)==null?void 0:tc.showReasoning)!=null?nc:!0,We=(oc=(rc=r.features)==null?void 0:rc.showToolCalls)!=null?oc:!0,le=(ac=(sc=r.features)==null?void 0:sc.showEventStreamToggle)!=null?ac:!1,me=(lc=(ic=r.features)==null?void 0:ic.scrollToBottom)!=null?lc:{},re=(dc=(cc=r.features)==null?void 0:cc.scrollBehavior)!=null?dc:{},de=`${(uc=typeof r.persistState=="object"?(pc=r.persistState)==null?void 0:pc.keyPrefix:void 0)!=null?uc:"persona-"}event-stream`,ze=le?new oa(de):null,Fe=(fc=(gc=(mc=r.features)==null?void 0:mc.eventStream)==null?void 0:gc.maxEvents)!=null?fc:2e3,G=le?new ra(Fe,ze):null,X=le?new sa:null,ve=null,Y=!1,ie=null,Ee=0;ze==null||ze.open().then(()=>G==null?void 0:G.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Je={onCopy:l=>{var p,h;i.emit("message:copy",l),z!=null&&z.isClientTokenMode()&&z.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;i.emit("message:feedback",l),z!=null&&z.isClientTokenMode()&&z.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},nt=(hc=r.statusIndicator)!=null?hc:{},wt=l=>{var p,h,b,S;return l==="idle"?(p=nt.idleText)!=null?p:An.idle:l==="connecting"?(h=nt.connectingText)!=null?h:An.connecting:l==="connected"?(b=nt.connectedText)!=null?b:An.connected:l==="error"?(S=nt.errorText)!=null?S:An.error:An[l]};function dt(l,p,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=p,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=p}let tt=gm({config:r,showClose:U()}),{wrapper:He,panel:Q,pillRoot:Ve}=tt.shell,je=tt.panelElements,{container:we,body:Se,messagesWrapper:Ye,suggestions:Qe,textarea:Te,sendButton:_e,sendButtonWrapper:pn,composerForm:Ft,statusText:Yt,introTitle:Rr,introSubtitle:B,closeButton:K,iconHolder:ue,headerTitle:Be,headerSubtitle:$e,header:De,footer:Le,actionsRow:it,leftActions:Wt,rightActions:yt}=je,Rt=je.setSendButtonMode,P=je.micButton,ce=je.micButtonWrapper,Me=je.attachmentButton,Mt=je.attachmentButtonWrapper,Ze=je.attachmentInput,qt=je.attachmentPreviewsContainer;we.classList.add("persona-relative"),Se.classList.add("persona-relative");let yn=12,vt=()=>{var l;return(l=me.label)!=null?l:""},xt=()=>{var l;return(l=me.iconName)!=null?l:"arrow-down"},Ht=()=>me.enabled!==!1,Ct=()=>{var l;return(l=re.mode)!=null?l:"follow"},un=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Ut=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Ut.type="button",Ut.style.display="none",Ut.setAttribute("data-persona-scroll-to-bottom","true");let On=y("span","persona-flex persona-items-center"),En=y("span",""),Mn=y("span","");Mn.setAttribute("data-persona-scroll-to-bottom-count",""),Mn.style.display="none",Ut.append(On,En,Mn),we.appendChild(Ut);let vn=y("div","persona-stream-anchor-spacer");vn.setAttribute("aria-hidden","true"),vn.setAttribute("data-persona-anchor-spacer",""),vn.style.flexShrink="0",vn.style.pointerEvents="none",vn.style.height="0px",Se.appendChild(vn);let kn=()=>{let p=Le.style.display==="none"?0:Le.offsetHeight;Ut.style.bottom=`${p+yn}px`};kn();let lr=()=>{let l=!!vt();Ut.setAttribute("aria-label",vt()||"Jump to latest"),Ut.title=vt(),Ut.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),On.innerHTML="";let p=he(xt(),"14px","currentColor",2);p?(On.appendChild(p),On.style.display=""):On.style.display="none",En.textContent=vt(),En.style.display=l?"":"none"};lr();let At=null,br=null,vr=o.find(l=>l.renderHeader);if(vr!=null&&vr.renderHeader){let l=vr.renderHeader({config:r,defaultRenderer:()=>{let p=No({config:r,showClose:U()});return ta(we,p,r),p.header},onClose:()=>jt(!1,"user")});if(l){let p=we.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),De=l,tt.header.element=l)}}let Hr=()=>{var p,h,b,S;if(!G)return;if(Y=!0,!ve&&G&&(ve=Im({buffer:G,getFullHistory:()=>G.getAllFromStore(),onClose:()=>cr(),config:r,plugins:o,getThroughput:()=>{var D;return(D=X==null?void 0:X.getMetric())!=null?D:{status:"idle"}}})),ve&&(Se.style.display="none",(p=Le.parentNode)==null||p.insertBefore(ve.element,Le),ve.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Hn.actionIconColor}`;let D=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;D&&D.split(/\s+/).forEach(V=>V&&ut.classList.add(V))}let l=()=>{if(!Y)return;let D=Date.now();D-Ee>=200&&(ve==null||ve.update(),Ee=D),ie=requestAnimationFrame(l)};Ee=0,ie=requestAnimationFrame(l),Vn(),i.emit("eventStream:opened",{timestamp:Date.now()})},cr=()=>{var l,p,h;if(Y){if(Y=!1,ve&&ve.element.remove(),Se.style.display="",ut){ut.style.boxShadow="";let b=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&ut.classList.remove(S))}ie!==null&&(cancelAnimationFrame(ie),ie=null),Vn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(le){let l=(bc=(yc=r.features)==null?void 0:yc.eventStream)==null?void 0:bc.classNames,p="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ut=y("button",p),ut.style.width="28px",ut.style.height="28px",ut.style.color=Hn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=he("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=je.clearChatButtonWrapper,S=je.closeButtonWrapper,D=b||S;D&&D.parentNode===De?De.insertBefore(ut,D):De.appendChild(ut),ut.addEventListener("click",()=>{Y?cr():Hr()})}let yo=l=>{var S,D,V,$,N;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let se=l.querySelector("[data-persona-composer-form]");se!=null&&se.parentNode?se.parentNode.insertBefore(h,se):l.insertBefore(h,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let se=y("input");se.type="file",se.setAttribute("data-persona-composer-attachment-input",""),se.accept=((V=p.allowedTypes)!=null?V:jr).join(","),se.multiple=(($=p.maxFiles)!=null?$:4)>1,se.style.display="none",se.setAttribute("aria-label",(N=p.buttonTooltipText)!=null?N:"Attach files"),l.appendChild(se)}},xr=o.find(l=>l.renderComposer);if(xr!=null&&xr.renderComposer){let l=r.composer,p=xr.renderComposer({config:r,defaultRenderer:()=>ei({config:r}).footer,onSubmit:h=>{var V;if(!z||z.isStreaming())return;let b=h.trim(),S=(V=At==null?void 0:At.hasAttachments())!=null?V:!1;if(!b&&!S)return;xl();let D;S&&(D=[],D.push(...At.getContentParts()),b&&D.push(Wi(b))),z.sendMessage(b,{contentParts:D}),S&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ze==null||Ze.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((vc=r.voiceRecognition)==null?void 0:vc.enabled)===!0?()=>{br==null||br()}:void 0});p&&(tt.replaceComposer(p),Le=tt.composer.footer)}let bo=l=>{let p=(...ae)=>{for(let Z of ae){let be=l.querySelector(Z);if(be)return be}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),V=l.querySelector("[data-persona-composer-status]");h&&(Ft=h),b&&(Te=b),S&&(_e=S),D&&(P=D,ce=D.parentElement),V&&(Yt=V);let $=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(Qe=$);let N=p("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(Me=N,Mt=N.parentElement),Ze=p("[data-persona-composer-attachment-input]",'input[type="file"]'),qt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(it=se)};yo(Le),bo(Le);let Bn=(Sc=(xc=r.layout)==null?void 0:xc.contentMaxWidth)!=null?Sc:H()?(Ac=(Cc=(wc=r.launcher)==null?void 0:wc.composerBar)==null?void 0:Cc.contentMaxWidth)!=null?Ac:"720px":void 0;if(Bn&&(Ye.style.maxWidth=Bn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%"),Bn&&Ft&&!H()&&(Ft.style.maxWidth=Bn,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Bn&&Qe&&!H()&&(Qe.style.maxWidth=Bn,Qe.style.marginLeft="auto",Qe.style.marginRight="auto"),Bn&&qt&&!H()&&(qt.style.maxWidth=Bn,qt.style.marginLeft="auto",qt.style.marginRight="auto"),(Tc=r.attachments)!=null&&Tc.enabled&&Ze&&qt){At=Vs.fromConfig(r.attachments),At.setPreviewsContainer(qt),Ze.addEventListener("change",h=>{let b=h.target;At==null||At.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,p=Ym(l);we.appendChild(p)}(()=>{var b,S;let l=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},p=D=>{switch(D){case"body-top":return we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ye;case"footer-top":return Qe;case"composer":return Ft;case"footer-bottom":return Yt;default:return null}},h=(D,V)=>{var $;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")De.insertBefore(V,De.firstChild);else if(D==="header-right")De.appendChild(V);else{let N=De.querySelector(".persona-flex-col");N?($=N.parentNode)==null||$.insertBefore(V,N.nextSibling):De.appendChild(V)}break;case"body-top":{let N=Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(V):Se.insertBefore(V,Se.firstChild);break}case"body-bottom":Se.appendChild(V);break;case"footer-top":Qe.replaceWith(V);break;case"footer-bottom":Yt.replaceWith(V);break;default:break}};for(let[D,V]of Object.entries(l))if(V)try{let $=V({config:r,defaultContent:()=>p(D)});$&&h(D,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,$)}})();let Gr=l=>{var V,$;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")fs.has(S)?fs.delete(S):fs.add(S),ym(S,b);else if(D==="tool")hs.has(S)?hs.delete(S):hs.add(S),bm(S,b,r);else if(D==="approval"){let N=r.approval!==!1?r.approval:void 0,se=((V=N==null?void 0:N.detailsDisplay)!=null?V:"collapsed")==="expanded",ae=($=Fo.get(S))!=null?$:se;Fo.set(S,!ae),Cm(S,b,r)}Tr.delete(S)};Ye.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),Ye.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),Ye.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=Ye.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),D=Qu(S);!D||D===S||(p.setData("text/plain",D),l.preventDefault())});let Br=new Map,Qr=null,Xr="idle",vo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},xo=(l,p)=>{let{icon:h,label:b}=vo[p];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let S=he(h,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Jr=()=>{Ye.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var D;let h=p.closest("[data-actions-for]"),b=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;xo(p,b&&b===Qr?Xr:"idle")})};Ye.addEventListener("click",l=>{var V;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let D=h.getAttribute("data-action");if(D==="copy"){let N=z.getMessages().find(se=>se.id===S);if(N&&Je.onCopy){let se=N.content||"";navigator.clipboard.writeText(se).then(()=>{h.classList.add("persona-message-action-success");let ae=he("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Z=he("copy",14,"currentColor",2);Z&&(h.innerHTML="",h.appendChild(Z))},2e3)}).catch(ae=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ae)}),Je.onCopy(N)}}else if(D==="read-aloud")z.toggleReadAloud(S);else if(D==="upvote"||D==="downvote"){let N=((V=Br.get(S))!=null?V:null)===D,se=D==="upvote"?"thumbs-up":"thumbs-down";if(N){Br.delete(S),h.classList.remove("persona-message-action-active");let ae=he(se,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=D==="upvote"?"downvote":"upvote",Z=b.querySelector(`[data-action="${ae}"]`);if(Z){Z.classList.remove("persona-message-action-active");let Ue=he(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Z.innerHTML="",Z.appendChild(Ue))}Br.set(S,D),h.classList.add("persona-message-action-active");let be=he(se,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(be)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ce=z.getMessages().find(et=>et.id===S);Ce&&Je.onFeedback&&Je.onFeedback({type:D,messageId:Ce.id,message:Ce})}}}),Ye.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let D=h.getAttribute("data-approval-action");if(!D)return;let V=D==="approve"?"approved":"denied",N=z.getMessages().find(ae=>ae.id===S);if(!(N!=null&&N.approval))return;let se=b.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(Z=>{Z.disabled=!0,Z.style.opacity="0.5",Z.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?z.resolveWebMcpApproval(S,V):z.resolveApproval(N.approval,V)});let bt=null,_n=null,$n={artifacts:[],selectedId:null},Ln=!1,St={current:null};Ye.addEventListener("click",l=>{var Z,be,Ne,Ce,et;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Ne=(be=(Z=r.features)==null?void 0:Z.artifacts)==null?void 0:be.onArtifactAction)==null?void 0:Ne.call(be,{type:"download",artifactId:b}))===!0)return;let D=z.getArtifactById(b),V=D==null?void 0:D.markdown,$=(D==null?void 0:D.title)||"artifact";if(!V){let Ue=h.closest("[data-open-artifact]"),ct=Ue==null?void 0:Ue.closest("[data-message-id]"),rt=ct==null?void 0:ct.getAttribute("data-message-id");if(rt){let ke=z.getMessages().find(qe=>qe.id===rt);if(ke!=null&&ke.rawContent)try{let qe=JSON.parse(ke.rawContent);V=(Ce=qe==null?void 0:qe.props)==null?void 0:Ce.markdown,$=((et=qe==null?void 0:qe.props)==null?void 0:et.title)||$}catch{}}}if(!V)return;let N=new Blob([V],{type:"text/markdown"}),se=URL.createObjectURL(N),ae=document.createElement("a");ae.href=se,ae.download=`${$}.md`,ae.click(),URL.revokeObjectURL(se)}),Ye.addEventListener("click",l=>{var D,V,$;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||(($=(V=(D=r.features)==null?void 0:D.artifacts)==null?void 0:V.onArtifactAction)==null?void 0:$.call(V,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Ln=!1,z.selectArtifact(b),Dn())}),Ye.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Yn=je.composerOverlay,Zn=(l,p,h)=>{var $,N,se,ae;let b=p.trim();if(!b||!St.current)return;let S=($=l.getAttribute("data-tool-call-id"))!=null?$:"",D=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?b.split(", "):[b],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),is(Yn,S);let V=St.current.getMessages().find(Z=>{var be;return((be=Z.toolCall)==null?void 0:be.id)===S});(se=V==null?void 0:V.agentMetadata)!=null&&se.awaitingLocalTool?St.current.resolveAskUserQuestion(V,(ae=h.structured)!=null?ae:b):St.current.sendMessage(b)},Un=l=>{var S;let p=St.current;if(!p)return;let h=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",b=p.getMessages().find(D=>{var V;return((V=D.toolCall)==null?void 0:V.id)===h});b&&p.persistAskUserQuestionProgress(b,{answers:wa(l,b),currentIndex:ar(l)})},Yr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Dr=l=>{var S,D,V;if(((D=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let p=ar(l),h=as(l);if(p>=h-1)return;let b=(V=St.current)==null?void 0:V.getMessages().find($=>{var N;return((N=$.toolCall)==null?void 0:N.id)===l.getAttribute("data-tool-call-id")});b&&(Aa(l,b,r,p+1),Un(l))};Yn.addEventListener("click",l=>{var D,V,$,N,se,ae,Z,be,Ne,Ce,et,Ue,ct,rt;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Pe=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),is(Yn,Pe);let ke=(V=St.current)==null?void 0:V.getMessages().find(qe=>{var Ke;return((Ke=qe.toolCall)==null?void 0:Ke.id)===Pe});($=ke==null?void 0:ke.agentMetadata)!=null&&$.awaitingLocalTool&&((N=St.current)==null||N.markAskUserQuestionResolved(ke),(se=St.current)==null||se.resolveAskUserQuestion(ke,"(dismissed)"));return}if(S==="pick"){let Pe=h.getAttribute("data-option-label");if(!Pe)return;let ke=b.getAttribute("data-multi-select")==="true",qe=uo(b);if(qe&&ke){let Ke=Ro(b)[ar(b)],ft=new Set(Array.isArray(Ke)?Ke:[]);ft.has(Pe)?ft.delete(Pe):ft.add(Pe),mo(b,Array.from(ft)),Un(b);return}if(qe){mo(b,Pe),Un(b),Dr(b);return}if(ke){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let ft=b.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=Ei(b).length===0);return}Zn(b,Pe,{source:"pick",values:[Pe]});return}if(S==="submit-multi"){let Pe=Ei(b);if(Pe.length===0)return;Zn(b,Pe.join(", "),{source:"multi",values:Pe});return}if(S==="open-free-text"){let Pe=b.querySelector('[data-ask-free-text-row="true"]');if(Pe){Pe.classList.remove("persona-hidden");let ke=Pe.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(S==="focus-free-text"){let Pe=b.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus();return}if(S==="submit-free-text"){let Pe=b.querySelector('[data-ask-free-text-input="true"]'),ke=(ae=Pe==null?void 0:Pe.value)!=null?ae:"";if(!ke.trim())return;if(uo(b)){mo(b,ke.trim()),Un(b),Dr(b);return}Zn(b,ke,{source:"free-text"});return}if(S==="next"||S==="back"){if(!St.current)return;let Pe=(Z=b.getAttribute("data-tool-call-id"))!=null?Z:"",ke=St.current.getMessages().find(Re=>{var Ie;return((Ie=Re.toolCall)==null?void 0:Ie.id)===Pe});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ne=(be=qe==null?void 0:qe.value)==null?void 0:be.trim())!=null?Ne:"";if(Ke){let Re=Ro(b)[ar(b)];(typeof Re!="string"||Re!==Ke)&&mo(b,Ke)}let ft=S==="next"?1:-1,W=ar(b)+ft;Aa(b,ke,r,W),Un(b);return}if(S==="submit-all"){if(!St.current)return;let Pe=(Ce=b.getAttribute("data-tool-call-id"))!=null?Ce:"",ke=St.current.getMessages().find(Re=>{var Ie;return((Ie=Re.toolCall)==null?void 0:Ie.id)===Pe});if(!ke)return;let qe=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(et=qe==null?void 0:qe.value)==null?void 0:et.trim())!=null?Ue:"";Ke&&mo(b,Ke);let ft=wa(b,ke);St.current.persistAskUserQuestionProgress(ke,{answers:ft,currentIndex:ar(b)});let W=Yr(ft);Zn(b,W||"(submitted)",{source:"submit-all",structured:ft});return}if(S==="skip"){if(!St.current)return;let Pe=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",ke=St.current.getMessages().find(Ie=>{var ge;return((ge=Ie.toolCall)==null?void 0:ge.id)===Pe});if(!ke)return;let qe=uo(b),Ke=ar(b),ft=as(b),W=Ke>=ft-1;if(!qe){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Pe},bubbles:!0,composed:!0})),is(Yn,Pe),(rt=ke.agentMetadata)!=null&&rt.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(ke),St.current.resolveAskUserQuestion(ke,"(dismissed)"));return}mo(b,"");let Re=b.querySelector('[data-ask-free-text-input="true"]');if(Re&&(Re.value=""),W){let Ie=wa(b,ke),ge=Yr(Ie);Zn(b,ge||"(skipped)",{source:"submit-all",structured:Ie});return}Aa(b,ke,r,Ke+1),Un(b);return}}),Yn.addEventListener("keydown",l=>{var D;if(l.key!=="Enter")return;let h=l.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let S=h.value;if(S.trim()){if(uo(b)){mo(b,S.trim()),Un(b),Dr(b);return}Zn(b,S,{source:"free-text"})}});let Zr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=Yn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];D&&(l.preventDefault(),D.click())};document.addEventListener("keydown",Zr);let zn=null,Bt=null,Pn=null,er=null,eo=()=>{};function Nr(){er==null||er(),er=null}let to=()=>{var V;if(!zn||!Bt)return;let l=t.classList.contains("persona-artifact-appearance-seamless"),h=((V=t.ownerDocument.defaultView)!=null?V:window).innerWidth<=640;if(!l||t.classList.contains("persona-artifact-narrow-host")||h){Bt.style.removeProperty("position"),Bt.style.removeProperty("left"),Bt.style.removeProperty("top"),Bt.style.removeProperty("bottom"),Bt.style.removeProperty("width"),Bt.style.removeProperty("z-index");return}let b=zn.firstElementChild;if(!b||b===Bt)return;let S=10;Bt.style.position="absolute",Bt.style.top="0",Bt.style.bottom="0",Bt.style.width=`${S}px`,Bt.style.zIndex="5";let D=b.offsetWidth-S/2;Bt.style.left=`${Math.max(0,D)}px`},ye=()=>{},Dn=()=>{var h,b,S,D,V;if(!bt||!ir(r))return;oi(t,r),si(t,r),ye();let l=(D=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?D:520,p=Q.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),bt.update($n),Ln?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(V=bt.backdrop)==null||V.classList.add("persona-hidden")):$n.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),eo()};if(ir(r)){Q.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(we),bt=Hm(r,{onSelect:h=>{var b;return(b=St.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Ln=!0,Dn()}}),bt.element.classList.add("persona-hidden"),zn=p,p.appendChild(l),p.appendChild(bt.element),bt.backdrop&&Q.appendChild(bt.backdrop),Q.appendChild(p),eo=()=>{var b,S,D,V;if(!zn||!bt)return;if(!(((D=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:D.resizable)===!0)){Pn==null||Pn(),Pn=null,Nr(),Bt&&(Bt.remove(),Bt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Bt){let $=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");$.setAttribute("role","separator"),$.setAttribute("aria-orientation","vertical"),$.setAttribute("aria-label","Resize artifacts panel"),$.tabIndex=0;let N=t.ownerDocument,se=(V=N.defaultView)!=null?V:window,ae=Z=>{var ct,rt;if(!bt||Z.button!==0||t.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;Z.preventDefault(),Nr();let be=Z.clientX,Ne=bt.element.getBoundingClientRect().width,Ce=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,et=Pe=>{let ke=zn.getBoundingClientRect().width,qe=t.classList.contains("persona-artifact-appearance-seamless"),Ke=qe?0:Fm(zn,se),ft=qe?0:$.getBoundingClientRect().width||6,W=Ne-(Pe.clientX-be),Re=Om(W,ke,Ke,ft,Ce==null?void 0:Ce.resizableMinWidth,Ce==null?void 0:Ce.resizableMaxWidth);bt.element.style.width=`${Re}px`,bt.element.style.maxWidth="none",to()},Ue=()=>{N.removeEventListener("pointermove",et),N.removeEventListener("pointerup",Ue),N.removeEventListener("pointercancel",Ue),er=null;try{$.releasePointerCapture(Z.pointerId)}catch{}};er=Ue,N.addEventListener("pointermove",et),N.addEventListener("pointerup",Ue),N.addEventListener("pointercancel",Ue);try{$.setPointerCapture(Z.pointerId)}catch{}};$.addEventListener("pointerdown",ae),Bt=$,zn.insertBefore($,bt.element),Pn=()=>{$.removeEventListener("pointerdown",ae)}}if(Bt){let $=$n.artifacts.length>0&&!Ln;Bt.classList.toggle("persona-hidden",!$),to()}},ye=()=>{var se,ae,Z,be,Ne,Ce,et,Ue,ct,rt,Pe,ke,qe,Ke;if(!k||!bt||((ae=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?ae:!1)||bn(r)&&hr(r).reveal==="emerge")return;let b=(Z=t.ownerDocument.defaultView)!=null?Z:window,S=(Ne=(be=r.launcher)==null?void 0:be.mobileFullscreen)!=null?Ne:!0,D=(et=(Ce=r.launcher)==null?void 0:Ce.mobileBreakpoint)!=null?et:640;if(S&&b.innerWidth<=D||!Nm(r,k))return;let V=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:Vr,$=(Ke=(qe=(ke=(Pe=r.features)==null?void 0:Pe.artifacts)==null?void 0:ke.layout)==null?void 0:qe.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";$n.artifacts.length>0&&!Ln?(Q.style.width=$,Q.style.maxWidth=$):(Q.style.width=V,Q.style.maxWidth=V)},typeof ResizeObserver!="undefined"&&(_n=new ResizeObserver(()=>{Dn()}),_n.observe(Q))}else Q.appendChild(we),H()&&Ve&&(je.peekBanner&&Ve.appendChild(je.peekBanner),Ve.appendChild(Le));t.appendChild(He),Ve&&t.appendChild(Ve);let wr=()=>{var Re,Ie,ge,Ot,Dt,Qt,ht,Vt,Kn,nn,Ge,kt,on,or,Gn,To,Eo,es,ts,Xt,Mo,ao,io,Ur,ko,mr,Pr,Xe;if(H()){Q.style.width="100%",Q.style.maxWidth="100%";let _t=(Ie=(Re=r.launcher)==null?void 0:Re.composerBar)!=null?Ie:{},Gt=He.dataset.state==="expanded",$t=(ge=_t.expandedSize)!=null?ge:"anchored";if(!(Gt&&$t!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let Lt=(Dt=(Ot=r.theme)==null?void 0:Ot.components)==null?void 0:Dt.panel,zt=Da(r),gn=(hn,sr)=>{var lo;return hn==null||hn===""?sr:(lo=us(zt,hn))!=null?lo:hn},Qn="1px solid var(--persona-border)",Ir="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",fn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=gn(Lt==null?void 0:Lt.border,Qn),we.style.borderRadius=gn(Lt==null?void 0:Lt.borderRadius,fn),we.style.boxShadow=gn(Lt==null?void 0:Lt.shadow,Ir),we.style.overflow="hidden";return}let l=bn(r),p=(ht=(Qt=r.launcher)==null?void 0:Qt.sidebarMode)!=null?ht:!1,h=l||p||((Kn=(Vt=r.launcher)==null?void 0:Vt.fullHeight)!=null?Kn:!1),b=((nn=r.launcher)==null?void 0:nn.enabled)===!1,S=(kt=(Ge=r.theme)==null?void 0:Ge.components)==null?void 0:kt.panel,D=Da(r),V=(_t,Gt)=>{var $t;return _t==null||_t===""?Gt:($t=us(D,_t))!=null?$t:_t},$=(on=t.ownerDocument.defaultView)!=null?on:window,N=(Gn=(or=r.launcher)==null?void 0:or.mobileFullscreen)!=null?Gn:!0,se=(Eo=(To=r.launcher)==null?void 0:To.mobileBreakpoint)!=null?Eo:640,ae=$.innerWidth<=se,Z=N&&ae&&k,be=(ts=(es=r.launcher)==null?void 0:es.position)!=null?ts:"bottom-left",Ne=be==="bottom-left"||be==="top-left",Ce=(Mo=(Xt=r.launcher)==null?void 0:Xt.zIndex)!=null?Mo:Sn,et=p||Z?"none":"1px solid var(--persona-border)",Ue=Z?"none":p?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Z&&(Ue="none",et="none");let ct=p||Z?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=V(S==null?void 0:S.border,et),Pe=V(S==null?void 0:S.shadow,Ue),ke=V(S==null?void 0:S.borderRadius,ct),qe=Se.scrollTop;t.style.cssText="",He.style.cssText="",Q.style.cssText="",we.style.cssText="",Se.style.cssText="",Le.style.cssText="";let Ke=()=>{var Gt;if(qe<=0)return;((Gt=Se.ownerDocument.defaultView)!=null?Gt:window).requestAnimationFrame(()=>{if(Se.scrollTop===qe)return;let $t=Se.scrollHeight-Se.clientHeight;$t<=0||(Se.scrollTop=Math.min(qe,$t))})};if(Z){He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),He.style.cssText=`
|
|
33
35
|
position: fixed !important;
|
|
34
36
|
inset: 0 !important;
|
|
35
37
|
width: 100% !important;
|
|
@@ -41,7 +43,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
41
43
|
flex-direction: column !important;
|
|
42
44
|
z-index: ${Ce} !important;
|
|
43
45
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
44
|
-
`,
|
|
46
|
+
`,Q.style.cssText=`
|
|
45
47
|
position: relative !important;
|
|
46
48
|
display: flex !important;
|
|
47
49
|
flex-direction: column !important;
|
|
@@ -54,7 +56,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
54
56
|
padding: 0 !important;
|
|
55
57
|
box-shadow: none !important;
|
|
56
58
|
border-radius: 0 !important;
|
|
57
|
-
`,
|
|
59
|
+
`,we.style.cssText=`
|
|
58
60
|
display: flex !important;
|
|
59
61
|
flex-direction: column !important;
|
|
60
62
|
flex: 1 1 0% !important;
|
|
@@ -65,7 +67,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
65
67
|
overflow: hidden !important;
|
|
66
68
|
border-radius: 0 !important;
|
|
67
69
|
border: none !important;
|
|
68
|
-
`,
|
|
70
|
+
`,Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",Le.style.flexShrink="0",_=!0,Ke();return}let ft=(io=(ao=r==null?void 0:r.launcher)==null?void 0:ao.width)!=null?io:r==null?void 0:r.launcherWidth,W=ft!=null?ft:Vr;if(!p&&!l)b&&h?(Q.style.width="100%",Q.style.maxWidth="100%"):(Q.style.width=W,Q.style.maxWidth=W);else if(l)if(hr(r).reveal==="emerge"){let Gt=hr(r).width;Q.style.width=Gt,Q.style.maxWidth=Gt}else Q.style.width="100%",Q.style.maxWidth="100%";if(ye(),Q.style.boxShadow=Pe,Q.style.borderRadius=ke,we.style.border=rt,we.style.borderRadius=ke,l&&!Z&&(S==null?void 0:S.border)===void 0&&(we.style.border="none",hr(r).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",b&&(t.style.width="100%"),He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.height="100%",b&&(He.style.overflow="hidden"),Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.height="100%",Q.style.overflow="hidden",we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.overflow="hidden",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.overflowY="auto",Le.style.flexShrink="0"),He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!p&&!b&&!l&&((Ur=yr[be])!=null?Ur:yr["bottom-right"]).split(" ").forEach(Gt=>He.classList.add(Gt)),p){let _t=(mr=(ko=r.launcher)==null?void 0:ko.sidebarWidth)!=null?mr:"420px";He.style.cssText=`
|
|
69
71
|
position: fixed !important;
|
|
70
72
|
top: 0 !important;
|
|
71
73
|
bottom: 0 !important;
|
|
@@ -77,8 +79,8 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
77
79
|
display: flex !important;
|
|
78
80
|
flex-direction: column !important;
|
|
79
81
|
z-index: ${Ce} !important;
|
|
80
|
-
${
|
|
81
|
-
`,
|
|
82
|
+
${Ne?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
83
|
+
`,Q.style.cssText=`
|
|
82
84
|
position: relative !important;
|
|
83
85
|
display: flex !important;
|
|
84
86
|
flex-direction: column !important;
|
|
@@ -89,9 +91,9 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
89
91
|
min-height: 0 !important;
|
|
90
92
|
margin: 0 !important;
|
|
91
93
|
padding: 0 !important;
|
|
92
|
-
box-shadow: ${
|
|
93
|
-
border-radius: ${
|
|
94
|
-
`,
|
|
94
|
+
box-shadow: ${Pe} !important;
|
|
95
|
+
border-radius: ${ke} !important;
|
|
96
|
+
`,Q.style.setProperty("width","100%","important"),Q.style.setProperty("max-width","100%","important"),we.style.cssText=`
|
|
95
97
|
display: flex !important;
|
|
96
98
|
flex-direction: column !important;
|
|
97
99
|
flex: 1 1 0% !important;
|
|
@@ -100,15 +102,15 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
100
102
|
min-height: 0 !important;
|
|
101
103
|
max-height: 100% !important;
|
|
102
104
|
overflow: hidden !important;
|
|
103
|
-
border-radius: ${
|
|
104
|
-
border: ${
|
|
105
|
-
`,
|
|
105
|
+
border-radius: ${ke} !important;
|
|
106
|
+
border: ${rt} !important;
|
|
107
|
+
`,Le.style.cssText=`
|
|
106
108
|
flex-shrink: 0 !important;
|
|
107
109
|
border-top: none !important;
|
|
108
110
|
padding: 8px 16px 12px 16px !important;
|
|
109
|
-
`}if(!y&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Ot=p?"":"padding-top: 1.25em !important;",ft=p?"":`z-index: ${(an=(Ye=r.launcher)==null?void 0:Ye.zIndex)!=null?an:wn} !important;`;Ee.style.cssText+=_t+Ot+ft}Ke()};ye(),ls(n,r),ti(n,r),ni(n,r);let dt=[];dt.push(()=>{document.removeEventListener("keydown",Xr)});let Qt=null,on=null;dt.push(()=>{Qt==null||Qt(),Qt=null,on==null||on(),on=null}),Fn&&dt.push(()=>{Fn==null||Fn.disconnect(),Fn=null}),dt.push(()=>{Tn==null||Tn(),Tn=null,Rr(),Bt&&(Bt.remove(),Bt=null),Ct==null||Ct.element.style.removeProperty("width"),Ct==null||Ct.element.style.removeProperty("maxWidth")}),Ie&&dt.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),K==null||K.destroy(),K=null,he==null||he.destroy(),he=null,X=null});let wr=null,fs=()=>{wr&&(wr(),wr=null),r.colorScheme==="auto"&&(wr=_u(()=>{ls(n,r)}))};fs(),dt.push(()=>{wr&&(wr(),wr=null)});let Hr=(Ac=r.features)==null?void 0:Ac.streamAnimation;if(Hr!=null&&Hr.type&&Hr.type!=="none"){let l=zs(Hr.type,Hr.plugins);l&&(Fi(l,n),dt.push(()=>em(n)))}let ho=hm(Pt),Cr=null,_,Fo=l=>{var y,S;if(!_)return;let p=l!=null?l:_.getMessages(),h=((S=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:S.enabled)!==!1?au(p):null;h?ho.render(h,_,Te,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(H=>H.role==="user")?ho.render([],_,Te,p):ho.render(r.suggestionChips,_,Te,p,r.suggestionChipsConfig)},Ar=!1,Sr=ju(),Br=new Map,Tr=new Map,lr=new Map,Oo=0,ra=Eo()!==null,qn=Da(),zn=0,cr=null,dr=!1,yo=!1,Dr=0,yn=null,Mr=null,_o=!1,bo=!1,$o=null,oa=4,Uo=24,sa=80,qo=new Map,ht={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},hs=(Tc=(Sc=r.voiceRecognition)==null?void 0:Sc.autoResume)!=null?Tc:!1,tr=l=>{s.emit("voice:state",{active:ht.active,source:l,timestamp:Date.now()})},Rn=()=>{u(l=>({...l,voiceState:{active:ht.active,timestamp:Date.now(),manuallyDeactivated:ht.manuallyDeactivated}}))},aa=()=>{var y,S;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=al(d.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);ht.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<dy&&setTimeout(()=>{var H,z;ht.active||(ht.manuallyDeactivated=!1,((z=(H=r.voiceRecognition)==null?void 0:H.provider)==null?void 0:z.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("restore"),_.isVoiceActive()&&Vo()}):ca("restore"))},1e3)},ia=()=>_?Om(_.getMessages()).filter(l=>!l.__skipPersist):[];function Zr(l){if(!(i!=null&&i.save))return;let h={messages:l?Om(l):_?ia():[],metadata:d,artifacts:On.artifacts,selectedArtifactId:On.selectedId};try{let y=i.save(h);y instanceof Promise&&y.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let tt=null,w=()=>Ee.querySelector("#persona-scroll-container")||we,U=()=>{tt!==null&&(cancelAnimationFrame(tt),tt=null),dr=!1},$=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!1,U()},Q=()=>{Dr>0?(An.textContent=String(Dr),An.style.display="",ct.setAttribute("aria-label",`${Zt()||"Jump to latest"} (${Dr} new)`)):(An.textContent="",An.style.display="none",ct.setAttribute("aria-label",Zt()||"Jump to latest"))},fe=()=>{Dr!==0&&(Dr=0,Q())},Oe=()=>et()==="follow"?!qn.isFollowing():!Ro(we,Uo),Je=()=>{if(!Ht()||te){ct.parentNode&&ct.remove(),ct.style.display="none";return}ct.parentNode!==ce&&ce.appendChild(ct),In();let p=zr(we)>0&&Oe();p||fe(),ct.style.display=p?"":"none"},Et=()=>{qn.pause()&&($(),Je())},Nr=()=>{qn.resume(),fe(),Je()},Hn=(l=!1)=>{et()==="follow"&&qn.isFollowing()&&(!l&&!Ar||(cr!==null&&(cancelAnimationFrame(cr),cr=null),yo=!0,cr=requestAnimationFrame(()=>{cr=null,yo=!1,qn.isFollowing()&&un(w(),l?220:140)})))},jn=(l,p,h,y=()=>!0)=>{let S=l.scrollTop,H=p(),z=H-S;U();let O=performance.now();dr=!0;let B=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!y()){U();return}let Z=p();Z!==H&&(H=Z,z=H-S);let be=ae-O,Fe=Math.min(be/h,1),Ce=B(Fe),nt=S+z*Ce;l.scrollTop=nt,zn=l.scrollTop,Fe<1?tt=requestAnimationFrame(se):(l.scrollTop=H,zn=l.scrollTop,tt=null,dr=!1)};tt=requestAnimationFrame(se)},un=(l,p=500)=>{let h=zr(l)-l.scrollTop;if(Math.abs(h)<1){zn=l.scrollTop;return}if(Math.abs(h)>=sa){U(),dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1;return}jn(l,()=>zr(l),p,()=>qn.isFollowing())},eo=()=>{let l=w();dr=!0,l.scrollTop=zr(l),zn=l.scrollTop,dr=!1,Je()},Fr=l=>{en.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},mn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),U(),yn=null,en.style.height="0px"},Bn=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var se;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,S=h;for(;S&&S!==we;)y+=S.offsetTop,S=S.offsetParent;let H=(se=yn==null?void 0:yn.spacerHeight)!=null?se:0,z=we.scrollHeight-H,{targetScrollTop:O,spacerHeight:B}=Xu({anchorOffsetTop:y,topOffset:Rt(),viewportHeight:we.clientHeight,contentHeight:z});yn={initialSpacerHeight:B,contentHeightAtAnchor:z,spacerHeight:B},Fr(B),jn(we,()=>O,220)})},Vn=()=>{if(et()==="follow"){if(!qn.isFollowing()||Ro(we,1))return;Hn(!Ar);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,p=Ju({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});p!==yn.spacerHeight&&Fr(p)}Je()},eg=l=>{let p=et();p==="follow"?(Nr(),Hn(!0)):p==="anchor-top"&&Bn(l)},tg=l=>{let p=new Map;l.forEach(h=>{let y=qo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(s.emit("assistant:message",h),!bo&&et()!=="anchor-top"&&Oe()&&(Dr+=1,Q(),Je())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),qo.clear(),p.forEach((h,y)=>{qo.set(y,h)})},ng=(l,p,h)=>{var st,Be,We,ze,Ke,bt;let y=document.createElement("div"),H=(()=>{var Ne;let P=o.find(De=>De.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Ne=r.loadingIndicator)!=null&&Ne.render)return r.loadingIndicator.render})(),z=(P,Ne)=>Ne==null?!1:typeof Ne=="string"?(P.textContent=Ne,!0):(P.appendChild(Ne),!0),O=new Set,B=new Set,se=o.some(P=>P.renderAskUserQuestion),ae=[],Z=[],be=r.enableComponentStreaming!==!1,Fe=o.some(P=>P.renderApproval)&&r.approval!==!1,Ce=[];if(p.forEach(P=>{var Qe,kt,nn,or,Gn,xo,wo,Go,Qo,jt,Co,ro,oo,_r,Ao,pr;O.add(P.id);let Ne=se&&Lo(P),De=Fe&&P.variant==="approval"&&!!P.approval,ge=!Ne&&P.role==="assistant"&&!P.variant&&be&&Bm(P);if(!De&&lr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),lr.delete(P.id)}if(!ge&&Tr.has(P.id)){let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime"),Tr.delete(P.id)}let Ft=Lo(P)?`:${(Qe=P.agentMetadata)!=null&&Qe.askUserQuestionAnswered?"a":"u"}:${(kt=P.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=zu(P,Oo)+Ft,zt=Ne||De||ge?null:Vu(Sr,P.id,Dt);if(zt){y.appendChild(zt.cloneNode(!0)),Lo(P)&&((nn=P.toolCall)!=null&&nn.id)&&((or=P.agentMetadata)==null?void 0:or.awaitingLocalTool)===!0&&!((Gn=P.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let wt=null,Ut=o.find(Ye=>!!(P.variant==="reasoning"&&Ye.renderReasoning||P.variant==="tool"&&Ye.renderToolCall||!P.variant&&Ye.renderMessage)),Kn=(xo=r.layout)==null?void 0:xo.messages;if(Lo(P)&&((wo=P.agentMetadata)==null?void 0:wo.askUserQuestionAnswered)===!0){Br.delete(P.id);let Ye=l.querySelector(`#wrapper-${P.id}`);Ye==null||Ye.removeAttribute("data-preserve-runtime");return}if(Mi(P)&&((Qo=(Go=r.features)==null?void 0:Go.suggestReplies)==null?void 0:Qo.enabled)!==!1)return;if(Lo(P)&&((Co=(jt=r.features)==null?void 0:jt.askUserQuestion)==null?void 0:Co.enabled)!==!1){let Ye=o.find(an=>typeof an.renderAskUserQuestion=="function");if(Ye&&St.current){let an=Br.get(P.id),_t=an!==Dt,Ot=null;if(_t){let{payload:At,complete:bn}=Zo(P),Mn=P.id,kr=()=>{var dn;return(dn=St.current)==null?void 0:dn.getMessages().find(En=>En.id===Mn)};Ot=Ye.renderAskUserQuestion({message:P,payload:At,complete:bn,resolve:dn=>{var kn;let En=kr();En&&((kn=St.current)==null||kn.resolveAskUserQuestion(En,dn))},dismiss:()=>{var En,kn,So;let dn=kr();(En=dn==null?void 0:dn.agentMetadata)!=null&&En.awaitingLocalTool&&((kn=St.current)==null||kn.markAskUserQuestionResolved(dn),(So=St.current)==null||So.resolveAskUserQuestion(dn,"(dismissed)"))},config:r})}let ft=an!=null;if(_t&&Ot===null&&!ft){((ro=P.agentMetadata)==null?void 0:ro.awaitingLocalTool)===!0&&!((oo=P.agentMetadata)!=null&&oo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-ask-plugin-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),y.appendChild(Vt),ae.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}else{((_r=P.agentMetadata)==null?void 0:_r.awaitingLocalTool)===!0&&!((Ao=P.agentMetadata)!=null&&Ao.askUserQuestionAnswered)&&(B.add(P.toolCall.id),va(P,r,J.composerOverlay));return}}else if(De){let Ye=o.find(ft=>typeof ft.renderApproval=="function"),_t=lr.get(P.id)!==Dt,Ot=null;if(_t&&(Ye!=null&&Ye.renderApproval)){let ft=P.id,Vt=(At,bn)=>{var kr,dn,En;let Mn=(kr=St.current)==null?void 0:kr.getMessages().find(kn=>kn.id===ft);Mn!=null&&Mn.approval&&(Mn.approval.toolType==="webmcp"?(dn=St.current)==null||dn.resolveWebMcpApproval(Mn.id,At):(En=St.current)==null||En.resolveApproval(Mn.approval,At,bn))};Ot=Ye.renderApproval({message:P,defaultRenderer:()=>Za(P,r),config:r,approve:At=>Vt("approved",At),deny:At=>Vt("denied",At)})}if(_t&&Ot===null){let ft=l.querySelector(`#wrapper-${P.id}`);ft==null||ft.removeAttribute("data-preserve-runtime"),lr.delete(P.id),wt=Za(P,r)}else{let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${P.id}`,ft.setAttribute("data-wrapper-id",P.id),ft.setAttribute("data-approval-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),y.appendChild(ft),Ce.push({messageId:P.id,fingerprint:Dt,bubble:Ot});return}}else if(Ut)if(P.variant==="reasoning"&&P.reasoning&&Ut.renderReasoning){if(!Ue)return;wt=Ut.renderReasoning({message:P,defaultRenderer:()=>Ki(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&Ut.renderToolCall){if(!xe)return;wt=Ut.renderToolCall({message:P,defaultRenderer:()=>Qi(P,r),config:r})}else Ut.renderMessage&&(wt=Ut.renderMessage({message:P,defaultRenderer:()=>{let Ye=Vi(P,h,Kn,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r});return P.role!=="user"&&Zi(Ye,P,r,_),Ye},config:r}));if(!wt&&ge){let Ye=Dm(P);if(Ye){let an=Tr.get(P.id),_t=an!==Dt,Ot=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Vt=Rm(Ye,{config:r,message:P,transform:h});if(Vt)if(Ot){let At=document.createElement("div");if(At.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}else{let At=document.createElement("div");if(At.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",At.id=`bubble-${P.id}`,At.setAttribute("data-message-id",P.id),At.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let bn=document.createElement("div");bn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",bn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),At.appendChild(bn)}At.appendChild(Vt),ft=At}}if(ft||an!=null){let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id=`wrapper-${P.id}`,Vt.setAttribute("data-wrapper-id",P.id),Vt.setAttribute("data-component-directive-stub","true"),Vt.setAttribute("data-preserve-runtime","true"),Ot||Vt.classList.add("persona-w-full"),y.appendChild(Vt),Z.push({messageId:P.id,fingerprint:Dt,bubble:ft});return}}}if(!wt)if(P.variant==="reasoning"&&P.reasoning){if(!Ue)return;wt=Ki(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!xe)return;wt=Qi(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;wt=Za(P,r)}else{let Ye=(pr=r.layout)==null?void 0:pr.messages;Ye!=null&&Ye.renderUserMessage&&P.role==="user"?wt=Ye.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):Ye!=null&&Ye.renderAssistantMessage&&P.role==="assistant"?wt=Ye.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):wt=Vi(P,h,Ye,r.messageActions,le,{loadingIndicatorRenderer:H,widgetConfig:r}),P.role!=="user"&&wt&&Zi(wt,P,r,_)}let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${P.id}`,Jt.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Jt.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Jt.classList.add("persona-w-full"),Jt.appendChild(wt),Ku(Sr,P.id,Dt,Jt),y.appendChild(Jt)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let De=Ne.getAttribute("data-persona-ask-sheet-for");De&&!B.has(De)&&ts(J.composerOverlay,De)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let P=[],Ne=[];p.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&xe){Ne.push(De);return}Ne.length>1&&P.push(Ne),Ne=[]}),Ne.length>1&&P.push(Ne),P.forEach((De,ge)=>{var Qe,kt;let Ft=De.map(nn=>Array.from(y.children).find(or=>or instanceof HTMLElement&&or.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Ft.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${ge}-${De[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${ge}-${De[0].id}`);let zt=document.createElement("div");zt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",zt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Ut=`Called ${De.length} tools`,Kn=(kt=(Qe=r.toolCall)==null?void 0:Qe.renderGroupedSummary)==null?void 0:kt.call(Qe,{messages:De,toolCalls:De.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:Ut,config:r});z(wt,Kn)||(wt.textContent=Ut);let Jt=document.createElement("div");Jt.className="persona-tool-group-stack persona-flex persona-flex-col",zt.append(wt,Jt),Dt.appendChild(zt),Ft[0].before(Dt),Ft.forEach((nn,or)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),or<Ft.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(nn),Jt.appendChild(Gn)})})}Gu(Sr,O);let nt=p.some(P=>P.role==="assistant"&&P.streaming),$e=p[p.length-1],gt=($e==null?void 0:$e.role)==="assistant"&&!$e.streaming&&$e.variant!=="approval";if(Ar&&p.some(P=>P.role==="user")&&!nt&&!gt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:Js},Ne=o.find(ge=>ge.renderLoadingIndicator),De=null;if(Ne!=null&&Ne.renderLoadingIndicator&&(De=Ne.renderLoadingIndicator(P)),De===null&&((We=r.loadingIndicator)!=null&&We.render)&&(De=r.loadingIndicator.render(P)),De===null&&(De=Js()),De){let ge=document.createElement("div"),Ft=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ge.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(De);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(ge),y.appendChild(Dt)}}if(!Ar&&p.length>0){let P=p[p.length-1],Ne={config:r,lastMessage:P,messageCount:p.length},De=o.find(Ft=>Ft.renderIdleIndicator),ge=null;if(De!=null&&De.renderIdleIndicator&&(ge=De.renderIdleIndicator(Ne)),ge===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Ne)),ge){let Ft=document.createElement("div"),Dt=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Ft.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ge);let zt=document.createElement("div");zt.className="persona-flex",zt.id="wrapper-idle-indicator",zt.setAttribute("data-wrapper-id","idle-indicator"),zt.appendChild(Ft),y.appendChild(zt)}}if(Ha(l,y),ae.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of ae){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Br.set(P,Ne))}if(Br.size>0)for(let P of Br.keys())O.has(P)||Br.delete(P);if(Z.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Z){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),Tr.set(P,Ne))}if(Tr.size>0)for(let P of Tr.keys())O.has(P)||Tr.delete(P);if(Ce.length>0)for(let{messageId:P,fingerprint:Ne,bubble:De}of Ce){let ge=l.querySelector(`#wrapper-${P}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Ne),lr.set(P,Ne))}if(lr.size>0)for(let P of lr.keys())O.has(P)||lr.delete(P)},ys=(l,p,h)=>{ng(l,p,h),Gr()},bs=null,rg=()=>{var h;if(bs)return;let l=y=>{let S=y.composedPath();S.includes(Ee)||Xe&&S.includes(Xe)||$t(!1,"user")};bs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},ml=()=>{var p;if(!bs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",bs,!0),bs=null};dt.push(()=>ml());let vs=null,og=()=>{var h;if(vs)return;let l=y=>{y.key==="Escape"&&(y.isComposing||$t(!1,"user"))};vs=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},gl=()=>{var p;if(!vs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",vs,!0),vs=null};dt.push(()=>gl());let xs=!1,fl=new Set,sg=()=>{var p,h,y,S;let l=(y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},zo=()=>{var gt,st,Be,We;if(!N())return;let l=J.peekBanner,p=J.peekTextNode;if(!l||!p)return;if(k){l.classList.remove("persona-pill-peek--visible");return}let h=(gt=_==null?void 0:_.getMessages())!=null?gt:[],y;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){y=Ke;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let S=y.content,H=!!y.streaming,z=sg(),O=Oa(z),B=O.type!=="none"?zs(O.type,z==null?void 0:z.plugins):null,se=((st=B==null?void 0:B.isAnimating)==null?void 0:st.call(B,y))===!0,ae=B!==null&&(H||se);ae&&B&&!fl.has(B.name)&&(Fi(B,n),fl.add(B.name));let Z=ae&&(B!=null&&B.containerClass)?B.containerClass:null,be=(Be=p.dataset.personaPeekStreamClass)!=null?Be:null;be&&be!==Z&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),Z&&be!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),ae?(p.style.setProperty("--persona-stream-step",`${O.speed}ms`),p.style.setProperty("--persona-stream-duration",`${O.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Fe=ae?_a(S,O.buffer,B,y,H):S;if(ae&&O.placeholder==="skeleton"&&H&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=Vs();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),Ha(p,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,bt=so(Ke);if(!ae||!B){let P=Fe.length>100?`\u2026${Ke}`:Ke;p.textContent!==P&&(p.textContent=P)}else{let P=bt;(B.wrap==="char"||B.wrap==="word")&&(P=js(bt,B.wrap,`peek-${y.id}`,{skipTags:B.skipTags,startIndex:ze}));let Ne=document.createElement("div");if(Ne.innerHTML=P,B.useCaret&&Ke.length>0){let De=$a(),ge=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ge[ge.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(De,Ft.nextSibling):Ne.appendChild(De)}Ha(p,Ne),(We=B.onAfterRender)==null||We.call(B,{container:p,bubble:l,messageId:y.id,message:y,speed:O.speed,duration:O.duration})}}let $e=Ar||xs;l.classList.toggle("persona-pill-peek--visible",$e)};if(N()){let l=J.peekBanner;if(l){let y=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",y),dt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{xs||(xs=!0,zo())},h=()=>{xs&&(xs=!1,zo())};pe.addEventListener("pointerenter",p),pe.addEventListener("pointerleave",h),dt.push(()=>{pe.removeEventListener("pointerenter",p),pe.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",p),Xe.addEventListener("pointerleave",h),dt.push(()=>{Xe.removeEventListener("pointerenter",p),Xe.removeEventListener("pointerleave",h)}))}let ag=l=>{var be,Fe,Ce,nt,$e,gt,st,Be;let p=(Fe=(be=r.launcher)==null?void 0:be.composerBar)!=null?Fe:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",y=(nt=p.bottomOffset)!=null?nt:"16px",S=p.collapsedMaxWidth,H=($e=p.expandedMaxWidth)!=null?$e:"880px",z=(gt=p.expandedTopOffset)!=null?gt:"5vh",O=(st=p.modalMaxWidth)!=null?st:"880px",B=(Be=p.modalMaxHeight)!=null?Be:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Z=Ee.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Xe){let We=Xe.style;We.bottom=y,We.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=O,Z.maxWidth=se,Z.maxHeight=B,Z.height=B;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${y} + ${ae})`,Z.top=z,Z.width=H,Z.maxWidth=se}},ws=()=>{var B,se,ae,Z,be,Fe,Ce,nt;if(!D())return;if(N()){let gt=(ae=((se=(B=r.launcher)==null?void 0:B.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",st=k?"expanded":"collapsed";Ee.dataset.state=st,Ee.dataset.expandedSize=gt,Xe&&(Xe.dataset.state=st,Xe.dataset.expandedSize=gt),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ag(k),ce.style.display=k?"flex":"none",ye(),k?(rg(),og()):(ml(),gl()),zo();return}let l=gn(r),p=(Z=n.ownerDocument.defaultView)!=null?Z:window,h=(Fe=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Fe:640,y=(nt=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?nt:!0,S=p.innerWidth<=h,H=y&&S&&M,z=gr(r).reveal;k?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-95","persona-opacity-0"),pe.classList.add("persona-scale-100","persona-opacity-100"),Xt?Xt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(z==="overlay"||z==="push")&&!H?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),pe.classList.remove("persona-scale-100","persona-opacity-100"),pe.classList.add("persona-scale-95","persona-opacity-0")),Xt?Xt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},$t=(l,p="user")=>{var H,z;if(!D()||k===l)return;let h=k;k=l,ws();let y=(()=>{var Ce,nt,$e,gt,st,Be,We,ze,Ke,bt;let O=(nt=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?nt:!1,B=($e=n.ownerDocument.defaultView)!=null?$e:window,se=(st=(gt=r.launcher)==null?void 0:gt.mobileFullscreen)!=null?st:!0,ae=(We=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?We:640,Z=B.innerWidth<=ae,be=gn(r)&&se&&Z,Fe=N()&&((bt=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return O||se&&Z&&M||be||Fe})();if(k&&y){if(!Qt){let O=n.getRootNode(),B=O instanceof ShadowRoot?O.host:n.closest(".persona-host");B&&(Qt=Oi(B,(z=(H=r.launcher)==null?void 0:H.zIndex)!=null?z:wn))}on||(on=_i(n.ownerDocument))}else k||(Qt==null||Qt(),Qt=null,on==null||on(),on=null);k&&(Cs(),et()==="follow"?Hn(!0):eo());let S={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",S):!k&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()})},si=l=>{Wt(l?"stop":"send"),q&&(q.disabled=l),ho.buttons.forEach(p=>{p.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ai=()=>{ht.active||Te&&Te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ai(),200)});let hl=()=>{var h,y,S,H,z,O,B,se,ae,Z,be;hr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",hn.textContent=(H=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",Te.placeholder=(O=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?O:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Fe=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(_!=null&&_.isStreaming())&&(me.textContent=(be=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?be:"Send"),Te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=d.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{u(p=>({...p,sessionId:l}))}});let vo=null,ig=()=>{vo==null&&(vo=setInterval(()=>{let l=je.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(vo),vo=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=wa(p-y))})},100))};_=new Ia(r,{onMessagesChanged(l){var y;ys(je,l,Re),ig(),Fo(l),Hn(!Ar),tg(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&mn(),!_o||bo?(_o=!0,$o=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==$o&&($o=p.id,eg(p.id));let h=ht.lastUserMessageId;p&&p.id!==h&&(ht.lastUserMessageId=p.id,s.emit("user:message",p)),ht.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Zr(l),zo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};lt(rn,(S=>{var H,z,O,B;return S==="idle"?(H=p.idleText)!=null?H:xn.idle:S==="connecting"?(z=p.connectingText)!=null?z:xn.connecting:S==="connected"?(O=p.connectedText)!=null?O:xn.connected:S==="error"?(B=p.errorText)!=null?B:xn.error:xn[S]})(l),p,l)},onStreamingChanged(l){Ar=l,si(l),_&&ys(je,_.getMessages(),Re),l||Hn(!0),zo()},onVoiceStatusChanged(l){var p,h;if(s.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Or(),Vo();break;case"processing":Or(),ug();break;case"speaking":Or(),mg();break;default:l==="idle"&&_.isBargeInActive()?(Or(),Vo(),q==null||q.setAttribute("aria-label","End voice session")):(ht.active=!1,Or(),tr("system"),Rn());break}},onArtifactsState(l){On=l,Un(),Zr()}}),St.current=_;let ii=null;if(_.onReadAloudChange((l,p)=>{var S;Vr=l,Kr=p,Gr();let h=l!=null?l:ii;l&&(ii=l);let y=h&&(S=_.getMessages().find(H=>H.id===h))!=null?S:null;s.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(ii=null)}),_o=!0,((Ec=(Mc=r.voiceRecognition)==null?void 0:Mc.provider)==null?void 0:Ec.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(he||r.onSSEEvent)&&_.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),oe==null||oe.processEvent(l,p),he==null||he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),c&&c.then(l=>{var p,h,y;if(l){if(l.metadata&&(d=al(l.metadata),I.syncFromMetadata()),(p=l.messages)!=null&&p.length){bo=!0;try{_.hydrateMessages(l.messages)}finally{bo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let yl=()=>{var p,h,y;!N()||k||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||$t(!0,"auto")},bl=l=>{var S;if(l.preventDefault(),_.isStreaming()){_.cancel(),oe==null||oe.reset(),K==null||K.update();return}let p=Te.value.trim(),h=(S=xt==null?void 0:xt.hasAttachments())!=null?S:!1;if(!p&&!h)return;yl();let y;h&&(y=[],y.push(...xt.getContentParts()),p&&y.push(Pi(p))),Te.value="",Te.style.height="auto",la(),_.sendMessage(p,{contentParts:y}),h&&xt.clearAttachments()},lg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},li={...Ba},ci=!1,la=()=>{li={...Ba}},cg=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),dg=l=>{if(!Te)return;ci=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ci=!1;let p=Te.value.length;Te.setSelectionRange(p,p)},vl=()=>{ci||la()},xl=l=>{if(Te){if(lg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Te.selectionStart===0&&Te.selectionEnd===0,h=qu({direction:l.key==="ArrowUp"?"up":"down",history:cg(),currentValue:Te.value,atStart:p,state:li});if(li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&dg(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}la(),l.preventDefault(),me.click()}}},wl=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ce)&&(_.cancel(),oe==null||oe.reset(),K==null||K.update(),la(),l.preventDefault(),l.stopImmediatePropagation())},Cl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!xt)return;let p=uy(l.clipboardData);p.length!==0&&(l.preventDefault(),await xt.handleFiles(p))},nr=null,Er=!1,jo=null,mt=null,Al=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ca=(l="user")=>{var H,z,O,B,se,ae,Z;if(Er||_.isStreaming())return;let p=Al();if(!p)return;nr=new p;let y=(z=((H=r.voiceRecognition)!=null?H:{}).pauseDuration)!=null?z:2e3;nr.continuous=!0,nr.interimResults=!0,nr.lang="en-US";let S=Te.value;nr.onresult=be=>{let Fe="",Ce="";for(let $e=0;$e<be.results.length;$e++){let gt=be.results[$e],st=gt[0].transcript;gt.isFinal?Fe+=st+" ":Ce=st}let nt=S+Fe+Ce;Te.value=nt,jo&&clearTimeout(jo),(Fe||Ce)&&(jo=window.setTimeout(()=>{let $e=Te.value.trim();$e&&nr&&Er&&(to(),Te.value="",Te.style.height="auto",_.sendMessage($e,{viaVoice:!0}))},y))},nr.onerror=be=>{be.error!=="no-speech"&&to()},nr.onend=()=>{if(Er){let be=Te.value.trim();be&&be!==S.trim()&&(Te.value="",Te.style.height="auto",_.sendMessage(be,{viaVoice:!0})),to()}};try{if(nr.start(),Er=!0,ht.active=!0,l!=="system"&&(ht.manuallyDeactivated=!1),tr(l),Rn(),q){let be=(O=r.voiceRecognition)!=null?O:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(B=be.iconName)!=null?B:"mic",iconSize:parseFloat((Z=(ae=be.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Fe=be.recordingBackgroundColor,Ce=be.recordingIconColor,nt=be.recordingBorderColor;if(q.classList.add("persona-voice-recording"),q.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let $e=q.querySelector("svg");$e&&$e.setAttribute("stroke",Ce)}nt&&(q.style.borderColor=nt),q.setAttribute("aria-label","Stop voice recognition")}}catch{to("system")}},to=(l="user")=>{if(Er){if(Er=!1,jo&&(clearTimeout(jo),jo=null),nr){try{nr.stop()}catch{}nr=null}if(ht.active=!1,tr(l),Rn(),q){if(q.classList.remove("persona-voice-recording"),mt){q.style.backgroundColor=mt.backgroundColor,q.style.color=mt.color,q.style.borderColor=mt.borderColor;let p=q.querySelector("svg");p&&p.setAttribute("stroke",mt.color||"currentColor"),mt=null}q.setAttribute("aria-label","Start voice recognition")}}},pg=(l,p)=>{var st,Be,We,ze,Ke,bt,P,Ne,De;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",S=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||y||S))return null;let z=b("div","persona-send-button-wrapper"),O=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let B=(We=l==null?void 0:l.iconName)!=null?We:"mic",se=(ze=p==null?void 0:p.size)!=null?ze:"40px",ae=(Ke=l==null?void 0:l.iconSize)!=null?Ke:se,Z=parseFloat(ae)||24,be=(bt=l==null?void 0:l.backgroundColor)!=null?bt:p==null?void 0:p.backgroundColor,Fe=(P=l==null?void 0:l.iconColor)!=null?P:p==null?void 0:p.textColor;O.style.width=ae,O.style.height=ae,O.style.minWidth=ae,O.style.minHeight=ae,O.style.fontSize="18px",O.style.lineHeight="1",Fe?O.style.color=Fe:O.style.color="var(--persona-text, #111827)";let nt=Ae(B,Z,Fe||"currentColor",1.5);nt?O.appendChild(nt):O.textContent="\u{1F3A4}",be?O.style.backgroundColor=be:O.style.backgroundColor="",l!=null&&l.borderWidth&&(O.style.borderWidth=l.borderWidth,O.style.borderStyle="solid"),l!=null&&l.borderColor&&(O.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(O.style.paddingLeft=l.paddingX,O.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(O.style.paddingTop=l.paddingY,O.style.paddingBottom=l.paddingY),z.appendChild(O);let $e=(Ne=l==null?void 0:l.tooltipText)!=null?Ne:"Start voice recognition";if(((De=l==null?void 0:l.showTooltip)!=null?De:!1)&&$e){let ge=b("div","persona-send-button-tooltip");ge.textContent=$e,z.appendChild(ge)}return{micButton:O,micButtonWrapper:z}},di=()=>{var p,h,y,S,H;if(!q||mt)return;let l=(p=r.voiceRecognition)!=null?p:{};mt={backgroundColor:q.style.backgroundColor,color:q.style.color,borderColor:q.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((H=(S=l.iconSize)!=null?S:(y=r.sendButton)==null?void 0:y.size)!=null?H:"40")||24}},pi=(l,p)=>{var H,z,O,B,se;if(!q)return;let h=q.querySelector("svg");h&&h.remove();let y=(se=mt==null?void 0:mt.iconSize)!=null?se:parseFloat((B=(O=(H=r.voiceRecognition)==null?void 0:H.iconSize)!=null?O:(z=r.sendButton)==null?void 0:z.size)!=null?B:"40")||24,S=Ae(l,y,p,1.5);S&&q.appendChild(S)},da=()=>{q&&q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Vo=()=>{var S;if(!q)return;di();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(da(),q.classList.add("persona-voice-recording"),q.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",q.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let H=q.querySelector("svg");H&&H.setAttribute("stroke",h)}y&&(q.style.borderColor=y),q.setAttribute("aria-label","Stop voice recognition")},ug=()=>{var O,B,se,ae,Z,be,Fe,Ce;if(!q)return;di();let l=(O=r.voiceRecognition)!=null?O:{},p=_.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",y=(ae=(se=l.processingIconColor)!=null?se:mt==null?void 0:mt.color)!=null?ae:"",S=(be=(Z=l.processingBackgroundColor)!=null?Z:mt==null?void 0:mt.backgroundColor)!=null?be:"",H=(Ce=(Fe=l.processingBorderColor)!=null?Fe:mt==null?void 0:mt.borderColor)!=null?Ce:"";da(),q.classList.add("persona-voice-processing"),q.style.backgroundColor=S,q.style.borderColor=H;let z=y||"currentColor";q.style.color=z,pi(h,z),q.setAttribute("aria-label","Processing voice input"),p==="none"&&(q.style.cursor="default")},mg=()=>{var se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We;if(!q)return;di();let l=(se=r.voiceRecognition)!=null?se:{},p=_.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ae=l.speakingIconName)!=null?ae:h,S=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(be=(Z=l.recordingIconColor)!=null?Z:mt==null?void 0:mt.color)!=null?be:"":(Fe=mt==null?void 0:mt.color)!=null?Fe:"",H=(gt=l.speakingBackgroundColor)!=null?gt:p==="barge-in"?(nt=l.recordingBackgroundColor)!=null?nt:"var(--persona-voice-recording-bg, #ef4444)":($e=mt==null?void 0:mt.backgroundColor)!=null?$e:"",z=(We=l.speakingBorderColor)!=null?We:p==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=mt==null?void 0:mt.borderColor)!=null?Be:"";da(),q.classList.add("persona-voice-speaking"),q.style.backgroundColor=H,q.style.borderColor=z;let O=S||"currentColor";q.style.color=O,pi(y,O);let B=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";q.setAttribute("aria-label",B),p==="none"&&(q.style.cursor="default"),p==="barge-in"&&q.classList.add("persona-voice-recording")},Or=()=>{var l,p,h;q&&(da(),mt&&(q.style.backgroundColor=(l=mt.backgroundColor)!=null?l:"",q.style.color=(p=mt.color)!=null?p:"",q.style.borderColor=(h=mt.borderColor)!=null?h:"",pi(mt.iconName,mt.color||"currentColor"),mt=null),q.style.cursor="",q.setAttribute("aria-label","Start voice recognition"))},pa=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=_.getVoiceStatus(),y=_.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()});return}_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),ht.manuallyDeactivated=!_.isVoiceActive(),Rn(),tr("user"),_.isVoiceActive()?Vo():Or()});return}if(Er){let h=Te.value.trim();ht.manuallyDeactivated=!0,Rn(),to("user"),h&&(Te.value="",Te.style.height="auto",_.sendMessage(h))}else ht.manuallyDeactivated=!1,Rn(),ca("user")};Nn=pa,q&&(q.addEventListener("click",pa),dt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Or()):to("system"),q&&q.removeEventListener("click",pa)}));let gg=s.on("assistant:complete",()=>{hs&&(ht.active||ht.manuallyDeactivated||hs==="assistant"&&!ht.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!ht.active&&!ht.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("auto"),_.isVoiceActive()&&Vo()}):ca("auto"))},600))});dt.push(gg);let fg=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(fg);let Sl=()=>{$t(!k,"user")},Xt=null,sn=null;if(M&&!N()){let{instance:l,element:p}=qi({config:r,plugins:o,onToggle:Sl});Xt=l,l||(sn=p)}Xt?n.appendChild(Xt.element):sn&&n.appendChild(sn),ws(),Fo(),hl(),si(_.isStreaming()),et()==="follow"?Hn(!0):eo(),aa(),F&&(!M||N()?setTimeout(()=>ai(),0):k&&setTimeout(()=>ai(),200));let Cs=()=>{var B,se,ae,Z,be,Fe,Ce,nt,$e,gt,st,Be,We,ze,Ke,bt,P,Ne,De,ge,Ft,Dt;if(N()){In(),ws();return}let l=gn(r),p=(se=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?se:!1,h=l||p||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),y=(be=n.ownerDocument.defaultView)!=null?be:window,S=(Ce=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ce:!0,H=($e=(nt=r.launcher)==null?void 0:nt.mobileBreakpoint)!=null?$e:640,z=y.innerWidth<=H,O=S&&z&&M;try{if(O){ye(),ls(n,r);return}if(W&&(W=!1,ye(),ls(n,r)),!M&&!l){pe.style.height="",pe.style.width="";return}if(!p&&!l){let zt=(st=(gt=r==null?void 0:r.launcher)==null?void 0:gt.width)!=null?st:r==null?void 0:r.launcherWidth,wt=zt!=null?zt:qr;pe.style.width=wt,pe.style.maxWidth=wt}if(xr(),!h){let zt=y.innerHeight,wt=64,Ut=(We=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?We:0,Kn=Math.max(200,zt-wt),Jt=Math.min(640,Kn),Qe=Math.max(200,Jt-Ut);pe.style.height=`${Qe}px`}}finally{if(In(),ws(),k&&M){let wt=((ze=n.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?bt:640),Ut=(Ne=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Ne:!1,Kn=(ge=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?ge:!0,Jt=gn(r)&&Kn&&wt,Qe=Ut||Kn&&wt&&M||Jt;if(Qe&&!on){let kt=n.getRootNode(),nn=kt instanceof ShadowRoot?kt.host:n.closest(".persona-host");nn&&!Qt&&(Qt=Oi(nn,(Dt=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Dt:wn)),on=_i(n.ownerDocument)}else Qe||(Qt==null||Qt(),Qt=null,on==null||on(),on=null)}}};Cs();let Tl=(kc=n.ownerDocument.defaultView)!=null?kc:window;if(Tl.addEventListener("resize",Cs),dt.push(()=>Tl.removeEventListener("resize",Cs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{In()});l.observe(He),dt.push(()=>l.disconnect())}zn=we.scrollTop;let Ml=zr(we),hg=()=>{let l=we.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},ui=()=>Qu(hg(),we),El=()=>{let l=we.scrollTop,p=zr(we),h=p<Ml;if(Ml=p,et()!=="follow"){zn=l,Je();return}let{action:y,nextLastScrollTop:S}=Na({following:qn.isFollowing(),currentScrollTop:l,lastScrollTop:zn,nearBottom:Ro(we,Uo),userScrollThreshold:oa,isAutoScrolling:dr||yo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=S,y==="resume"){ui()||Nr();return}y==="pause"&&Et()};if(we.addEventListener("scroll",El,{passive:!0}),dt.push(()=>we.removeEventListener("scroll",El)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(je),l.observe(we),dt.push(()=>l.disconnect())}let kl=()=>{et()==="follow"&&qn.isFollowing()&&ui()&&Et()},Ll=we.ownerDocument;Ll.addEventListener("selectionchange",kl),dt.push(()=>{Ll.removeEventListener("selectionchange",kl)});let Pl=l=>{if(et()!=="follow")return;let p=Fa({following:qn.isFollowing(),deltaY:l.deltaY,nearBottom:Ro(we,Uo),resumeWhenNearBottom:!0});p==="pause"?Et():p==="resume"&&!ui()&&Nr()};we.addEventListener("wheel",Pl,{passive:!0}),dt.push(()=>we.removeEventListener("wheel",Pl)),ct.addEventListener("click",()=>{mn(),we.scrollTop=we.scrollHeight,zn=we.scrollTop,Nr(),Hn(!0),Je()}),dt.push(()=>ct.remove()),dt.push(()=>{$(),mn()});let Il=()=>{Ve&&(Cr&&(Ve.removeEventListener("click",Cr),Cr=null),D()?(Ve.style.display="",Cr=()=>{$t(!1,"user")},Ve.addEventListener("click",Cr)):Ve.style.display="none")};Il(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{_.clearMessages(),Sr.clear(),Nr(),ts(J.composerOverlay);try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()})})(),It&&It.addEventListener("submit",bl),Te==null||Te.addEventListener("keydown",xl),Te==null||Te.addEventListener("input",vl),Te==null||Te.addEventListener("paste",Cl);let Wl=(Lc=n.ownerDocument)!=null?Lc:document;Wl.addEventListener("keydown",wl,!0);let Rl="persona-attachment-drop-active",As=0,mi=()=>{As=0,ce.classList.remove(Rl)},Ko=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&xt!==null},Hl=l=>{!ri(l.dataTransfer)||!Ko()||(As++,As===1&&ce.classList.add(Rl))},Bl=l=>{!ri(l.dataTransfer)||!Ko()||(As--,As<=0&&mi())},Dl=l=>{!ri(l.dataTransfer)||!Ko()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Nl=l=>{var h;if(!ri(l.dataTransfer)||!Ko())return;l.preventDefault(),l.stopPropagation(),mi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&xt.handleFiles(p)},no=!0;ce.addEventListener("dragenter",Hl,no),ce.addEventListener("dragleave",Bl,no),n.addEventListener("dragover",Dl,no),n.addEventListener("drop",Nl,no);let ua=n.ownerDocument,Fl=l=>{Ko()&&l.preventDefault()},Ol=l=>{Ko()&&l.preventDefault()};ua.addEventListener("dragover",Fl),ua.addEventListener("drop",Ol),dt.push(()=>{It&&It.removeEventListener("submit",bl),Te==null||Te.removeEventListener("keydown",xl),Te==null||Te.removeEventListener("input",vl),Te==null||Te.removeEventListener("paste",Cl),Wl.removeEventListener("keydown",wl,!0)}),dt.push(()=>{ce.removeEventListener("dragenter",Hl,no),ce.removeEventListener("dragleave",Bl,no),n.removeEventListener("dragover",Dl,no),n.removeEventListener("drop",Nl,no),ua.removeEventListener("dragover",Fl),ua.removeEventListener("drop",Ol),mi()}),dt.push(()=>{_.cancel()}),Xt?dt.push(()=>{Xt==null||Xt.destroy()}):sn&&dt.push(()=>{sn==null||sn.remove()});let tn={update(l){var bn,Mn,kr,dn,En,kn,So,Ss,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Md,Ed,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Mp,Ep,kp,Lp,Pp,Ip,Wp,Rp,Hp;let p=r.toolCall,h=r.messageActions,y=(bn=r.layout)==null?void 0:bn.messages,S=r.colorScheme,H=r.loadingIndicator,z=r.iterationDisplay,O=(Mn=r.features)==null?void 0:Mn.showReasoning,B=(kr=r.features)==null?void 0:kr.showToolCalls,se=(dn=r.features)==null?void 0:dn.toolCallDisplay,ae=(En=r.features)==null?void 0:En.reasoningDisplay;r={...r,...l},ye(),ls(n,r),ti(n,r),ni(n,r),Un(),r.colorScheme!==S&&fs();let Z=tl.getForInstance(r.plugins);o.length=0,o.push(...Z),M=(So=(kn=r.launcher)==null?void 0:kn.enabled)!=null?So:!0,E=(Dc=(Ss=r.launcher)==null?void 0:Ss.autoExpand)!=null?Dc:!1,Ue=(Fc=(Nc=r.features)==null?void 0:Nc.showReasoning)!=null?Fc:!0,xe=(_c=(Oc=r.features)==null?void 0:Oc.showToolCalls)!=null?_c:!0,_e=(Uc=($c=r.features)==null?void 0:$c.scrollToBottom)!=null?Uc:{};let be=et();Se=(zc=(qc=r.features)==null?void 0:qc.scrollBehavior)!=null?zc:{},be!==et()&&(mn(),Nr()),yr(),Je();let Fe=Ie;if(Ie=(Vc=(jc=r.features)==null?void 0:jc.showEventStreamToggle)!=null?Vc:!1,Ie&&!Fe){if(he||(X=new Zs(re),he=new Ys(ie,X),oe=oe!=null?oe:new ea,X.open().then(()=>he==null?void 0:he.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Tt)=>{var qt;(qt=r.onSSEEvent)==null||qt.call(r,ee,Tt),oe==null||oe.processEvent(ee,Tt),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&Me){let ee=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee!=null&&ee.toggleButton?" "+ee.toggleButton:"");yt=b("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Pn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let qt=Ae("activity","18px","currentColor",1.5);qt&&yt.appendChild(qt);let at=J.clearChatButtonWrapper,Lt=J.closeButtonWrapper,ln=at||Lt;ln&&ln.parentNode===Me?Me.insertBefore(yt,ln):Me.appendChild(yt),yt.addEventListener("click",()=>{te?ir():Pr()})}}else!Ie&&Fe&&(ir(),yt&&(yt.remove(),yt=null),he==null||he.clear(),X==null||X.destroy(),he=null,X=null,oe==null||oe.reset(),oe=null);if(((Qc=r.launcher)==null?void 0:Qc.enabled)===!1&&Xt&&(Xt.destroy(),Xt=null),((Xc=r.launcher)==null?void 0:Xc.enabled)===!1&&sn&&(sn.remove(),sn=null),((Jc=r.launcher)==null?void 0:Jc.enabled)!==!1&&!Xt&&!sn){let{instance:ee,element:Tt}=qi({config:r,plugins:o,onToggle:Sl});Xt=ee,ee||(sn=Tt),n.appendChild(Tt)}Xt&&Xt.update(r),ue&&((Yc=r.launcher)==null?void 0:Yc.title)!==void 0&&(ue.textContent=r.launcher.title),Le&&((Zc=r.launcher)==null?void 0:Zc.subtitle)!==void 0&&(Le.textContent=r.launcher.subtitle);let Ce=(ed=r.layout)==null?void 0:ed.header;if((Ce==null?void 0:Ce.layout)!==A&&Me){let ee=Ce?za(r,Ce,{showClose:D(),onClose:()=>$t(!1,"user")}):Ho({config:r,showClose:D(),onClose:()=>$t(!1,"user")});rt.replaceHeader(ee),Me=rt.header.element,T=rt.header.iconHolder,ue=rt.header.headerTitle,Le=rt.header.headerSubtitle,Ve=rt.header.closeButton,A=Ce==null?void 0:Ce.layout}else if(Ce&&(T&&(T.style.display=Ce.showIcon===!1?"none":""),ue&&(ue.style.display=Ce.showTitle===!1?"none":""),Le&&(Le.style.display=Ce.showSubtitle===!1?"none":""),Ve&&(Ve.style.display=Ce.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let ee=Ce.showClearChat;if(ee!==void 0){J.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Tt}=J;Tt&&!Tt.classList.contains("persona-absolute")&&(ee?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let $e=((td=r.layout)==null?void 0:td.showHeader)!==!1;Me&&(Me.style.display=$e?"":"none");let gt=((nd=r.layout)==null?void 0:nd.showFooter)!==!1;He&&(He.style.display=gt?"":"none"),In(),Je(),M!==R?M?$t(E,"auto"):(k=!0,ws()):E!==L&&$t(E,"auto"),L=E,R=M,Cs(),Il();let We=JSON.stringify(l.toolCall)!==JSON.stringify(p),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((rd=r.layout)==null?void 0:rd.messages)!==JSON.stringify(y),bt=((od=r.loadingIndicator)==null?void 0:od.render)!==(H==null?void 0:H.render)||((sd=r.loadingIndicator)==null?void 0:sd.renderIdle)!==(H==null?void 0:H.renderIdle)||((ad=r.loadingIndicator)==null?void 0:ad.showBubble)!==(H==null?void 0:H.showBubble),P=r.iterationDisplay!==z,Ne=((ld=(id=r.features)==null?void 0:id.showReasoning)!=null?ld:!0)!==(O!=null?O:!0)||((dd=(cd=r.features)==null?void 0:cd.showToolCalls)!=null?dd:!0)!==(B!=null?B:!0)||JSON.stringify((pd=r.features)==null?void 0:pd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((ud=r.features)==null?void 0:ud.reasoningDisplay)!==JSON.stringify(ae);(We||ze||Ke||bt||P||Ne)&&_&&(Oo++,ys(je,_.getMessages(),Re));let ge=(md=r.launcher)!=null?md:{},Ft=(gd=ge.headerIconHidden)!=null?gd:!1,Dt=(hd=(fd=r.layout)==null?void 0:fd.header)==null?void 0:hd.showIcon,zt=Ft||Dt===!1,wt=ge.headerIconName,Ut=(yd=ge.headerIconSize)!=null?yd:"48px";if(T){let ee=ce.querySelector(".persona-border-b-persona-divider"),Tt=ee==null?void 0:ee.querySelector(".persona-flex-col");if(zt)T.style.display="none",ee&&Tt&&!ee.contains(Tt)&&ee.insertBefore(Tt,ee.firstChild);else{if(T.style.display="",T.style.height=Ut,T.style.width=Ut,ee&&Tt&&(ee.contains(T)?T.nextSibling!==Tt&&(T.remove(),ee.insertBefore(T,Tt)):ee.insertBefore(T,Tt)),wt){let at=parseFloat(Ut)||24,Lt=Ae(wt,at*.6,"currentColor",1);Lt?T.replaceChildren(Lt):T.textContent=(bd=ge.agentIconText)!=null?bd:"\u{1F4AC}"}else if(ge.iconUrl){let at=T.querySelector("img");if(at)at.src=ge.iconUrl,at.style.height=Ut,at.style.width=Ut;else{let Lt=document.createElement("img");Lt.src=ge.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Ut,Lt.style.width=Ut,T.replaceChildren(Lt)}}else{let at=T.querySelector("svg"),Lt=T.querySelector("img");(at||Lt)&&T.replaceChildren(),T.textContent=(vd=ge.agentIconText)!=null?vd:"\u{1F4AC}"}let qt=T.querySelector("img");qt&&(qt.style.height=Ut,qt.style.width=Ut)}}let Kn=(wd=(xd=r.layout)==null?void 0:xd.header)==null?void 0:wd.showTitle,Jt=(Ad=(Cd=r.layout)==null?void 0:Cd.header)==null?void 0:Ad.showSubtitle;if(ue&&(ue.style.display=Kn===!1?"none":""),Le&&(Le.style.display=Jt===!1?"none":""),Ve){((Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showCloseButton)===!1?Ve.style.display="none":Ve.style.display="";let Tt=(Md=ge.closeButtonSize)!=null?Md:"32px",qt=(Ed=ge.closeButtonPlacement)!=null?Ed:"inline";Ve.style.height=Tt,Ve.style.width=Tt;let{closeButtonWrapper:at}=J,Lt=qt==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&Lt!==ln)if(at.remove(),Lt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ce.style.position="relative",ce.appendChild(at);else{let pt=(Ld=(kd=ge.clearChat)==null?void 0:kd.placement)!=null?Ld:"inline",cn=(Id=(Pd=ge.clearChat)==null?void 0:Pd.enabled)!=null?Id:!0;at.className=cn&&pt==="inline"?"":"persona-ml-auto";let Dn=ce.querySelector(".persona-border-b-persona-divider");Dn&&Dn.appendChild(at)}if(Ve.style.color=ge.closeButtonColor||Pn.actionIconColor,ge.closeButtonBackgroundColor?(Ve.style.backgroundColor=ge.closeButtonBackgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let pt=ge.closeButtonBorderWidth||"0px",cn=ge.closeButtonBorderColor||"transparent";Ve.style.border=`${pt} solid ${cn}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ve.style.borderRadius=ge.closeButtonBorderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ve.style.paddingLeft=ge.closeButtonPaddingX,Ve.style.paddingRight=ge.closeButtonPaddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),ge.closeButtonPaddingY?(Ve.style.paddingTop=ge.closeButtonPaddingY,Ve.style.paddingBottom=ge.closeButtonPaddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let vn=(Wd=ge.closeButtonIconName)!=null?Wd:"x",ur=(Rd=ge.closeButtonIconText)!=null?Rd:"\xD7";Ve.innerHTML="";let Ln=Ae(vn,"28px","currentColor",1);Ln?Ve.appendChild(Ln):Ve.textContent=ur;let Gt=(Hd=ge.closeButtonTooltipText)!=null?Hd:"Close chat",Qn=(Bd=ge.closeButtonShowTooltip)!=null?Bd:!0;if(Ve.setAttribute("aria-label",Gt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Ve)return;let To=Ve.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Ve.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Dn),Ve.addEventListener("focus",cn),Ve.addEventListener("blur",Dn),at._cleanupTooltip=()=>{Dn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Dn)),Ve&&(Ve.removeEventListener("focus",cn),Ve.removeEventListener("blur",Dn))}}}let{clearChatButton:Qe,clearChatButtonWrapper:kt}=J;if(Qe){let ee=(Dd=ge.clearChat)!=null?Dd:{},Tt=(Nd=ee.enabled)!=null?Nd:!0,qt=(Od=(Fd=r.layout)==null?void 0:Fd.header)==null?void 0:Od.showClearChat,at=qt!==void 0?qt:Tt,Lt=(_d=ee.placement)!=null?_d:"inline";if(kt){kt.style.display=at?"":"none";let{closeButtonWrapper:ln}=J;!N()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let vn=Lt==="top-right",ur=kt.classList.contains("persona-absolute");if(!N()&&vn!==ur&&at){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",ce.style.position="relative",ce.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Gt=ce.querySelector(".persona-border-b-persona-divider"),Qn=J.closeButtonWrapper;Gt&&Qn&&Qn.parentElement===Gt?Gt.insertBefore(kt,Qn):Gt&&Gt.appendChild(kt)}let Ln=J.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(vn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(at){if(!N()){let pt=($d=ee.size)!=null?$d:"32px";Qe.style.height=pt,Qe.style.width=pt}let ln=(Ud=ee.iconName)!=null?Ud:"refresh-cw",vn=(qd=ee.iconColor)!=null?qd:"";Qe.style.color=vn||Pn.actionIconColor,Qe.innerHTML="";let ur=N()?"14px":"20px",Ln=Ae(ln,ur,"currentColor",2);if(Ln&&Qe.appendChild(Ln),ee.backgroundColor?(Qe.style.backgroundColor=ee.backgroundColor,Qe.classList.remove("hover:persona-bg-gray-100")):(Qe.style.backgroundColor="",Qe.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let pt=ee.borderWidth||"0px",cn=ee.borderColor||"transparent";Qe.style.border=`${pt} solid ${cn}`,Qe.classList.remove("persona-border-none")}else Qe.style.border="",Qe.classList.add("persona-border-none");ee.borderRadius?(Qe.style.borderRadius=ee.borderRadius,Qe.classList.remove("persona-rounded-full")):(Qe.style.borderRadius="",Qe.classList.add("persona-rounded-full")),ee.paddingX?(Qe.style.paddingLeft=ee.paddingX,Qe.style.paddingRight=ee.paddingX):(Qe.style.paddingLeft="",Qe.style.paddingRight=""),ee.paddingY?(Qe.style.paddingTop=ee.paddingY,Qe.style.paddingBottom=ee.paddingY):(Qe.style.paddingTop="",Qe.style.paddingBottom="");let Gt=(zd=ee.tooltipText)!=null?zd:"Clear chat",Qn=(jd=ee.showTooltip)!=null?jd:!0;if(Qe.setAttribute("aria-label",Gt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Qn&&Gt)){let pt=null,cn=()=>{if(pt||!Qe)return;let To=Qe.ownerDocument,Ts=To.body;if(!Ts)return;pt=Lr(To,"div","persona-clear-chat-tooltip"),pt.textContent=Gt;let Ms=Lr(To,"div");Ms.className="persona-clear-chat-tooltip-arrow",pt.appendChild(Ms);let Mo=Qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(co),pt.style.left=`${Mo.left+Mo.width/2}px`,pt.style.top=`${Mo.top-8}px`,pt.style.transform="translate(-50%, -100%)",Ts.appendChild(pt)},Dn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};kt.addEventListener("mouseenter",cn),kt.addEventListener("mouseleave",Dn),Qe.addEventListener("focus",cn),Qe.addEventListener("blur",Dn),kt._cleanupTooltip=()=>{Dn(),kt&&(kt.removeEventListener("mouseenter",cn),kt.removeEventListener("mouseleave",Dn)),Qe&&(Qe.removeEventListener("focus",cn),Qe.removeEventListener("blur",Dn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[rl],or=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ta.message,ta.messageAndClick];I=ol({parsers:nn,handlers:or,getSessionMetadata:g,updateSessionMetadata:u,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Re=_m(r,I,ne),_.updateConfig(r),ys(je,_.getMessages(),Re),Fo(),hl(),si(_.isStreaming());let Gn=((Vd=r.voiceRecognition)==null?void 0:Vd.enabled)===!0,xo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),wo=((Gd=(Kd=r.voiceRecognition)==null?void 0:Kd.provider)==null?void 0:Gd.type)==="runtype";if(Gn&&(xo||wo))if(!q||!ot){let ee=pg(r.voiceRecognition,r.sendButton);ee&&(q=ee.micButton,ot=ee.micButtonWrapper,ut.insertBefore(ot,fn),q.addEventListener("click",pa),q.disabled=_.isStreaming())}else{let ee=(Qd=r.voiceRecognition)!=null?Qd:{},Tt=(Xd=r.sendButton)!=null?Xd:{},qt=(Jd=ee.iconName)!=null?Jd:"mic",at=(Yd=Tt.size)!=null?Yd:"40px",Lt=(Zd=ee.iconSize)!=null?Zd:at,ln=parseFloat(Lt)||24;q.style.width=Lt,q.style.height=Lt,q.style.minWidth=Lt,q.style.minHeight=Lt;let vn=(tp=(ep=ee.iconColor)!=null?ep:Tt.textColor)!=null?tp:"currentColor";q.innerHTML="";let ur=Ae(qt,ln,vn,2);ur?q.appendChild(ur):q.textContent="\u{1F3A4}";let Ln=(np=ee.backgroundColor)!=null?np:Tt.backgroundColor;Ln?q.style.backgroundColor=Ln:q.style.backgroundColor="",vn?q.style.color=vn:q.style.color="var(--persona-text, #111827)",ee.borderWidth?(q.style.borderWidth=ee.borderWidth,q.style.borderStyle="solid"):(q.style.borderWidth="",q.style.borderStyle=""),ee.borderColor?q.style.borderColor=ee.borderColor:q.style.borderColor="",ee.paddingX?(q.style.paddingLeft=ee.paddingX,q.style.paddingRight=ee.paddingX):(q.style.paddingLeft="",q.style.paddingRight=""),ee.paddingY?(q.style.paddingTop=ee.paddingY,q.style.paddingBottom=ee.paddingY):(q.style.paddingTop="",q.style.paddingBottom="");let Gt=ot==null?void 0:ot.querySelector(".persona-send-button-tooltip"),Qn=(rp=ee.tooltipText)!=null?rp:"Start voice recognition";if(((op=ee.showTooltip)!=null?op:!1)&&Qn)if(Gt)Gt.textContent=Qn,Gt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Qn,ot==null||ot.insertBefore(cn,q)}else Gt&&(Gt.style.display="none");ot.style.display="",q.disabled=_.isStreaming()}else q&&ot&&(ot.style.display="none",((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Er&&to());if(((ip=r.attachments)==null?void 0:ip.enabled)===!0)if(!de||!G){let ee=(lp=r.attachments)!=null?lp:{},qt=(dp=((cp=r.sendButton)!=null?cp:{}).size)!=null?dp:"40px";vt||(vt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),vt.style.display="none",It.insertBefore(vt,Te)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=((pp=ee.allowedTypes)!=null?pp:Ur).join(","),ke.multiple=((up=ee.maxFiles)!=null?up:4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),It.insertBefore(ke,Te)),de=b("div","persona-send-button-wrapper"),G=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),G.type="button",G.setAttribute("aria-label",(mp=ee.buttonTooltipText)!=null?mp:"Attach file");let at=(gp=ee.buttonIconName)!=null?gp:"paperclip",Lt=qt,ln=parseFloat(Lt)||40,vn=Math.round(ln*.6);G.style.width=Lt,G.style.height=Lt,G.style.minWidth=Lt,G.style.minHeight=Lt,G.style.fontSize="18px",G.style.lineHeight="1",G.style.backgroundColor="transparent",G.style.color="var(--persona-primary, #111827)",G.style.border="none",G.style.borderRadius="6px",G.style.transition="background-color 0.15s ease",G.addEventListener("mouseenter",()=>{G.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),G.addEventListener("mouseleave",()=>{G.style.backgroundColor="transparent"});let ur=Ae(at,vn,"currentColor",1.5);ur?G.appendChild(ur):G.textContent="\u{1F4CE}",G.addEventListener("click",Qn=>{Qn.preventDefault(),ke==null||ke.click()}),de.appendChild(G);let Ln=(fp=ee.buttonTooltipText)!=null?fp:"Attach file",Gt=b("div","persona-send-button-tooltip");Gt.textContent=Ln,de.appendChild(Gt),Ge.append(de),!xt&&ke&&vt&&(xt=$s.fromConfig(ee),xt.setPreviewsContainer(vt),ke.addEventListener("change",async()=>{xt&&(ke!=null&&ke.files)&&(await xt.handleFileSelect(ke.files),ke.value="")})),ce.querySelector(".persona-attachment-drop-overlay")||ce.appendChild($m(ee.dropOverlay))}else{de.style.display="";let ee=(hp=r.attachments)!=null?hp:{};ke&&(ke.accept=((yp=ee.allowedTypes)!=null?yp:Ur).join(","),ke.multiple=((bp=ee.maxFiles)!=null?bp:4)>1),xt&&xt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else de&&(de.style.display="none"),xt&&xt.clearAttachments(),(vp=ce.querySelector(".persona-attachment-drop-overlay"))==null||vp.remove();let jt=(xp=r.sendButton)!=null?xp:{},Co=(wp=jt.useIcon)!=null?wp:!1,ro=(Cp=jt.iconText)!=null?Cp:"\u2191",oo=jt.iconName,_r=(Ap=jt.tooltipText)!=null?Ap:"Send message",Ao=(Sp=jt.showTooltip)!=null?Sp:!1,pr=(Tp=jt.size)!=null?Tp:"40px",Ye=jt.backgroundColor,an=jt.textColor;if(Co){if(me.style.width=pr,me.style.height=pr,me.style.minWidth=pr,me.style.minHeight=pr,me.style.fontSize="18px",me.style.lineHeight="1",me.innerHTML="",an?me.style.color=an:me.style.color="var(--persona-button-primary-fg, #ffffff)",oo){let ee=parseFloat(pr)||24,Tt=(an==null?void 0:an.trim())||"currentColor",qt=Ae(oo,ee,Tt,2);qt?me.appendChild(qt):me.textContent=ro}else me.textContent=ro;me.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-primary")):(me.style.backgroundColor="",me.classList.add("persona-bg-persona-primary"))}else me.textContent=(Ep=(Mp=r.copy)==null?void 0:Mp.sendButtonLabel)!=null?Ep:"Send",me.style.width="",me.style.height="",me.style.minWidth="",me.style.minHeight="",me.style.fontSize="",me.style.lineHeight="",me.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",Ye?(me.style.backgroundColor=Ye,me.classList.remove("persona-bg-persona-accent")):me.classList.add("persona-bg-persona-accent"),an?me.style.color=an:me.classList.add("persona-text-white");jt.borderWidth?(me.style.borderWidth=jt.borderWidth,me.style.borderStyle="solid"):(me.style.borderWidth="",me.style.borderStyle=""),jt.borderColor?me.style.borderColor=jt.borderColor:me.style.borderColor="",jt.paddingX?(me.style.paddingLeft=jt.paddingX,me.style.paddingRight=jt.paddingX):(me.style.paddingLeft="",me.style.paddingRight=""),jt.paddingY?(me.style.paddingTop=jt.paddingY,me.style.paddingBottom=jt.paddingY):(me.style.paddingTop="",me.style.paddingBottom="");let _t=fn==null?void 0:fn.querySelector(".persona-send-button-tooltip");if(Ao&&_r)if(_t)_t.textContent=_r,_t.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=_r,fn==null||fn.insertBefore(ee,me)}else _t&&(_t.style.display="none");let Ot=(Wp=(kp=r.layout)==null?void 0:kp.contentMaxWidth)!=null?Wp:N()?(Ip=(Pp=(Lp=r.launcher)==null?void 0:Lp.composerBar)==null?void 0:Pp.contentMaxWidth)!=null?Ip:"720px":void 0;Ot?(je.style.maxWidth=Ot,je.style.marginLeft="auto",je.style.marginRight="auto",je.style.width="100%",It&&(It.style.maxWidth=Ot,It.style.marginLeft="auto",It.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Ot,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(je.style.maxWidth="",je.style.marginLeft="",je.style.marginRight="",je.style.width="",It&&(It.style.maxWidth="",It.style.marginLeft="",It.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let ft=(Rp=r.statusIndicator)!=null?Rp:{},Vt=(Hp=ft.visible)!=null?Hp:!0;if(rn.style.display=Vt?"":"none",_){let ee=_.getStatus();lt(rn,(qt=>{var at,Lt,ln,vn;return qt==="idle"?(at=ft.idleText)!=null?at:xn.idle:qt==="connecting"?(Lt=ft.connectingText)!=null?Lt:xn.connecting:qt==="connected"?(ln=ft.connectedText)!=null?ln:xn.connected:qt==="error"?(vn=ft.errorText)!=null?vn:xn.error:xn[qt]})(ee),ft,ee)}rn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let At=ft.align==="left"?"persona-text-left":ft.align==="center"?"persona-text-center":"persona-text-right";rn.classList.add(At)},open(){D()&&$t(!0,"api")},close(){D()&&$t(!1,"api")},toggle(){D()&&$t(!k,"api")},clearChat(){Sn=!1,_.clearMessages(),Sr.clear(),Nr();try{localStorage.removeItem(ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ms}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ms)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}d={},I.syncFromMetadata(),he==null||he.clear(),oe==null||oe.reset(),K==null||K.update()},setMessage(l){return!Te||_.isStreaming()?!1:(!k&&D()&&$t(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Te.value.trim();return p?(!k&&D()&&$t(!0,"system"),Te.value="",Te.style.height="auto",_.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return _.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),_.toggleVoice().then(()=>{ht.active=_.isVoiceActive(),tr("user"),_.isVoiceActive()&&Vo()})),!0):Er?!0:Al()?(!k&&D()&&$t(!0,"system"),ht.manuallyDeactivated=!1,Rn(),ca("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{ht.active=!1,ht.manuallyDeactivated=!0,Rn(),tr("user"),Or()}),!0):!1:Er?(ht.manuallyDeactivated=!0,Rn(),to("user"),!0):!1},injectMessage(l){return!k&&D()&&$t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!k&&D()&&$t(!0,"system");let p=_.injectAssistantMessage(l);return j&&(j=!1,V&&(clearTimeout(V),V=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),p},injectUserMessage(l){return!k&&D()&&$t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!k&&D()&&$t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!k&&D()&&$t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!k&&D()&&$t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!k&&D()&&$t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,p){return _.connectStream(l,p)},__pushEventStreamEvent(l){he&&(oe==null||oe.processEvent(l.type,l.payload),he.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ie||!he||Pr()},hideEventStream(){te&&ir()},isEventStreamVisible(){return te},showArtifacts(){ar(r)&&(Sn=!1,Un(),Ct==null||Ct.setMobileOpen(!0))},hideArtifacts(){ar(r)&&(Sn=!0,Un())},upsertArtifact(l){return ar(r)?(Sn=!1,_.upsertArtifact(l)):null},selectArtifact(l){ar(r)&&_.selectArtifact(l)},clearArtifacts(){ar(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!k&&!N()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,p,h){let S=_.getMessages().find(H=>{var z;return H.variant==="approval"&&((z=H.approval)==null?void 0:z.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){_.resolveWebMcpApproval(S.id,p);return}return _.resolveApproval(S.approval,p,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){u(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return D()&&k},isVoiceActive(){return ht.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:D()&&k,launcherEnabled:M,voiceActive:ht.active,streaming:_.isStreaming()}},showCSATFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=Nm({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitCSATFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&D()&&$t(!0,"system");let p=je.querySelector(".persona-feedback-container");p&&p.remove();let h=Fm({onSubmit:async(y,S)=>{var H;_.isClientTokenMode()&&await _.submitNPSFeedback(y,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,y,S)},onDismiss:l==null?void 0:l.onDismiss,...l});je.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return _.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return _.submitNPSFeedback(l,p)},destroy(){vo!=null&&(clearInterval(vo),vo=null),dt.forEach(l=>l()),Ee.remove(),Xe==null||Xe.remove(),Xt==null||Xt.destroy(),sn==null||sn.remove(),Cr&&Ve.removeEventListener("click",Cr)}};if((((Pc=t==null?void 0:t.debugTools)!=null?Pc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,dt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",p),dt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ie){let O=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.showEventStream()},B=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",O),window.addEventListener("persona:hideEventStream",B),dt.push(()=>{window.removeEventListener("persona:showEventStream",O),window.removeEventListener("persona:hideEventStream",B)})}let h=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.showArtifacts()},y=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.hideArtifacts()},S=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&tn.upsertArtifact(B.artifact)},H=O=>{let B=O.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&tn.selectArtifact(B.id)},z=O=>{let B=O.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",z),dt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",z)})}let rr=my(r.persistState);if(rr&&D()){let l=gy(rr.storage),p=`${rr.keyPrefix}widget-open`,h=`${rr.keyPrefix}widget-voice`,y=`${rr.keyPrefix}widget-voice-mode`;if(l){let S=((Ic=rr.persist)==null?void 0:Ic.openState)&&l.getItem(p)==="true",H=((Wc=rr.persist)==null?void 0:Wc.voiceState)&&l.getItem(h)==="true",z=((Rc=rr.persist)==null?void 0:Rc.voiceState)&&l.getItem(y)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var O;if(H||z)tn.startVoiceRecognition();else if((O=rr.persist)!=null&&O.focusInput){let B=n.querySelector("textarea");B&&B.focus()}},100)},0),(Hc=rr.persist)!=null&&Hc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Bc=rr.persist)!=null&&Bc.voiceState&&(s.on("voice:state",O=>{l.setItem(h,O.active?"true":"false")}),s.on("user:message",O=>{l.setItem(y,O.viaVoice?"true":"false")})),rr.clearOnChatClear){let O=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},B=()=>O();window.addEventListener("persona:clear-chat",B),dt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return m&&D()&&setTimeout(()=>{tn.open()},0),zo(),ra||Up().then(()=>{_&&(Oo++,Sr.clear(),ys(je,_.getMessages(),Re))}).catch(()=>{}),tn};var fy=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},hy=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},yy=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},by=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},qm=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},dl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},zm=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",dl(n)},il=n=>{n.style.transition=""},ll=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},cl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},oi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},vy=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},xy=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},jm=(n,e,t,r,o,s,a)=>{var v,x,I,M,E,F;let i=gr(s),d=i.reveal==="push";vy(n,e,t,r,d),xy(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=n.ownerDocument.defaultView,m=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(I=s==null?void 0:s.launcher)==null?void 0:I.mobileBreakpoint)!=null?M:640,g=c!=null?c.innerWidth<=f:!1;if(m&&g&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),ll(e),il(r),zm(r),cl(t),oi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((F=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?F:wn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),zm(r),hy(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",ll(e),il(r),cl(t),oi(o,r);let L=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=L,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",il(r),dl(r),oi(o,r);let L=fy(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-L:0:a?0:-L;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${R+L}px`,e.style.transition=A,e.style.marginLeft=`${W}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${R}px`,t.style.maxWidth=`${R}px`,t.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",ll(e),dl(r),cl(t),oi(o,r);let L=i.reveal==="emerge";L?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",yy(r,i.maxHeight),r.style.overflow=L||W?"hidden":"visible",r.style.transition=A,L&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},wy=(n,e)=>{let t=n.ownerDocument.createElement("div");return qm(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){qm(t,r)},destroy(){t.remove()}}},Cy=(n,e)=>{var F,L,R,A;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),m=t.createElement("div"),f=(L=(F=e==null?void 0:e.launcher)==null?void 0:F.enabled)==null||L?(A=(R=e==null?void 0:e.launcher)==null?void 0:R.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",m.dataset.personaDockRole="host",c.appendChild(m),r.insertBefore(a,n),d.appendChild(n);let g=null,u=()=>{g==null||g.disconnect(),g=null},v=()=>{u(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{jm(a,i,d,c,m,e,f)}),g.observe(a))},x=!1,I=()=>{jm(a,i,d,c,m,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,by(a,gr(e)))},M=a.ownerDocument.defaultView,E=()=>{I()};return M==null||M.addEventListener("resize",E),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),I(),{mode:"docked",host:m,shell:a,syncWidgetState(W){let N=W.launcherEnabled?W.open:!0;f!==N&&(f=N,I())},updateConfig(W){var N,D;e=W,((D=(N=e==null?void 0:e.launcher)==null?void 0:N.enabled)!=null?D:!0)===!1&&(f=!0),I()},destroy(){M==null||M.removeEventListener("resize",E),u(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},Vm=(n,e)=>gn(e)?Cy(n,e):wy(n,e);var na={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Km=.15,Gm=1.5,pl="persona-preview-shell-theme",Ay={load:()=>null,save:()=>{},clear:()=>{}},Sy=["How do I get started?","Pricing & plans","Talk to support"];function ul(n){return n.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ty(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Qm(n){let e=Ty(n);return`* { box-sizing: border-box; }
|
|
111
|
+
`}if(!b&&!l){let _t="max-height: -moz-available !important; max-height: stretch !important;",Gt=p?"":"padding-top: 1.25em !important;",$t=p?"":`z-index: ${(Xe=(Pr=r.launcher)==null?void 0:Pr.zIndex)!=null?Xe:Sn} !important;`;He.style.cssText+=_t+Gt+$t}Ke()};wr(),ms(t,r),oi(t,r),si(t,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",Zr)});let sn=null,an=null;mt.push(()=>{sn==null||sn(),sn=null,an==null||an(),an=null}),_n&&mt.push(()=>{_n==null||_n.disconnect(),_n=null}),mt.push(()=>{Pn==null||Pn(),Pn=null,Nr(),Bt&&(Bt.remove(),Bt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),le&&mt.push(()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),ve==null||ve.destroy(),ve=null,G==null||G.destroy(),G=null,ze=null});let Cr=null,xs=()=>{Cr&&(Cr(),Cr=null),r.colorScheme==="auto"&&(Cr=Ku(()=>{ms(t,r)}))};xs(),mt.push(()=>{Cr&&(Cr(),Cr=null)}),mt.push(a);let Fr=(Ec=r.features)==null?void 0:Ec.streamAnimation;if(Fr!=null&&Fr.type&&Fr.type!=="none"){let l=Qs(Fr.type,Fr.plugins);l&&(_i(l,t),mt.push(()=>im(t)))}let wo=Mm(Qe),Ar=null,z,zo=l=>{var b,S;if(!z)return;let p=l!=null?l:z.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?mu(p):null;h?wo.render(h,z,Te,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(D=>D.role==="user")?wo.render([],z,Te,p):wo.render(r.suggestionChips,z,Te,p,r.suggestionChipsConfig)},Sr=!1,Tr=Yu(),Or=new Map,Er=new Map,dr=new Map,qo=0,la=Io()!==null,qn=Oa(),jn=0,pr=null,ur=!1,Co=!1,_r=0,xn=null,Mr=null,jo=!1,Ao=!1,Vo=null,ca=4,Ko=24,da=80,Go=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(kc=(Mc=r.voiceRecognition)==null?void 0:Mc.autoResume)!=null?kc:!1,tr=l=>{i.emit("voice:state",{active:pt.active,source:l,timestamp:Date.now()})},Nn=()=>{v(l=>({...l,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},Qo=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=cl(u.voiceState),p=!!l.active,h=Number((S=l.timestamp)!=null?S:0);pt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<Wy&&setTimeout(()=>{var D,V;pt.active||(pt.manuallyDeactivated=!1,((V=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:V.type)==="runtype"?z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),tr("restore"),z.isVoiceActive()&&Yo()}):ua("restore"))},1e3)},st=()=>z?Xm(z.getMessages()).filter(l=>!l.__skipPersist):[];function w(l){if(!(c!=null&&c.save))return;let h={messages:l?Xm(l):z?st():[],metadata:u,artifacts:$n.artifacts,selectedArtifactId:$n.selectedId};try{let b=c.save(h);b instanceof Promise&&b.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let j=null,q=()=>He.querySelector("#persona-scroll-container")||Se,J=()=>{j!==null&&(cancelAnimationFrame(j),j=null),ur=!1},fe=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Co=!1,J()},Oe=()=>{_r>0?(Mn.textContent=String(_r),Mn.style.display="",Ut.setAttribute("aria-label",`${vt()||"Jump to latest"} (${_r} new)`)):(Mn.textContent="",Mn.style.display="none",Ut.setAttribute("aria-label",vt()||"Jump to latest"))},gt=()=>{_r!==0&&(_r=0,Oe())},It=()=>Ct()==="follow"?!qn.isFollowing():!Do(Se,Ko),Vn=()=>{if(!Ht()||Y){Ut.parentNode&&Ut.remove(),Ut.style.display="none";return}Ut.parentNode!==we&&we.appendChild(Ut),kn();let p=Kr(Se)>0&&It();p||gt(),Ut.style.display=p?"":"none"},kr=()=>{qn.pause()&&(fe(),Vn())},mn=()=>{qn.resume(),gt(),Vn()},Zt=(l=!1)=>{Ct()==="follow"&&qn.isFollowing()&&(!l&&!Sr||(pr!==null&&(cancelAnimationFrame(pr),pr=null),Co=!0,pr=requestAnimationFrame(()=>{pr=null,Co=!1,qn.isFollowing()&&ro(q(),l?220:140)})))},no=(l,p,h,b=()=>!0)=>{let S=l.scrollTop,D=p(),V=D-S;J();let $=performance.now();ur=!0;let N=ae=>1-Math.pow(1-ae,3),se=ae=>{if(!b()){J();return}let Z=p();Z!==D&&(D=Z,V=D-S);let be=ae-$,Ne=Math.min(be/h,1),Ce=N(Ne),et=S+V*Ce;l.scrollTop=et,jn=l.scrollTop,Ne<1?j=requestAnimationFrame(se):(l.scrollTop=D,jn=l.scrollTop,j=null,ur=!1)};j=requestAnimationFrame(se)},ro=(l,p=500)=>{let h=Kr(l)-l.scrollTop;if(Math.abs(h)<1){jn=l.scrollTop;return}if(Math.abs(h)>=da){J(),ur=!0,l.scrollTop=Kr(l),jn=l.scrollTop,ur=!1;return}no(l,()=>Kr(l),p,()=>qn.isFollowing())},In=()=>{let l=q();ur=!0,l.scrollTop=Kr(l),jn=l.scrollTop,ur=!1,Vn()},Wn=l=>{vn.style.height=`${Math.max(0,Math.round(l))}px`,xn&&(xn.spacerHeight=Math.max(0,l))},wn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),J(),xn=null,vn.style.height="0px"},pg=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var se;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Se.querySelector(`[data-message-id="${p}"]`);if(!h)return;let b=0,S=h;for(;S&&S!==Se;)b+=S.offsetTop,S=S.offsetParent;let D=(se=xn==null?void 0:xn.spacerHeight)!=null?se:0,V=Se.scrollHeight-D,{targetScrollTop:$,spacerHeight:N}=rm({anchorOffsetTop:b,topOffset:un(),viewportHeight:Se.clientHeight,contentHeight:V});xn={initialSpacerHeight:N,contentHeightAtAnchor:V,spacerHeight:N},Wn(N),no(Se,()=>$,220)})},ug=()=>{if(Ct()==="follow"){if(!qn.isFollowing()||Do(Se,1))return;Zt(!Sr);return}if(xn&&xn.initialSpacerHeight>0){let l=Se.scrollHeight-xn.spacerHeight,p=om({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:l});p!==xn.spacerHeight&&Wn(p)}Vn()},mg=l=>{let p=Ct();p==="follow"?(mn(),Zt(!0)):p==="anchor-top"&&pg(l)},gg=l=>{let p=new Map;l.forEach(h=>{let b=Go.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!Ao&&Ct()!=="anchor-top"&&It()&&(_r+=1,Oe(),Vn())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),Go.clear(),p.forEach((h,b)=>{Go.set(b,h)})},fg=(l,p,h)=>{var rt,Pe,ke,qe,Ke,ft;let b=document.createElement("div"),D=(()=>{var Re;let W=o.find(Ie=>Ie.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Re=r.loadingIndicator)!=null&&Re.render)return r.loadingIndicator.render})(),V=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),$=new Set,N=new Set,se=o.some(W=>W.renderAskUserQuestion),ae=[],Z=[],be=r.enableComponentStreaming!==!1,Ne=r.approval!==!1,Ce=[];if(p.forEach(W=>{var Ge,kt,on,or,Gn,To,Eo,es,ts,Xt,Mo,ao,io,Ur,ko,mr,Pr;$.add(W.id);let Re=se&&Wo(W),Ie=Ne&&W.variant==="approval"&&!!W.approval,ge=!Re&&W.role==="assistant"&&!W.variant&&be&&Vm(W);if(!Ie&&dr.has(W.id)){let Xe=l.querySelector(`#wrapper-${W.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),dr.delete(W.id)}if(!ge&&Er.has(W.id)){let Xe=l.querySelector(`#wrapper-${W.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime"),Er.delete(W.id)}let Ot=Wo(W)?`:${(Ge=W.agentMetadata)!=null&&Ge.askUserQuestionAnswered?"a":"u"}:${(kt=W.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=Ju(W,qo)+Ot,Qt=Re||Ie||ge?null:Zu(Tr,W.id,Dt);if(Qt){b.appendChild(Qt.cloneNode(!0)),Wo(W)&&((on=W.toolCall)!=null&&on.id)&&((or=W.agentMetadata)==null?void 0:or.awaitingLocalTool)===!0&&!((Gn=W.agentMetadata)!=null&&Gn.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Ca(W,r,je.composerOverlay));return}let ht=null,Vt=o.find(Xe=>!!(W.variant==="reasoning"&&Xe.renderReasoning||W.variant==="tool"&&Xe.renderToolCall||!W.variant&&Xe.renderMessage)),Kn=(To=r.layout)==null?void 0:To.messages;if(Wo(W)&&((Eo=W.agentMetadata)==null?void 0:Eo.askUserQuestionAnswered)===!0){Or.delete(W.id);let Xe=l.querySelector(`#wrapper-${W.id}`);Xe==null||Xe.removeAttribute("data-preserve-runtime");return}if(ki(W)&&((ts=(es=r.features)==null?void 0:es.suggestReplies)==null?void 0:ts.enabled)!==!1)return;if(Wo(W)&&((Mo=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:Mo.enabled)!==!1){let Xe=o.find(_t=>typeof _t.renderAskUserQuestion=="function");if(Xe&&St.current){let _t=Or.get(W.id),Gt=_t!==Dt,$t=null;if(Gt){let{payload:zt,complete:gn}=ss(W),Qn=W.id,Ir=()=>{var fn;return(fn=St.current)==null?void 0:fn.getMessages().find(hn=>hn.id===Qn)};$t=Xe.renderAskUserQuestion({message:W,payload:zt,complete:gn,resolve:fn=>{var sr;let hn=Ir();hn&&((sr=St.current)==null||sr.resolveAskUserQuestion(hn,fn))},dismiss:()=>{var hn,sr,lo;let fn=Ir();(hn=fn==null?void 0:fn.agentMetadata)!=null&&hn.awaitingLocalTool&&((sr=St.current)==null||sr.markAskUserQuestionResolved(fn),(lo=St.current)==null||lo.resolveAskUserQuestion(fn,"(dismissed)"))},config:r})}let Jt=_t!=null;if(Gt&&$t===null&&!Jt){((ao=W.agentMetadata)==null?void 0:ao.awaitingLocalTool)===!0&&!((io=W.agentMetadata)!=null&&io.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Ca(W,r,je.composerOverlay));return}let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-${W.id}`,Lt.setAttribute("data-wrapper-id",W.id),Lt.setAttribute("data-ask-plugin-stub","true"),Lt.setAttribute("data-preserve-runtime","true"),b.appendChild(Lt),ae.push({messageId:W.id,fingerprint:Dt,bubble:$t});return}else{((Ur=W.agentMetadata)==null?void 0:Ur.awaitingLocalTool)===!0&&!((ko=W.agentMetadata)!=null&&ko.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Ca(W,r,je.composerOverlay));return}}else if(Ie){let Xe=(mr=o.find(Jt=>typeof Jt.renderApproval=="function"))!=null?mr:s,Gt=dr.get(W.id)!==Dt,$t=null;if(Gt&&(Xe!=null&&Xe.renderApproval)){let Jt=W.id,Lt=(zt,gn)=>{var Ir,fn,hn;let Qn=(Ir=St.current)==null?void 0:Ir.getMessages().find(sr=>sr.id===Jt);Qn!=null&&Qn.approval&&(Qn.approval.toolType==="webmcp"?(fn=St.current)==null||fn.resolveWebMcpApproval(Qn.id,zt):(hn=St.current)==null||hn.resolveApproval(Qn.approval,zt,gn))};$t=Xe.renderApproval({message:W,defaultRenderer:()=>ni(W,r),config:r,approve:zt=>Lt("approved",zt),deny:zt=>Lt("denied",zt)})}if(Gt&&$t===null){let Jt=l.querySelector(`#wrapper-${W.id}`);Jt==null||Jt.removeAttribute("data-preserve-runtime"),dr.delete(W.id),ht=ni(W,r)}else{let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${W.id}`,Jt.setAttribute("data-wrapper-id",W.id),Jt.setAttribute("data-approval-plugin-stub","true"),Jt.setAttribute("data-preserve-runtime","true"),b.appendChild(Jt),Ce.push({messageId:W.id,fingerprint:Dt,bubble:$t});return}}else if(Vt)if(W.variant==="reasoning"&&W.reasoning&&Vt.renderReasoning){if(!xe)return;ht=Vt.renderReasoning({message:W,defaultRenderer:()=>Qi(W,r),config:r})}else if(W.variant==="tool"&&W.toolCall&&Vt.renderToolCall){if(!We)return;ht=Vt.renderToolCall({message:W,defaultRenderer:()=>Ji(W,r),config:r})}else Vt.renderMessage&&(ht=Vt.renderMessage({message:W,defaultRenderer:()=>{let Xe=Gi(W,h,Kn,r.messageActions,Je,{loadingIndicatorRenderer:D,widgetConfig:r});return W.role!=="user"&&nl(Xe,W,r,z),Xe},config:r}));if(!ht&&ge){let Xe=Km(W);if(Xe){let _t=Er.get(W.id),Gt=_t!==Dt,$t=r.wrapComponentDirectiveInBubble!==!1,Jt=null;if(Gt){let Lt=qm(Xe,{config:r,message:W,transform:h});if(Lt)if($t){let zt=document.createElement("div");if(zt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),zt.id=`bubble-${W.id}`,zt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),zt.appendChild(gn)}zt.appendChild(Lt),Jt=zt}else{let zt=document.createElement("div");if(zt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",zt.id=`bubble-${W.id}`,zt.setAttribute("data-message-id",W.id),zt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),zt.appendChild(gn)}zt.appendChild(Lt),Jt=zt}}if(Jt||_t!=null){let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-${W.id}`,Lt.setAttribute("data-wrapper-id",W.id),Lt.setAttribute("data-component-directive-stub","true"),Lt.setAttribute("data-preserve-runtime","true"),$t||Lt.classList.add("persona-w-full"),b.appendChild(Lt),Z.push({messageId:W.id,fingerprint:Dt,bubble:Jt});return}}}if(!ht)if(W.variant==="reasoning"&&W.reasoning){if(!xe)return;ht=Qi(W,r)}else if(W.variant==="tool"&&W.toolCall){if(!We)return;ht=Ji(W,r)}else if(W.variant==="approval"&&W.approval){if(r.approval===!1)return;ht=ni(W,r)}else{let Xe=(Pr=r.layout)==null?void 0:Pr.messages;Xe!=null&&Xe.renderUserMessage&&W.role==="user"?ht=Xe.renderUserMessage({message:W,config:r,streaming:!!W.streaming}):Xe!=null&&Xe.renderAssistantMessage&&W.role==="assistant"?ht=Xe.renderAssistantMessage({message:W,config:r,streaming:!!W.streaming}):ht=Gi(W,h,Xe,r.messageActions,Je,{loadingIndicatorRenderer:D,widgetConfig:r}),W.role!=="user"&&ht&&nl(ht,W,r,z)}let nn=document.createElement("div");nn.className="persona-flex",nn.id=`wrapper-${W.id}`,nn.setAttribute("data-wrapper-id",W.id),W.role==="user"&&nn.classList.add("persona-justify-end"),(ht==null?void 0:ht.getAttribute("data-persona-component-directive"))==="true"&&nn.classList.add("persona-w-full"),nn.appendChild(ht),em(Tr,W.id,Dt,nn),b.appendChild(nn)}),je.composerOverlay&&je.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Ie=Re.getAttribute("data-persona-ask-sheet-for");Ie&&!N.has(Ie)&&is(je.composerOverlay,Ie)}),(Pe=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Pe.grouped){let W=[],Re=[];p.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&We){Re.push(Ie);return}Re.length>1&&W.push(Re),Re=[]}),Re.length>1&&W.push(Re),W.forEach((Ie,ge)=>{var Ge,kt;let Ot=Ie.map(on=>Array.from(b.children).find(or=>or instanceof HTMLElement&&or.getAttribute("data-wrapper-id")===on.id)).filter(on=>!!on);if(Ot.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${ge}-${Ie[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${ge}-${Ie[0].id}`);let Qt=document.createElement("div");Qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Qt.setAttribute("data-persona-tool-group","true");let ht=document.createElement("div");ht.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Vt=`Called ${Ie.length} tools`,Kn=(kt=(Ge=r.toolCall)==null?void 0:Ge.renderGroupedSummary)==null?void 0:kt.call(Ge,{messages:Ie,toolCalls:Ie.map(on=>on.toolCall).filter(on=>!!on),defaultSummary:Vt,config:r});V(ht,Kn)||(ht.textContent=Vt);let nn=document.createElement("div");nn.className="persona-tool-group-stack persona-flex persona-flex-col",Qt.append(ht,nn),Dt.appendChild(Qt),Ot[0].before(Dt),Ot.forEach((on,or)=>{let Gn=document.createElement("div");Gn.className="persona-tool-group-item persona-relative",Gn.setAttribute("data-persona-tool-group-item","true"),or<Ot.length-1&&Gn.setAttribute("data-persona-tool-group-connector","true"),Gn.appendChild(on),nn.appendChild(Gn)})})}tm(Tr,$);let et=p.some(W=>W.role==="assistant"&&W.streaming),Ue=p[p.length-1],ct=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(Sr&&p.some(W=>W.role==="user")&&!et&&!ct){let W={config:r,streaming:!0,location:"standalone",defaultRenderer:na},Re=o.find(ge=>ge.renderLoadingIndicator),Ie=null;if(Re!=null&&Re.renderLoadingIndicator&&(Ie=Re.renderLoadingIndicator(W)),Ie===null&&((ke=r.loadingIndicator)!=null&&ke.render)&&(Ie=r.loadingIndicator.render(W)),Ie===null&&(Ie=na()),Ie){let ge=document.createElement("div"),Ot=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;ge.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(Ie);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(ge),b.appendChild(Dt)}}if(!Sr&&p.length>0){let W=p[p.length-1],Re={config:r,lastMessage:W,messageCount:p.length},Ie=o.find(Ot=>Ot.renderIdleIndicator),ge=null;if(Ie!=null&&Ie.renderIdleIndicator&&(ge=Ie.renderIdleIndicator(Re)),ge===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Re)),ge){let Ot=document.createElement("div"),Dt=((ft=r.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Ot.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(ge);let Qt=document.createElement("div");Qt.className="persona-flex",Qt.id="wrapper-idle-indicator",Qt.setAttribute("data-wrapper-id","idle-indicator"),Qt.appendChild(Ot),b.appendChild(Qt)}}if(Na(l,b),ae.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ie}of ae){let ge=l.querySelector(`#wrapper-${W}`);ge&&Ie!==null&&(ge.replaceChildren(Ie),ge.setAttribute("data-bubble-fp",Re),Or.set(W,Re))}if(Or.size>0)for(let W of Or.keys())$.has(W)||Or.delete(W);if(Z.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ie}of Z){let ge=l.querySelector(`#wrapper-${W}`);ge&&Ie!==null&&(ge.replaceChildren(Ie),ge.setAttribute("data-bubble-fp",Re),Er.set(W,Re))}if(Er.size>0)for(let W of Er.keys())$.has(W)||Er.delete(W);if(Ce.length>0)for(let{messageId:W,fingerprint:Re,bubble:Ie}of Ce){let ge=l.querySelector(`#wrapper-${W}`);ge&&Ie!==null&&(ge.replaceChildren(Ie),ge.setAttribute("data-bubble-fp",Re),dr.set(W,Re))}if(dr.size>0)for(let W of dr.keys())$.has(W)||dr.delete(W)},Cs=(l,p,h)=>{fg(l,p,h),Jr()},As=null,hg=()=>{var h;if(As)return;let l=b=>{let S=b.composedPath();S.includes(He)||Ve&&S.includes(Ve)||jt(!1,"user")};As=l,((h=t.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},hl=()=>{var p;if(!As)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("pointerdown",As,!0),As=null};mt.push(()=>hl());let Ss=null,yg=()=>{var h;if(Ss)return;let l=b=>{b.key==="Escape"&&(b.isComposing||jt(!1,"user"))};Ss=l,((h=t.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},yl=()=>{var p;if(!Ss)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("keydown",Ss,!0),Ss=null};mt.push(()=>yl());let Ts=!1,bl=new Set,bg=()=>{var p,h,b,S;let l=(b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},Xo=()=>{var ct,rt,Pe,ke;if(!H())return;let l=je.peekBanner,p=je.peekTextNode;if(!l||!p)return;if(F){l.classList.remove("persona-pill-peek--visible");return}let h=(ct=z==null?void 0:z.getMessages())!=null?ct:[],b;for(let qe=h.length-1;qe>=0;qe--){let Ke=h[qe];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let S=b.content,D=!!b.streaming,V=bg(),$=Ua(V),N=$.type!=="none"?Qs($.type,V==null?void 0:V.plugins):null,se=((rt=N==null?void 0:N.isAnimating)==null?void 0:rt.call(N,b))===!0,ae=N!==null&&(D||se);ae&&N&&!bl.has(N.name)&&(_i(N,t),bl.add(N.name));let Z=ae&&(N!=null&&N.containerClass)?N.containerClass:null,be=(Pe=p.dataset.personaPeekStreamClass)!=null?Pe:null;be&&be!==Z&&(p.classList.remove(be),delete p.dataset.personaPeekStreamClass),Z&&be!==Z&&(p.classList.add(Z),p.dataset.personaPeekStreamClass=Z),ae?(p.style.setProperty("--persona-stream-step",`${$.speed}ms`),p.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Ne=ae?za(S,$.buffer,N,b,D):S;if(ae&&$.placeholder==="skeleton"&&D&&(!Ne||!Ne.trim())){let qe=document.createElement("div"),Ke=Js();Ke.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Ke),Na(p,qe)}else{let qe=Math.max(0,Ne.length-100),Ke=Ne.length>100?Ne.slice(-100):Ne,ft=co(Ke);if(!ae||!N){let W=Ne.length>100?`\u2026${Ke}`:Ke;p.textContent!==W&&(p.textContent=W)}else{let W=ft;(N.wrap==="char"||N.wrap==="word")&&(W=Xs(ft,N.wrap,`peek-${b.id}`,{skipTags:N.skipTags,startIndex:qe}));let Re=document.createElement("div");if(Re.innerHTML=W,N.useCaret&&Ke.length>0){let Ie=qa(),ge=Re.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=ge[ge.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(Ie,Ot.nextSibling):Re.appendChild(Ie)}Na(p,Re),(ke=N.onAfterRender)==null||ke.call(N,{container:p,bubble:l,messageId:b.id,message:b,speed:$.speed,duration:$.duration})}}let Ue=Sr||Ts;l.classList.toggle("persona-pill-peek--visible",Ue)};if(H()){let l=je.peekBanner;if(l){let b=S=>{S.preventDefault(),S.stopPropagation(),jt(!0,"user")};l.addEventListener("pointerdown",b),mt.push(()=>{l.removeEventListener("pointerdown",b)})}let p=()=>{Ts||(Ts=!0,Xo())},h=()=>{Ts&&(Ts=!1,Xo())};Q.addEventListener("pointerenter",p),Q.addEventListener("pointerleave",h),mt.push(()=>{Q.removeEventListener("pointerenter",p),Q.removeEventListener("pointerleave",h)}),Ve&&(Ve.addEventListener("pointerenter",p),Ve.addEventListener("pointerleave",h),mt.push(()=>{Ve.removeEventListener("pointerenter",p),Ve.removeEventListener("pointerleave",h)}))}let vg=l=>{var be,Ne,Ce,et,Ue,ct,rt,Pe;let p=(Ne=(be=r.launcher)==null?void 0:be.composerBar)!=null?Ne:{},h=(Ce=p.expandedSize)!=null?Ce:"anchored",b=(et=p.bottomOffset)!=null?et:"16px",S=p.collapsedMaxWidth,D=(Ue=p.expandedMaxWidth)!=null?Ue:"880px",V=(ct=p.expandedTopOffset)!=null?ct:"5vh",$=(rt=p.modalMaxWidth)!=null?rt:"880px",N=(Pe=p.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",se="calc(100vw - 32px)",ae="var(--persona-pill-area-height, 80px)",Z=He.style;if(Z.left="",Z.right="",Z.top="",Z.bottom="",Z.transform="",Z.width="",Z.maxWidth="",Z.height="",Z.maxHeight="",Ve){let ke=Ve.style;ke.bottom=b,ke.width=S!=null?S:""}if(l&&h!=="fullscreen"){if(h==="modal"){Z.top="50%",Z.left="50%",Z.transform="translate(-50%, -50%)",Z.bottom="auto",Z.right="auto",Z.width=$,Z.maxWidth=se,Z.maxHeight=N,Z.height=N;return}Z.left="50%",Z.transform="translateX(-50%)",Z.bottom=`calc(${b} + ${ae})`,Z.top=V,Z.width=D,Z.maxWidth=se}},Es=()=>{var N,se,ae,Z,be,Ne,Ce,et;if(!U())return;if(H()){let ct=(ae=((se=(N=r.launcher)==null?void 0:N.composerBar)!=null?se:{}).expandedSize)!=null?ae:"anchored",rt=F?"expanded":"collapsed";He.dataset.state=rt,He.dataset.expandedSize=ct,Ve&&(Ve.dataset.state=rt,Ve.dataset.expandedSize=ct),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),vg(F),we.style.display=F?"flex":"none",wr(),F?(hg(),yg()):(hl(),yl()),Xo();return}let l=bn(r),p=(Z=t.ownerDocument.defaultView)!=null?Z:window,h=(Ne=(be=r.launcher)==null?void 0:be.mobileBreakpoint)!=null?Ne:640,b=(et=(Ce=r.launcher)==null?void 0:Ce.mobileFullscreen)!=null?et:!0,S=p.innerWidth<=h,D=b&&S&&k,V=hr(r).reveal;F?(He.style.removeProperty("display"),He.style.display=l?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),tn?tn.element.style.display="none":ln&&(ln.style.display="none")):(l?l&&(V==="overlay"||V==="push")&&!D?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),tn?tn.element.style.display=l?"none":"":ln&&(ln.style.display=l?"none":""))},jt=(l,p="user")=>{var D,V;if(!U()||F===l)return;let h=F;F=l,Es();let b=(()=>{var Ce,et,Ue,ct,rt,Pe,ke,qe,Ke,ft;let $=(et=(Ce=r.launcher)==null?void 0:Ce.sidebarMode)!=null?et:!1,N=(Ue=t.ownerDocument.defaultView)!=null?Ue:window,se=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,ae=(ke=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?ke:640,Z=N.innerWidth<=ae,be=bn(r)&&se&&Z,Ne=H()&&((ft=(Ke=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Ke.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return $||se&&Z&&k||be||Ne})();if(F&&b){if(!sn){let $=t.getRootNode(),N=$ instanceof ShadowRoot?$.host:t.closest(".persona-host");N&&(sn=$i(N,(V=(D=r.launcher)==null?void 0:D.zIndex)!=null?V:Sn))}an||(an=Ui(t.ownerDocument))}else F||(sn==null||sn(),sn=null,an==null||an(),an=null);F&&(Ms(),Ct()==="follow"?Zt(!0):In());let S={open:F,source:p,timestamp:Date.now()};F&&!h?i.emit("widget:opened",S):!F&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:F,launcherEnabled:k,voiceActive:pt.active,streaming:z.isStreaming()})},li=l=>{Rt(l?"stop":"send"),P&&(P.disabled=l),wo.buttons.forEach(p=>{p.disabled=l}),Le.dataset.personaComposerStreaming=l?"true":"false",Le.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},ci=()=>{pt.active||Te&&Te.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ci(),200)});let vl=()=>{var h,b,S,D,V,$,N,se,ae,Z,be;Rr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",B.textContent=(D=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",Te.placeholder=($=(V=r.copy)==null?void 0:V.inputPlaceholder)!=null?$:"How can I help...";let l=Se.querySelector("[data-persona-intro-card]");if(l){let Ne=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(Se.classList.remove("persona-gap-3"),Se.classList.add("persona-gap-6")):(Se.classList.remove("persona-gap-6"),Se.classList.add("persona-gap-3"))}!((ae=(se=r.sendButton)==null?void 0:se.useIcon)!=null&&ae)&&!(z!=null&&z.isStreaming())&&(_e.textContent=(be=(Z=r.copy)==null?void 0:Z.sendButtonLabel)!=null?be:"Send"),Te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(p=>({...p,sessionId:l}))}});let So=null,xg=()=>{So==null&&(So=setInterval(()=>{let l=Ye.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(So),So=null;return}let p=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Sa(p-b))})},100))};z=new Ha(r,{onMessagesChanged(l){var b;Cs(Ye,l,te),xg(),zo(l),Zt(!Sr),gg(l);let p=[...l].reverse().find(S=>S.role==="user");l.length===0&&wn(),!jo||Ao?(jo=!0,Vo=(b=p==null?void 0:p.id)!=null?b:null):p&&p.id!==Vo&&(Vo=p.id,mg(p.id));let h=pt.lastUserMessageId;p&&p.id!==h&&(pt.lastUserMessageId=p.id,i.emit("user:message",p)),pt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),w(l),Xo()},onStatusChanged(l){var b;let p=(b=r.statusIndicator)!=null?b:{};dt(Yt,(S=>{var D,V,$,N;return S==="idle"?(D=p.idleText)!=null?D:An.idle:S==="connecting"?(V=p.connectingText)!=null?V:An.connecting:S==="connected"?($=p.connectedText)!=null?$:An.connected:S==="error"?(N=p.errorText)!=null?N:An.error:An[S]})(l),p,l)},onStreamingChanged(l){Sr=l,li(l),z&&Cs(Ye,z.getMessages(),te),l||Zt(!0),Xo()},onVoiceStatusChanged(l){var p,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":$r(),Yo();break;case"processing":$r(),Tg();break;case"speaking":$r(),Eg();break;default:l==="idle"&&z.isBargeInActive()?($r(),Yo(),P==null||P.setAttribute("aria-label","End voice session")):(pt.active=!1,$r(),tr("system"),Nn());break}},onArtifactsState(l){$n=l,Dn(),w()}}),St.current=z;let di=null;if(z.onReadAloudChange((l,p)=>{var S;Qr=l,Xr=p,Jr();let h=l!=null?l:di;l&&(di=l);let b=h&&(S=z.getMessages().find(D=>D.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(di=null)}),jo=!0,((Pc=(Lc=r.voiceRecognition)==null?void 0:Lc.provider)==null?void 0:Pc.type)==="runtype")try{z.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&z.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(G||r.onSSEEvent)&&z.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),X==null||X.processEvent(l,p),G==null||G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),f&&f.then(l=>{var p,h,b;if(l){if(l.metadata&&(u=cl(l.metadata),T.syncFromMetadata()),(p=l.messages)!=null&&p.length){Ao=!0;try{z.hydrateMessages(l.messages)}finally{Ao=!1}}(h=l.artifacts)!=null&&h.length&&z.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let xl=()=>{var p,h,b;!H()||F||!((b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||jt(!0,"auto")},wl=l=>{var S;if(l.preventDefault(),z.isStreaming()){z.cancel(),X==null||X.reset(),ve==null||ve.update();return}let p=Te.value.trim(),h=(S=At==null?void 0:At.hasAttachments())!=null?S:!1;if(!p&&!h)return;xl();let b;h&&(b=[],b.push(...At.getContentParts()),p&&b.push(Wi(p))),Te.value="",Te.style.height="auto",pa(),z.sendMessage(p,{contentParts:b}),h&&At.clearAttachments()},wg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},pi={...Fa},ui=!1,pa=()=>{pi={...Fa}},Cg=()=>z.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Ag=l=>{if(!Te)return;ui=!0,Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),ui=!1;let p=Te.value.length;Te.setSelectionRange(p,p)},Cl=()=>{ui||pa()},Al=l=>{if(Te){if(wg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Te.selectionStart===0&&Te.selectionEnd===0,h=Xu({direction:l.key==="ArrowUp"?"up":"down",history:Cg(),currentValue:Te.value,atStart:p,state:pi});if(pi=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Ag(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(z.isStreaming()){l.preventDefault();return}pa(),l.preventDefault(),_e.click()}}},Sl=l=>{l.key!=="Escape"||l.isComposing||z.isStreaming()&&l.composedPath().includes(we)&&(z.cancel(),X==null||X.reset(),ve==null||ve.update(),pa(),l.preventDefault(),l.stopImmediatePropagation())},Tl=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let p=Hy(l.clipboardData);p.length!==0&&(l.preventDefault(),await At.handleFiles(p))},nr=null,Lr=!1,Jo=null,lt=null,El=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ua=(l="user")=>{var D,V,$,N,se,ae,Z;if(Lr||z.isStreaming())return;let p=El();if(!p)return;nr=new p;let b=(V=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?V:2e3;nr.continuous=!0,nr.interimResults=!0,nr.lang="en-US";let S=Te.value;nr.onresult=be=>{let Ne="",Ce="";for(let Ue=0;Ue<be.results.length;Ue++){let ct=be.results[Ue],rt=ct[0].transcript;ct.isFinal?Ne+=rt+" ":Ce=rt}let et=S+Ne+Ce;Te.value=et,Jo&&clearTimeout(Jo),(Ne||Ce)&&(Jo=window.setTimeout(()=>{let Ue=Te.value.trim();Ue&&nr&&Lr&&(oo(),Te.value="",Te.style.height="auto",z.sendMessage(Ue,{viaVoice:!0}))},b))},nr.onerror=be=>{be.error!=="no-speech"&&oo()},nr.onend=()=>{if(Lr){let be=Te.value.trim();be&&be!==S.trim()&&(Te.value="",Te.style.height="auto",z.sendMessage(be,{viaVoice:!0})),oo()}};try{if(nr.start(),Lr=!0,pt.active=!0,l!=="system"&&(pt.manuallyDeactivated=!1),tr(l),Nn(),P){let be=($=r.voiceRecognition)!=null?$:{};lt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(N=be.iconName)!=null?N:"mic",iconSize:parseFloat((Z=(ae=be.iconSize)!=null?ae:(se=r.sendButton)==null?void 0:se.size)!=null?Z:"40")||24};let Ne=be.recordingBackgroundColor,Ce=be.recordingIconColor,et=be.recordingBorderColor;if(P.classList.add("persona-voice-recording"),P.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=Ce!=null?Ce:"var(--persona-voice-recording-indicator, #ffffff)",Ce){let Ue=P.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ce)}et&&(P.style.borderColor=et),P.setAttribute("aria-label","Stop voice recognition")}}catch{oo("system")}},oo=(l="user")=>{if(Lr){if(Lr=!1,Jo&&(clearTimeout(Jo),Jo=null),nr){try{nr.stop()}catch{}nr=null}if(pt.active=!1,tr(l),Nn(),P){if(P.classList.remove("persona-voice-recording"),lt){P.style.backgroundColor=lt.backgroundColor,P.style.color=lt.color,P.style.borderColor=lt.borderColor;let p=P.querySelector("svg");p&&p.setAttribute("stroke",lt.color||"currentColor"),lt=null}P.setAttribute("aria-label","Start voice recognition")}}},Sg=(l,p)=>{var rt,Pe,ke,qe,Ke,ft,W,Re,Ie;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((rt=l==null?void 0:l.provider)==null?void 0:rt.type)==="runtype",S=((Pe=l==null?void 0:l.provider)==null?void 0:Pe.type)==="custom";if(!(h||b||S))return null;let V=y("div","persona-send-button-wrapper"),$=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button",$.setAttribute("aria-label","Start voice recognition");let N=(ke=l==null?void 0:l.iconName)!=null?ke:"mic",se=(qe=p==null?void 0:p.size)!=null?qe:"40px",ae=(Ke=l==null?void 0:l.iconSize)!=null?Ke:se,Z=parseFloat(ae)||24,be=(ft=l==null?void 0:l.backgroundColor)!=null?ft:p==null?void 0:p.backgroundColor,Ne=(W=l==null?void 0:l.iconColor)!=null?W:p==null?void 0:p.textColor;$.style.width=ae,$.style.height=ae,$.style.minWidth=ae,$.style.minHeight=ae,$.style.fontSize="18px",$.style.lineHeight="1",Ne?$.style.color=Ne:$.style.color="var(--persona-text, #111827)";let et=he(N,Z,Ne||"currentColor",1.5);et?$.appendChild(et):$.textContent="\u{1F3A4}",be?$.style.backgroundColor=be:$.style.backgroundColor="",l!=null&&l.borderWidth&&($.style.borderWidth=l.borderWidth,$.style.borderStyle="solid"),l!=null&&l.borderColor&&($.style.borderColor=l.borderColor),l!=null&&l.paddingX&&($.style.paddingLeft=l.paddingX,$.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&($.style.paddingTop=l.paddingY,$.style.paddingBottom=l.paddingY),V.appendChild($);let Ue=(Re=l==null?void 0:l.tooltipText)!=null?Re:"Start voice recognition";if(((Ie=l==null?void 0:l.showTooltip)!=null?Ie:!1)&&Ue){let ge=y("div","persona-send-button-tooltip");ge.textContent=Ue,V.appendChild(ge)}return{micButton:$,micButtonWrapper:V}},mi=()=>{var p,h,b,S,D;if(!P||lt)return;let l=(p=r.voiceRecognition)!=null?p:{};lt={backgroundColor:P.style.backgroundColor,color:P.style.color,borderColor:P.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((D=(S=l.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},gi=(l,p)=>{var D,V,$,N,se;if(!P)return;let h=P.querySelector("svg");h&&h.remove();let b=(se=lt==null?void 0:lt.iconSize)!=null?se:parseFloat((N=($=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?$:(V=r.sendButton)==null?void 0:V.size)!=null?N:"40")||24,S=he(l,b,p,1.5);S&&P.appendChild(S)},ma=()=>{P&&P.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Yo=()=>{var S;if(!P)return;mi();let l=(S=r.voiceRecognition)!=null?S:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(ma(),P.classList.add("persona-voice-recording"),P.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",P.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=P.querySelector("svg");D&&D.setAttribute("stroke",h)}b&&(P.style.borderColor=b),P.setAttribute("aria-label","Stop voice recognition")},Tg=()=>{var $,N,se,ae,Z,be,Ne,Ce;if(!P)return;mi();let l=($=r.voiceRecognition)!=null?$:{},p=z.getVoiceInterruptionMode(),h=(N=l.processingIconName)!=null?N:"loader",b=(ae=(se=l.processingIconColor)!=null?se:lt==null?void 0:lt.color)!=null?ae:"",S=(be=(Z=l.processingBackgroundColor)!=null?Z:lt==null?void 0:lt.backgroundColor)!=null?be:"",D=(Ce=(Ne=l.processingBorderColor)!=null?Ne:lt==null?void 0:lt.borderColor)!=null?Ce:"";ma(),P.classList.add("persona-voice-processing"),P.style.backgroundColor=S,P.style.borderColor=D;let V=b||"currentColor";P.style.color=V,gi(h,V),P.setAttribute("aria-label","Processing voice input"),p==="none"&&(P.style.cursor="default")},Eg=()=>{var se,ae,Z,be,Ne,Ce,et,Ue,ct,rt,Pe,ke;if(!P)return;mi();let l=(se=r.voiceRecognition)!=null?se:{},p=z.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(ae=l.speakingIconName)!=null?ae:h,S=(Ce=l.speakingIconColor)!=null?Ce:p==="barge-in"?(be=(Z=l.recordingIconColor)!=null?Z:lt==null?void 0:lt.color)!=null?be:"":(Ne=lt==null?void 0:lt.color)!=null?Ne:"",D=(ct=l.speakingBackgroundColor)!=null?ct:p==="barge-in"?(et=l.recordingBackgroundColor)!=null?et:"var(--persona-voice-recording-bg, #ef4444)":(Ue=lt==null?void 0:lt.backgroundColor)!=null?Ue:"",V=(ke=l.speakingBorderColor)!=null?ke:p==="barge-in"?(rt=l.recordingBorderColor)!=null?rt:"":(Pe=lt==null?void 0:lt.borderColor)!=null?Pe:"";ma(),P.classList.add("persona-voice-speaking"),P.style.backgroundColor=D,P.style.borderColor=V;let $=S||"currentColor";P.style.color=$,gi(b,$);let N=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";P.setAttribute("aria-label",N),p==="none"&&(P.style.cursor="default"),p==="barge-in"&&P.classList.add("persona-voice-recording")},$r=()=>{var l,p,h;P&&(ma(),lt&&(P.style.backgroundColor=(l=lt.backgroundColor)!=null?l:"",P.style.color=(p=lt.color)!=null?p:"",P.style.borderColor=(h=lt.borderColor)!=null?h:"",gi(lt.iconName,lt.color||"currentColor"),lt=null),P.style.cursor="",P.setAttribute("aria-label","Start voice recognition"))},ga=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=z.getVoiceStatus(),b=z.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Nn(),tr("user"),$r()});return}z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),pt.manuallyDeactivated=!z.isVoiceActive(),Nn(),tr("user"),z.isVoiceActive()?Yo():$r()});return}if(Lr){let h=Te.value.trim();pt.manuallyDeactivated=!0,Nn(),oo("user"),h&&(Te.value="",Te.style.height="auto",z.sendMessage(h))}else pt.manuallyDeactivated=!1,Nn(),ua("user")};br=ga,P&&(P.addEventListener("click",ga),mt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),$r()):oo("system"),P&&P.removeEventListener("click",ga)}));let Mg=i.on("assistant:complete",()=>{ws&&(pt.active||pt.manuallyDeactivated||ws==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!pt.active&&!pt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),tr("auto"),z.isVoiceActive()&&Yo()}):ua("auto"))},600))});mt.push(Mg);let kg=i.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});mt.push(kg);let Ml=()=>{jt(!F,"user")},tn=null,ln=null;if(k&&!H()){let{instance:l,element:p}=ji({config:r,plugins:o,onToggle:Ml});tn=l,l||(ln=p)}tn?t.appendChild(tn.element):ln&&t.appendChild(ln),Es(),zo(),vl(),li(z.isStreaming()),Ct()==="follow"?Zt(!0):In(),Qo(),I&&(!k||H()?setTimeout(()=>ci(),0):F&&setTimeout(()=>ci(),200));let Ms=()=>{var N,se,ae,Z,be,Ne,Ce,et,Ue,ct,rt,Pe,ke,qe,Ke,ft,W,Re,Ie,ge,Ot,Dt;if(H()){kn(),Es();return}let l=bn(r),p=(se=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?se:!1,h=l||p||((Z=(ae=r.launcher)==null?void 0:ae.fullHeight)!=null?Z:!1),b=(be=t.ownerDocument.defaultView)!=null?be:window,S=(Ce=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ce:!0,D=(Ue=(et=r.launcher)==null?void 0:et.mobileBreakpoint)!=null?Ue:640,V=b.innerWidth<=D,$=S&&V&&k;try{if($){wr(),ms(t,r);return}if(_&&(_=!1,wr(),ms(t,r)),!k&&!l){Q.style.height="",Q.style.width="";return}if(!p&&!l){let Qt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,ht=Qt!=null?Qt:Vr;Q.style.width=ht,Q.style.maxWidth=ht}if(ye(),!h){let Qt=b.innerHeight,ht=64,Vt=(ke=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?ke:0,Kn=Math.max(200,Qt-ht),nn=Math.min(640,Kn),Ge=Math.max(200,nn-Vt);Q.style.height=`${Ge}px`}}finally{if(kn(),Es(),F&&k){let ht=((qe=t.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((ft=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?ft:640),Vt=(Re=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?Re:!1,Kn=(ge=(Ie=r.launcher)==null?void 0:Ie.mobileFullscreen)!=null?ge:!0,nn=bn(r)&&Kn&&ht,Ge=Vt||Kn&&ht&&k||nn;if(Ge&&!an){let kt=t.getRootNode(),on=kt instanceof ShadowRoot?kt.host:t.closest(".persona-host");on&&!sn&&(sn=$i(on,(Dt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Dt:Sn)),an=Ui(t.ownerDocument)}else Ge||(sn==null||sn(),sn=null,an==null||an(),an=null)}}};Ms();let kl=(Ic=t.ownerDocument.defaultView)!=null?Ic:window;if(kl.addEventListener("resize",Ms),mt.push(()=>kl.removeEventListener("resize",Ms)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{kn()});l.observe(Le),mt.push(()=>l.disconnect())}jn=Se.scrollTop;let Ll=Kr(Se),Lg=()=>{let l=Se.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Se.ownerDocument.getSelection()},fi=()=>nm(Lg(),Se),Pl=()=>{let l=Se.scrollTop,p=Kr(Se),h=p<Ll;if(Ll=p,Ct()!=="follow"){jn=l,Vn();return}let{action:b,nextLastScrollTop:S}=_a({following:qn.isFollowing(),currentScrollTop:l,lastScrollTop:jn,nearBottom:Do(Se,Ko),userScrollThreshold:ca,isAutoScrolling:ur||Co||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(jn=S,b==="resume"){fi()||mn();return}b==="pause"&&kr()};if(Se.addEventListener("scroll",Pl,{passive:!0}),mt.push(()=>Se.removeEventListener("scroll",Pl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{ug()});l.observe(Ye),l.observe(Se),mt.push(()=>l.disconnect())}let Il=()=>{Ct()==="follow"&&qn.isFollowing()&&fi()&&kr()},Wl=Se.ownerDocument;Wl.addEventListener("selectionchange",Il),mt.push(()=>{Wl.removeEventListener("selectionchange",Il)});let Rl=l=>{if(Ct()!=="follow")return;let p=$a({following:qn.isFollowing(),deltaY:l.deltaY,nearBottom:Do(Se,Ko),resumeWhenNearBottom:!0});p==="pause"?kr():p==="resume"&&!fi()&&mn()};Se.addEventListener("wheel",Rl,{passive:!0}),mt.push(()=>Se.removeEventListener("wheel",Rl)),Ut.addEventListener("click",()=>{wn(),Se.scrollTop=Se.scrollHeight,jn=Se.scrollTop,mn(),Zt(!0),Vn()}),mt.push(()=>Ut.remove()),mt.push(()=>{fe(),wn()});let Hl=()=>{K&&(Ar&&(K.removeEventListener("click",Ar),Ar=null),U()?(K.style.display="",Ar=()=>{jt(!1,"user")},K.addEventListener("click",Ar)):K.style.display="none")};Hl(),(()=>{let{clearChatButton:l}=je;l&&l.addEventListener("click",()=>{z.clearMessages(),Tr.clear(),mn(),is(je.composerOverlay);try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}u={},T.syncFromMetadata(),G==null||G.clear(),X==null||X.reset(),ve==null||ve.update()})})(),Ft&&Ft.addEventListener("submit",wl),Te==null||Te.addEventListener("keydown",Al),Te==null||Te.addEventListener("input",Cl),Te==null||Te.addEventListener("paste",Tl);let Bl=(Wc=t.ownerDocument)!=null?Wc:document;Bl.addEventListener("keydown",Sl,!0);let Dl="persona-attachment-drop-active",ks=0,hi=()=>{ks=0,we.classList.remove(Dl)},Zo=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Nl=l=>{!ai(l.dataTransfer)||!Zo()||(ks++,ks===1&&we.classList.add(Dl))},Fl=l=>{!ai(l.dataTransfer)||!Zo()||(ks--,ks<=0&&hi())},Ol=l=>{!ai(l.dataTransfer)||!Zo()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},_l=l=>{var h;if(!ai(l.dataTransfer)||!Zo())return;l.preventDefault(),l.stopPropagation(),hi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&At.handleFiles(p)},so=!0;we.addEventListener("dragenter",Nl,so),we.addEventListener("dragleave",Fl,so),t.addEventListener("dragover",Ol,so),t.addEventListener("drop",_l,so);let fa=t.ownerDocument,$l=l=>{Zo()&&l.preventDefault()},Ul=l=>{Zo()&&l.preventDefault()};fa.addEventListener("dragover",$l),fa.addEventListener("drop",Ul),mt.push(()=>{Ft&&Ft.removeEventListener("submit",wl),Te==null||Te.removeEventListener("keydown",Al),Te==null||Te.removeEventListener("input",Cl),Te==null||Te.removeEventListener("paste",Tl),Bl.removeEventListener("keydown",Sl,!0)}),mt.push(()=>{we.removeEventListener("dragenter",Nl,so),we.removeEventListener("dragleave",Fl,so),t.removeEventListener("dragover",Ol,so),t.removeEventListener("drop",_l,so),fa.removeEventListener("dragover",$l),fa.removeEventListener("drop",Ul),hi()}),mt.push(()=>{z.cancel()}),tn?mt.push(()=>{tn==null||tn.destroy()}):ln&&mt.push(()=>{ln==null||ln.remove()});let rn={update(l){var zt,gn,Qn,Ir,fn,hn,sr,lo,Oc,_c,$c,Uc,zc,qc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,xd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,zd,qd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,xp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np;let p=r.toolCall,h=r.messageActions,b=(zt=r.layout)==null?void 0:zt.messages,S=r.colorScheme,D=r.loadingIndicator,V=r.iterationDisplay,$=(gn=r.features)==null?void 0:gn.showReasoning,N=(Qn=r.features)==null?void 0:Qn.showToolCalls,se=(Ir=r.features)==null?void 0:Ir.toolCallDisplay,ae=(fn=r.features)==null?void 0:fn.reasoningDisplay;r={...r,...l},wr(),ms(t,r),oi(t,r),si(t,r),Dn(),r.colorScheme!==S&&xs();let Z=ol.getForInstance(r.plugins);o.length=0,o.push(...Z),k=(sr=(hn=r.launcher)==null?void 0:hn.enabled)!=null?sr:!0,E=(Oc=(lo=r.launcher)==null?void 0:lo.autoExpand)!=null?Oc:!1,xe=($c=(_c=r.features)==null?void 0:_c.showReasoning)!=null?$c:!0,We=(zc=(Uc=r.features)==null?void 0:Uc.showToolCalls)!=null?zc:!0,me=(jc=(qc=r.features)==null?void 0:qc.scrollToBottom)!=null?jc:{};let be=Ct();re=(Kc=(Vc=r.features)==null?void 0:Vc.scrollBehavior)!=null?Kc:{},be!==Ct()&&(wn(),mn()),lr(),Vn();let Ne=le;if(le=(Qc=(Gc=r.features)==null?void 0:Gc.showEventStreamToggle)!=null?Qc:!1,le&&!Ne){if(G||(ze=new oa(de),G=new ra(Fe,ze),X=X!=null?X:new sa,ze.open().then(()=>G==null?void 0:G.restore()).catch(()=>{}),z.setSSEEventCallback((ne,Tt)=>{var Kt;(Kt=r.onSSEEvent)==null||Kt.call(r,ne,Tt),X==null||X.processEvent(ne,Tt),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!ut&&De){let ne=(Jc=(Xc=r.features)==null?void 0:Xc.eventStream)==null?void 0:Jc.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");ut=y("button",Tt),ut.style.width="28px",ut.style.height="28px",ut.style.color=Hn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Kt=he("activity","18px","currentColor",1.5);Kt&&ut.appendChild(Kt);let ot=je.clearChatButtonWrapper,Pt=je.closeButtonWrapper,cn=ot||Pt;cn&&cn.parentNode===De?De.insertBefore(ut,cn):De.appendChild(ut),ut.addEventListener("click",()=>{Y?cr():Hr()})}}else!le&&Ne&&(cr(),ut&&(ut.remove(),ut=null),G==null||G.clear(),ze==null||ze.destroy(),G=null,ze=null,X==null||X.reset(),X=null);if(((Yc=r.launcher)==null?void 0:Yc.enabled)===!1&&tn&&(tn.destroy(),tn=null),((Zc=r.launcher)==null?void 0:Zc.enabled)===!1&&ln&&(ln.remove(),ln=null),((ed=r.launcher)==null?void 0:ed.enabled)!==!1&&!tn&&!ln){let{instance:ne,element:Tt}=ji({config:r,plugins:o,onToggle:Ml});tn=ne,ne||(ln=Tt),t.appendChild(Tt)}tn&&tn.update(r),Be&&((td=r.launcher)==null?void 0:td.title)!==void 0&&(Be.textContent=r.launcher.title),$e&&((nd=r.launcher)==null?void 0:nd.subtitle)!==void 0&&($e.textContent=r.launcher.subtitle);let Ce=(rd=r.layout)==null?void 0:rd.header;if((Ce==null?void 0:Ce.layout)!==O&&De){let ne=Ce?Ka(r,Ce,{showClose:U(),onClose:()=>jt(!1,"user")}):No({config:r,showClose:U(),onClose:()=>jt(!1,"user")});tt.replaceHeader(ne),De=tt.header.element,ue=tt.header.iconHolder,Be=tt.header.headerTitle,$e=tt.header.headerSubtitle,K=tt.header.closeButton,O=Ce==null?void 0:Ce.layout}else if(Ce&&(ue&&(ue.style.display=Ce.showIcon===!1?"none":""),Be&&(Be.style.display=Ce.showTitle===!1?"none":""),$e&&($e.style.display=Ce.showSubtitle===!1?"none":""),K&&(K.style.display=Ce.showCloseButton===!1?"none":""),je.clearChatButtonWrapper)){let ne=Ce.showClearChat;if(ne!==void 0){je.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Tt}=je;Tt&&!Tt.classList.contains("persona-absolute")&&(ne?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let Ue=((od=r.layout)==null?void 0:od.showHeader)!==!1;De&&(De.style.display=Ue?"":"none");let ct=((sd=r.layout)==null?void 0:sd.showFooter)!==!1;Le&&(Le.style.display=ct?"":"none"),kn(),Vn(),k!==L?k?jt(E,"auto"):(F=!0,Es()):E!==A&&jt(E,"auto"),A=E,L=k,Ms(),Hl();let ke=JSON.stringify(l.toolCall)!==JSON.stringify(p),qe=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((ad=r.layout)==null?void 0:ad.messages)!==JSON.stringify(b),ft=((id=r.loadingIndicator)==null?void 0:id.render)!==(D==null?void 0:D.render)||((ld=r.loadingIndicator)==null?void 0:ld.renderIdle)!==(D==null?void 0:D.renderIdle)||((cd=r.loadingIndicator)==null?void 0:cd.showBubble)!==(D==null?void 0:D.showBubble),W=r.iterationDisplay!==V,Re=((pd=(dd=r.features)==null?void 0:dd.showReasoning)!=null?pd:!0)!==($!=null?$:!0)||((md=(ud=r.features)==null?void 0:ud.showToolCalls)!=null?md:!0)!==(N!=null?N:!0)||JSON.stringify((gd=r.features)==null?void 0:gd.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify((fd=r.features)==null?void 0:fd.reasoningDisplay)!==JSON.stringify(ae);(ke||qe||Ke||ft||W||Re)&&z&&(qo++,Cs(Ye,z.getMessages(),te));let ge=(hd=r.launcher)!=null?hd:{},Ot=(yd=ge.headerIconHidden)!=null?yd:!1,Dt=(vd=(bd=r.layout)==null?void 0:bd.header)==null?void 0:vd.showIcon,Qt=Ot||Dt===!1,ht=ge.headerIconName,Vt=(xd=ge.headerIconSize)!=null?xd:"48px";if(ue){let ne=we.querySelector(".persona-border-b-persona-divider"),Tt=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Qt)ue.style.display="none",ne&&Tt&&!ne.contains(Tt)&&ne.insertBefore(Tt,ne.firstChild);else{if(ue.style.display="",ue.style.height=Vt,ue.style.width=Vt,ne&&Tt&&(ne.contains(ue)?ue.nextSibling!==Tt&&(ue.remove(),ne.insertBefore(ue,Tt)):ne.insertBefore(ue,Tt)),ht){let ot=parseFloat(Vt)||24,Pt=he(ht,ot*.6,"currentColor",1);Pt?ue.replaceChildren(Pt):ue.textContent=(wd=ge.agentIconText)!=null?wd:"\u{1F4AC}"}else if(ge.iconUrl){let ot=ue.querySelector("img");if(ot)ot.src=ge.iconUrl,ot.style.height=Vt,ot.style.width=Vt;else{let Pt=document.createElement("img");Pt.src=ge.iconUrl,Pt.alt="",Pt.className="persona-rounded-xl persona-object-cover",Pt.style.height=Vt,Pt.style.width=Vt,ue.replaceChildren(Pt)}}else{let ot=ue.querySelector("svg"),Pt=ue.querySelector("img");(ot||Pt)&&ue.replaceChildren(),ue.textContent=(Cd=ge.agentIconText)!=null?Cd:"\u{1F4AC}"}let Kt=ue.querySelector("img");Kt&&(Kt.style.height=Vt,Kt.style.width=Vt)}}let Kn=(Sd=(Ad=r.layout)==null?void 0:Ad.header)==null?void 0:Sd.showTitle,nn=(Ed=(Td=r.layout)==null?void 0:Td.header)==null?void 0:Ed.showSubtitle;if(Be&&(Be.style.display=Kn===!1?"none":""),$e&&($e.style.display=nn===!1?"none":""),K){((kd=(Md=r.layout)==null?void 0:Md.header)==null?void 0:kd.showCloseButton)===!1?K.style.display="none":K.style.display="";let Tt=(Ld=ge.closeButtonSize)!=null?Ld:"32px",Kt=(Pd=ge.closeButtonPlacement)!=null?Pd:"inline";K.style.height=Tt,K.style.width=Tt;let{closeButtonWrapper:ot}=je,Pt=Kt==="top-right",cn=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&Pt!==cn)if(ot.remove(),Pt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",we.style.position="relative",we.appendChild(ot);else{let at=(Wd=(Id=ge.clearChat)==null?void 0:Id.placement)!=null?Wd:"inline",dn=(Hd=(Rd=ge.clearChat)==null?void 0:Rd.enabled)!=null?Hd:!0;ot.className=dn&&at==="inline"?"":"persona-ml-auto";let Fn=we.querySelector(".persona-border-b-persona-divider");Fn&&Fn.appendChild(ot)}if(K.style.color=ge.closeButtonColor||Hn.actionIconColor,ge.closeButtonBackgroundColor?(K.style.backgroundColor=ge.closeButtonBackgroundColor,K.classList.remove("hover:persona-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let at=ge.closeButtonBorderWidth||"0px",dn=ge.closeButtonBorderColor||"transparent";K.style.border=`${at} solid ${dn}`,K.classList.remove("persona-border-none")}else K.style.border="",K.classList.add("persona-border-none");ge.closeButtonBorderRadius?(K.style.borderRadius=ge.closeButtonBorderRadius,K.classList.remove("persona-rounded-full")):(K.style.borderRadius="",K.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(K.style.paddingLeft=ge.closeButtonPaddingX,K.style.paddingRight=ge.closeButtonPaddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ge.closeButtonPaddingY?(K.style.paddingTop=ge.closeButtonPaddingY,K.style.paddingBottom=ge.closeButtonPaddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Cn=(Bd=ge.closeButtonIconName)!=null?Bd:"x",gr=(Dd=ge.closeButtonIconText)!=null?Dd:"\xD7";K.innerHTML="";let Rn=he(Cn,"28px","currentColor",1);Rn?K.appendChild(Rn):K.textContent=gr;let en=(Nd=ge.closeButtonTooltipText)!=null?Nd:"Close chat",Xn=(Fd=ge.closeButtonShowTooltip)!=null?Fd:!0;if(K.setAttribute("aria-label",en),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),Xn&&en)){let at=null,dn=()=>{if(at||!K)return;let Lo=K.ownerDocument,Ls=Lo.body;if(!Ls)return;at=Wr(Lo,"div","persona-clear-chat-tooltip"),at.textContent=en;let Ps=Wr(Lo,"div");Ps.className="persona-clear-chat-tooltip-arrow",at.appendChild(Ps);let Po=K.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(fo),at.style.left=`${Po.left+Po.width/2}px`,at.style.top=`${Po.top-8}px`,at.style.transform="translate(-50%, -100%)",Ls.appendChild(at)},Fn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",dn),ot.addEventListener("mouseleave",Fn),K.addEventListener("focus",dn),K.addEventListener("blur",Fn),ot._cleanupTooltip=()=>{Fn(),ot&&(ot.removeEventListener("mouseenter",dn),ot.removeEventListener("mouseleave",Fn)),K&&(K.removeEventListener("focus",dn),K.removeEventListener("blur",Fn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:kt}=je;if(Ge){let ne=(Od=ge.clearChat)!=null?Od:{},Tt=(_d=ne.enabled)!=null?_d:!0,Kt=(Ud=($d=r.layout)==null?void 0:$d.header)==null?void 0:Ud.showClearChat,ot=Kt!==void 0?Kt:Tt,Pt=(zd=ne.placement)!=null?zd:"inline";if(kt){kt.style.display=ot?"":"none";let{closeButtonWrapper:cn}=je;!H()&&cn&&!cn.classList.contains("persona-absolute")&&(ot?cn.classList.remove("persona-ml-auto"):cn.classList.add("persona-ml-auto"));let Cn=Pt==="top-right",gr=kt.classList.contains("persona-absolute");if(!H()&&Cn!==gr&&ot){if(kt.remove(),Cn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",we.style.position="relative",we.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let en=we.querySelector(".persona-border-b-persona-divider"),Xn=je.closeButtonWrapper;en&&Xn&&Xn.parentElement===en?en.insertBefore(kt,Xn):en&&en.appendChild(kt)}let Rn=je.closeButtonWrapper;Rn&&!Rn.classList.contains("persona-absolute")&&(Cn?Rn.classList.add("persona-ml-auto"):Rn.classList.remove("persona-ml-auto"))}}if(ot){if(!H()){let at=(qd=ne.size)!=null?qd:"32px";Ge.style.height=at,Ge.style.width=at}let cn=(jd=ne.iconName)!=null?jd:"refresh-cw",Cn=(Vd=ne.iconColor)!=null?Vd:"";Ge.style.color=Cn||Hn.actionIconColor,Ge.innerHTML="";let gr=H()?"14px":"20px",Rn=he(cn,gr,"currentColor",2);if(Rn&&Ge.appendChild(Rn),ne.backgroundColor?(Ge.style.backgroundColor=ne.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let at=ne.borderWidth||"0px",dn=ne.borderColor||"transparent";Ge.style.border=`${at} solid ${dn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");ne.borderRadius?(Ge.style.borderRadius=ne.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),ne.paddingX?(Ge.style.paddingLeft=ne.paddingX,Ge.style.paddingRight=ne.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),ne.paddingY?(Ge.style.paddingTop=ne.paddingY,Ge.style.paddingBottom=ne.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let en=(Kd=ne.tooltipText)!=null?Kd:"Clear chat",Xn=(Gd=ne.showTooltip)!=null?Gd:!0;if(Ge.setAttribute("aria-label",en),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Xn&&en)){let at=null,dn=()=>{if(at||!Ge)return;let Lo=Ge.ownerDocument,Ls=Lo.body;if(!Ls)return;at=Wr(Lo,"div","persona-clear-chat-tooltip"),at.textContent=en;let Ps=Wr(Lo,"div");Ps.className="persona-clear-chat-tooltip-arrow",at.appendChild(Ps);let Po=Ge.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(fo),at.style.left=`${Po.left+Po.width/2}px`,at.style.top=`${Po.top-8}px`,at.style.transform="translate(-50%, -100%)",Ls.appendChild(at)},Fn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};kt.addEventListener("mouseenter",dn),kt.addEventListener("mouseleave",Fn),Ge.addEventListener("focus",dn),Ge.addEventListener("blur",Fn),kt._cleanupTooltip=()=>{Fn(),kt&&(kt.removeEventListener("mouseenter",dn),kt.removeEventListener("mouseleave",Fn)),Ge&&(Ge.removeEventListener("focus",dn),Ge.removeEventListener("blur",Fn))}}}}let on=r.actionParsers&&r.actionParsers.length?r.actionParsers:[al],or=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[aa.message,aa.messageAndClick];T=il({parsers:on,handlers:or,getSessionMetadata:x,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),te=Jm(r,T,pe),z.updateConfig(r),Cs(Ye,z.getMessages(),te),zo(),vl(),li(z.isStreaming());let Gn=((Qd=r.voiceRecognition)==null?void 0:Qd.enabled)===!0,To=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Eo=((Jd=(Xd=r.voiceRecognition)==null?void 0:Xd.provider)==null?void 0:Jd.type)==="runtype";if(Gn&&(To||Eo))if(!P||!ce){let ne=Sg(r.voiceRecognition,r.sendButton);ne&&(P=ne.micButton,ce=ne.micButtonWrapper,yt.insertBefore(ce,pn),P.addEventListener("click",ga),P.disabled=z.isStreaming())}else{let ne=(Yd=r.voiceRecognition)!=null?Yd:{},Tt=(Zd=r.sendButton)!=null?Zd:{},Kt=(ep=ne.iconName)!=null?ep:"mic",ot=(tp=Tt.size)!=null?tp:"40px",Pt=(np=ne.iconSize)!=null?np:ot,cn=parseFloat(Pt)||24;P.style.width=Pt,P.style.height=Pt,P.style.minWidth=Pt,P.style.minHeight=Pt;let Cn=(op=(rp=ne.iconColor)!=null?rp:Tt.textColor)!=null?op:"currentColor";P.innerHTML="";let gr=he(Kt,cn,Cn,2);gr?P.appendChild(gr):P.textContent="\u{1F3A4}";let Rn=(sp=ne.backgroundColor)!=null?sp:Tt.backgroundColor;Rn?P.style.backgroundColor=Rn:P.style.backgroundColor="",Cn?P.style.color=Cn:P.style.color="var(--persona-text, #111827)",ne.borderWidth?(P.style.borderWidth=ne.borderWidth,P.style.borderStyle="solid"):(P.style.borderWidth="",P.style.borderStyle=""),ne.borderColor?P.style.borderColor=ne.borderColor:P.style.borderColor="",ne.paddingX?(P.style.paddingLeft=ne.paddingX,P.style.paddingRight=ne.paddingX):(P.style.paddingLeft="",P.style.paddingRight=""),ne.paddingY?(P.style.paddingTop=ne.paddingY,P.style.paddingBottom=ne.paddingY):(P.style.paddingTop="",P.style.paddingBottom="");let en=ce==null?void 0:ce.querySelector(".persona-send-button-tooltip"),Xn=(ap=ne.tooltipText)!=null?ap:"Start voice recognition";if(((ip=ne.showTooltip)!=null?ip:!1)&&Xn)if(en)en.textContent=Xn,en.style.display="";else{let dn=document.createElement("div");dn.className="persona-send-button-tooltip",dn.textContent=Xn,ce==null||ce.insertBefore(dn,P)}else en&&(en.style.display="none");ce.style.display="",P.disabled=z.isStreaming()}else P&&ce&&(ce.style.display="none",((cp=(lp=r.voiceRecognition)==null?void 0:lp.provider)==null?void 0:cp.type)==="runtype"?z.isVoiceActive()&&z.toggleVoice():Lr&&oo());if(((dp=r.attachments)==null?void 0:dp.enabled)===!0)if(!Mt||!Me){let ne=(pp=r.attachments)!=null?pp:{},Kt=(mp=((up=r.sendButton)!=null?up:{}).size)!=null?mp:"40px";qt||(qt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),qt.style.display="none",Ft.insertBefore(qt,Te)),Ze||(Ze=document.createElement("input"),Ze.type="file",Ze.accept=((gp=ne.allowedTypes)!=null?gp:jr).join(","),Ze.multiple=((fp=ne.maxFiles)!=null?fp:4)>1,Ze.style.display="none",Ze.setAttribute("aria-label","Attach files"),Ft.insertBefore(Ze,Te)),Mt=y("div","persona-send-button-wrapper"),Me=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Me.type="button",Me.setAttribute("aria-label",(hp=ne.buttonTooltipText)!=null?hp:"Attach file");let ot=(yp=ne.buttonIconName)!=null?yp:"paperclip",Pt=Kt,cn=parseFloat(Pt)||40,Cn=Math.round(cn*.6);Me.style.width=Pt,Me.style.height=Pt,Me.style.minWidth=Pt,Me.style.minHeight=Pt,Me.style.fontSize="18px",Me.style.lineHeight="1",Me.style.backgroundColor="transparent",Me.style.color="var(--persona-primary, #111827)",Me.style.border="none",Me.style.borderRadius="6px",Me.style.transition="background-color 0.15s ease",Me.addEventListener("mouseenter",()=>{Me.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Me.addEventListener("mouseleave",()=>{Me.style.backgroundColor="transparent"});let gr=he(ot,Cn,"currentColor",1.5);gr?Me.appendChild(gr):Me.textContent="\u{1F4CE}",Me.addEventListener("click",Xn=>{Xn.preventDefault(),Ze==null||Ze.click()}),Mt.appendChild(Me);let Rn=(bp=ne.buttonTooltipText)!=null?bp:"Attach file",en=y("div","persona-send-button-tooltip");en.textContent=Rn,Mt.appendChild(en),Wt.append(Mt),!At&&Ze&&qt&&(At=Vs.fromConfig(ne),At.setPreviewsContainer(qt),Ze.addEventListener("change",async()=>{At&&(Ze!=null&&Ze.files)&&(await At.handleFileSelect(Ze.files),Ze.value="")})),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(Ym(ne.dropOverlay))}else{Mt.style.display="";let ne=(vp=r.attachments)!=null?vp:{};Ze&&(Ze.accept=((xp=ne.allowedTypes)!=null?xp:jr).join(","),Ze.multiple=((wp=ne.maxFiles)!=null?wp:4)>1),At&&At.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else Mt&&(Mt.style.display="none"),At&&At.clearAttachments(),(Cp=we.querySelector(".persona-attachment-drop-overlay"))==null||Cp.remove();let Xt=(Ap=r.sendButton)!=null?Ap:{},Mo=(Sp=Xt.useIcon)!=null?Sp:!1,ao=(Tp=Xt.iconText)!=null?Tp:"\u2191",io=Xt.iconName,Ur=(Ep=Xt.tooltipText)!=null?Ep:"Send message",ko=(Mp=Xt.showTooltip)!=null?Mp:!1,mr=(kp=Xt.size)!=null?kp:"40px",Pr=Xt.backgroundColor,Xe=Xt.textColor;if(Mo){if(_e.style.width=mr,_e.style.height=mr,_e.style.minWidth=mr,_e.style.minHeight=mr,_e.style.fontSize="18px",_e.style.lineHeight="1",_e.innerHTML="",Xe?_e.style.color=Xe:_e.style.color="var(--persona-button-primary-fg, #ffffff)",io){let ne=parseFloat(mr)||24,Tt=(Xe==null?void 0:Xe.trim())||"currentColor",Kt=he(io,ne,Tt,2);Kt?_e.appendChild(Kt):_e.textContent=ao}else _e.textContent=ao;_e.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pr?(_e.style.backgroundColor=Pr,_e.classList.remove("persona-bg-persona-primary")):(_e.style.backgroundColor="",_e.classList.add("persona-bg-persona-primary"))}else _e.textContent=(Pp=(Lp=r.copy)==null?void 0:Lp.sendButtonLabel)!=null?Pp:"Send",_e.style.width="",_e.style.height="",_e.style.minWidth="",_e.style.minHeight="",_e.style.fontSize="",_e.style.lineHeight="",_e.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",Pr?(_e.style.backgroundColor=Pr,_e.classList.remove("persona-bg-persona-accent")):_e.classList.add("persona-bg-persona-accent"),Xe?_e.style.color=Xe:_e.classList.add("persona-text-white");Xt.borderWidth?(_e.style.borderWidth=Xt.borderWidth,_e.style.borderStyle="solid"):(_e.style.borderWidth="",_e.style.borderStyle=""),Xt.borderColor?_e.style.borderColor=Xt.borderColor:_e.style.borderColor="",Xt.paddingX?(_e.style.paddingLeft=Xt.paddingX,_e.style.paddingRight=Xt.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),Xt.paddingY?(_e.style.paddingTop=Xt.paddingY,_e.style.paddingBottom=Xt.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let _t=pn==null?void 0:pn.querySelector(".persona-send-button-tooltip");if(ko&&Ur)if(_t)_t.textContent=Ur,_t.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Ur,pn==null||pn.insertBefore(ne,_e)}else _t&&(_t.style.display="none");let Gt=(Bp=(Ip=r.layout)==null?void 0:Ip.contentMaxWidth)!=null?Bp:H()?(Hp=(Rp=(Wp=r.launcher)==null?void 0:Wp.composerBar)==null?void 0:Rp.contentMaxWidth)!=null?Hp:"720px":void 0;Gt?(Ye.style.maxWidth=Gt,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%",Ft&&(Ft.style.maxWidth=Gt,Ft.style.marginLeft="auto",Ft.style.marginRight="auto"),Qe&&(Qe.style.maxWidth=Gt,Qe.style.marginLeft="auto",Qe.style.marginRight="auto")):(Ye.style.maxWidth="",Ye.style.marginLeft="",Ye.style.marginRight="",Ye.style.width="",Ft&&(Ft.style.maxWidth="",Ft.style.marginLeft="",Ft.style.marginRight=""),Qe&&(Qe.style.maxWidth="",Qe.style.marginLeft="",Qe.style.marginRight=""));let $t=(Dp=r.statusIndicator)!=null?Dp:{},Jt=(Np=$t.visible)!=null?Np:!0;if(Yt.style.display=Jt?"":"none",z){let ne=z.getStatus();dt(Yt,(Kt=>{var ot,Pt,cn,Cn;return Kt==="idle"?(ot=$t.idleText)!=null?ot:An.idle:Kt==="connecting"?(Pt=$t.connectingText)!=null?Pt:An.connecting:Kt==="connected"?(cn=$t.connectedText)!=null?cn:An.connected:Kt==="error"?(Cn=$t.errorText)!=null?Cn:An.error:An[Kt]})(ne),$t,ne)}Yt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Lt=$t.align==="left"?"persona-text-left":$t.align==="center"?"persona-text-center":"persona-text-right";Yt.classList.add(Lt)},open(){U()&&jt(!0,"api")},close(){U()&&jt(!1,"api")},toggle(){U()&&jt(!F,"api")},clearChat(){Ln=!1,z.clearMessages(),Tr.clear(),mn();try{localStorage.removeItem(bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${bs}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let p=c.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}u={},T.syncFromMetadata(),G==null||G.clear(),X==null||X.reset(),ve==null||ve.update()},setMessage(l){return!Te||z.isStreaming()?!1:(!F&&U()&&jt(!0,"system"),Te.value=l,Te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(z.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Te.value.trim();return p?(!F&&U()&&jt(!0,"system"),Te.value="",Te.style.height="auto",z.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return z.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(z.isVoiceActive()||(!F&&U()&&jt(!0,"system"),pt.manuallyDeactivated=!1,Nn(),z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),tr("user"),z.isVoiceActive()&&Yo()})),!0):Lr?!0:El()?(!F&&U()&&jt(!0,"system"),pt.manuallyDeactivated=!1,Nn(),ua("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Nn(),tr("user"),$r()}),!0):!1:Lr?(pt.manuallyDeactivated=!0,Nn(),oo("user"),!0):!1},injectMessage(l){return!F&&U()&&jt(!0,"system"),z.injectMessage(l)},injectAssistantMessage(l){!F&&U()&&jt(!0,"system");let p=z.injectAssistantMessage(l);return ee&&(ee=!1,Ae&&(clearTimeout(Ae),Ae=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),p},injectUserMessage(l){return!F&&U()&&jt(!0,"system"),z.injectUserMessage(l)},injectSystemMessage(l){return!F&&U()&&jt(!0,"system"),z.injectSystemMessage(l)},injectMessageBatch(l){return!F&&U()&&jt(!0,"system"),z.injectMessageBatch(l)},injectComponentDirective(l){return!F&&U()&&jt(!0,"system"),z.injectComponentDirective(l)},injectTestMessage(l){!F&&U()&&jt(!0,"system"),z.injectTestEvent(l)},async connectStream(l,p){return z.connectStream(l,p)},__pushEventStreamEvent(l){G&&(X==null||X.processEvent(l.type,l.payload),G.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!le||!G||Hr()},hideEventStream(){Y&&cr()},isEventStreamVisible(){return Y},showArtifacts(){ir(r)&&(Ln=!1,Dn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(Ln=!0,Dn())},upsertArtifact(l){return ir(r)?(Ln=!1,z.upsertArtifact(l)):null},selectArtifact(l){ir(r)&&z.selectArtifact(l)},clearArtifacts(){ir(r)&&z.clearArtifacts()},getArtifacts(){var l;return(l=z==null?void 0:z.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=z==null?void 0:z.getSelectedArtifactId())!=null?l:null},focusInput(){return k&&!F&&!H()||!Te?!1:(Te.focus(),!0)},async resolveApproval(l,p,h){let S=z.getMessages().find(D=>{var V;return D.variant==="approval"&&((V=D.approval)==null?void 0:V.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){z.resolveWebMcpApproval(S.id,p);return}return z.resolveApproval(S.approval,p,h)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){v(l)},on(l,p){return i.on(l,p)},off(l,p){i.off(l,p)},isOpen(){return U()&&F},isVoiceActive(){return pt.active},toggleReadAloud(l){z.toggleReadAloud(l)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(l){return z.getReadAloudState(l)},onReadAloudChange(l){return z.onReadAloudChange(l)},getState(){return{open:U()&&F,launcherEnabled:k,voiceActive:pt.active,streaming:z.isStreaming()}},showCSATFeedback(l){!F&&U()&&jt(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=Gm({onSubmit:async(b,S)=>{var D;z.isClientTokenMode()&&await z.submitCSATFeedback(b,S),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!F&&U()&&jt(!0,"system");let p=Ye.querySelector(".persona-feedback-container");p&&p.remove();let h=Qm({onSubmit:async(b,S)=>{var D;z.isClientTokenMode()&&await z.submitNPSFeedback(b,S),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ye.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return z.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return z.submitNPSFeedback(l,p)},destroy(){So!=null&&(clearInterval(So),So=null),mt.forEach(l=>l()),He.remove(),Ve==null||Ve.remove(),tn==null||tn.destroy(),ln==null||ln.remove(),Ar&&K.removeEventListener("click",Ar)}};if((((Rc=n==null?void 0:n.debugTools)!=null?Rc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:rn,getMessages:rn.getMessages,getStatus:rn.getStatus,getMetadata:rn.getPersistentMetadata,updateMetadata:rn.updatePersistentMetadata,clearHistory:()=>rn.clearChat(),setVoiceActive:h=>h?rn.startVoiceRecognition():rn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,mt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),p=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&rn.focusInput()};if(window.addEventListener("persona:focusInput",p),mt.push(()=>{window.removeEventListener("persona:focusInput",p)}),le){let $=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&rn.showEventStream()},N=se=>{let ae=se.detail;(!(ae!=null&&ae.instanceId)||ae.instanceId===l)&&rn.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",N),mt.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",N)})}let h=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&rn.showArtifacts()},b=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&rn.hideArtifacts()},S=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&rn.upsertArtifact(N.artifact)},D=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&rn.selectArtifact(N.id)},V=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&rn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",V),mt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",V)})}let rr=By(r.persistState);if(rr&&U()){let l=Dy(rr.storage),p=`${rr.keyPrefix}widget-open`,h=`${rr.keyPrefix}widget-voice`,b=`${rr.keyPrefix}widget-voice-mode`;if(l){let S=((Hc=rr.persist)==null?void 0:Hc.openState)&&l.getItem(p)==="true",D=((Bc=rr.persist)==null?void 0:Bc.voiceState)&&l.getItem(h)==="true",V=((Dc=rr.persist)==null?void 0:Dc.voiceState)&&l.getItem(b)==="true";if(S&&setTimeout(()=>{rn.open(),setTimeout(()=>{var $;if(D||V)rn.startVoiceRecognition();else if(($=rr.persist)!=null&&$.focusInput){let N=t.querySelector("textarea");N&&N.focus()}},100)},0),(Nc=rr.persist)!=null&&Nc.openState&&(i.on("widget:opened",()=>{l.setItem(p,"true")}),i.on("widget:closed",()=>{l.setItem(p,"false")})),(Fc=rr.persist)!=null&&Fc.voiceState&&(i.on("voice:state",$=>{l.setItem(h,$.active?"true":"false")}),i.on("user:message",$=>{l.setItem(b,$.viaVoice?"true":"false")})),rr.clearOnChatClear){let $=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(b)},N=()=>$();window.addEventListener("persona:clear-chat",N),mt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return g&&U()&&setTimeout(()=>{rn.open()},0),Xo(),la||jp().then(()=>{z&&(qo++,Tr.clear(),Cs(Ye,z.getMessages(),te))}).catch(()=>{}),rn};var Ny=(t,e)=>{let n=t.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,e*parseFloat(o[1])/100):420},Fy=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Oy=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},_y=(t,e)=>{let n=t.parentElement;if(!n)return;let r=t.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(e.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 ${e.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.")},eg=(t,e)=>{var r,o;let n=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},ml=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},tg=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",ml(t)},dl=t=>{t.style.transition=""},pl=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},ul=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},ii=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},$y=(t,e,n,r,o)=>{o?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,r),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(r))},Uy=(t,e,n,r,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},ng=(t,e,n,r,o,s,a)=>{var x,v,M,R,T,k;let i=hr(s),d=i.reveal==="push";$y(t,e,n,r,d),Uy(t,e,n,r,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=t.ownerDocument.defaultView,u=(v=(x=s==null?void 0:s.launcher)==null?void 0:x.mobileFullscreen)!=null?v:!0,f=(R=(M=s==null?void 0:s.launcher)==null?void 0:M.mobileBreakpoint)!=null?R:640,g=c!=null?c.innerWidth<=f:!1;if(u&&g&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),pl(e),dl(r),tg(r),ul(n),ii(o,r),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?k:Sn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),tg(r),Fy(r,i.maxHeight),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",pl(e),dl(r),ul(n),ii(o,r);let E=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=A,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",dl(r),ml(r),ii(o,r);let E=Ny(i.width,t.clientWidth),I=Math.max(0,t.clientWidth),A=i.animate?"margin-left 180ms ease":"none",L=i.side==="right"?a?-E:0:a?0:-E;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${I+E}px`,e.style.transition=A,e.style.marginLeft=`${L}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",pl(e),ml(r),ul(n),ii(o,r);let E=i.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",L=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",Oy(r,i.maxHeight),r.style.overflow=E||L?"hidden":"visible",r.style.transition=A,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},zy=(t,e)=>{let n=t.ownerDocument.createElement("div");return eg(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){eg(n,r)},destroy(){n.remove()}}},qy=(t,e)=>{var k,E,I,A;let{ownerDocument:n}=t,r=t.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=t.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),u=n.createElement("div"),f=(E=(k=e==null?void 0:e.launcher)==null?void 0:k.enabled)==null||E?(A=(I=e==null?void 0:e.launcher)==null?void 0:I.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,t),d.appendChild(t);let g=null,m=()=>{g==null||g.disconnect(),g=null},x=()=>{m(),hr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{ng(a,i,d,c,u,e,f)}),g.observe(a))},v=!1,M=()=>{ng(a,i,d,c,u,e,f),x(),f&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,_y(a,hr(e)))},R=a.ownerDocument.defaultView,T=()=>{M()};return R==null||R.addEventListener("resize",T),hr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:u,shell:a,syncWidgetState(L){let O=L.launcherEnabled?L.open:!0;f!==O&&(f=O,M())},updateConfig(L){var O,_;e=L,((_=(O=e==null?void 0:e.launcher)==null?void 0:O.enabled)!=null?_:!0)===!1&&(f=!0),M()},destroy(){R==null||R.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(t,s):r.appendChild(t)),a.remove()}}},rg=(t,e)=>bn(e)?qy(t,e):zy(t,e);var ia={desktop:{w:1280,h:800},mobile:{w:390,h:844}},og=.15,sg=1.5,gl="persona-preview-shell-theme",jy={load:()=>null,save:()=>{},clear:()=>{}},Vy=["How do I get started?","Pricing & plans","Talk to support"];function fl(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Ky(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function ag(t){let e=Ky(t);return`* { box-sizing: border-box; }
|
|
110
112
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
111
|
-
html { color-scheme: ${
|
|
113
|
+
html { color-scheme: ${t}; }
|
|
112
114
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
113
115
|
.preview-iframe-mock { min-height: 100%; }
|
|
114
116
|
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
|
|
@@ -130,7 +132,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
130
132
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
131
133
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
132
134
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
133
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
135
|
+
.preview-workspace-card.short { height: 96px; }`}function ig(t,e){let n=t.contentDocument;if(!(n!=null&&n.documentElement))return;let r=n.getElementById(gl);r||(r=n.createElement("style"),r.id=gl,n.head.appendChild(r)),r.textContent=ag(e)}var Gy=`
|
|
134
136
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
135
137
|
<div class="preview-iframe-chrome">
|
|
136
138
|
<span class="preview-iframe-dot"></span>
|
|
@@ -149,7 +151,7 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
149
151
|
<div class="preview-iframe-line body"></div>
|
|
150
152
|
<div class="preview-iframe-line body"></div>
|
|
151
153
|
</div>
|
|
152
|
-
</div>`,
|
|
154
|
+
</div>`,Qy=`
|
|
153
155
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
154
156
|
<div class="preview-iframe-line hero"></div>
|
|
155
157
|
<div class="preview-iframe-line body"></div>
|
|
@@ -162,9 +164,9 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
162
164
|
<div class="preview-workspace-card short"></div>
|
|
163
165
|
<div class="preview-workspace-card short"></div>
|
|
164
166
|
</div>
|
|
165
|
-
</div>`;function
|
|
166
|
-
${
|
|
167
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${
|
|
167
|
+
</div>`;function lg(t,e,n,r){let o=`
|
|
168
|
+
${Gy}
|
|
169
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
168
170
|
<div class="preview-workspace-shell">
|
|
169
171
|
<div class="preview-workspace-topbar">
|
|
170
172
|
<div class="preview-workspace-topbar-left">
|
|
@@ -174,8 +176,8 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
174
176
|
<span class="preview-workspace-topbar-pill"></span>
|
|
175
177
|
</div>
|
|
176
178
|
<div class="preview-workspace-body">
|
|
177
|
-
<div id="preview-content-${
|
|
178
|
-
${
|
|
179
|
+
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
180
|
+
${Qy}
|
|
179
181
|
</div>
|
|
180
182
|
</div>
|
|
181
183
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -183,16 +185,16 @@ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]
|
|
|
183
185
|
<head>
|
|
184
186
|
<meta charset="UTF-8">
|
|
185
187
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
186
|
-
<link rel="stylesheet" href="${
|
|
187
|
-
<style id="${
|
|
188
|
+
<link rel="stylesheet" href="${fl(r)}">
|
|
189
|
+
<style id="${gl}">${ag(e)}</style>
|
|
188
190
|
</head>
|
|
189
191
|
<body>
|
|
190
|
-
${
|
|
192
|
+
${n?s:o}
|
|
191
193
|
</body>
|
|
192
|
-
</html>`}var
|
|
193
|
-
${
|
|
194
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
195
|
-
</div>`,
|
|
194
|
+
</html>`}var Xy=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Jy=t=>{var e,n,r,o,s,a,i,d;return!!((n=(e=t==null?void 0:t.features)==null?void 0:e.toolCallDisplay)!=null&&n.activePreview||(o=(r=t==null?void 0:t.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=t==null?void 0:t.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=t==null?void 0:t.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Yy(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Jy(e)?[...Xy(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Zy(t,e,n=[]){var s,a;let r={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...t,launcher:r,suggestionChips:e==="home"?(s=t.suggestionChips)!=null&&s.length?t.suggestionChips:Vy:t.suggestionChips,initialMessages:Yy(e,t,n),storageAdapter:jy};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function eb(t,e){var r,o;let n=t.theme?Bo(t.theme,{validate:!1}):Bo();return{...Nt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:(o=e!=null?e:(r=t.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function vs(t,e){var r,o;let n=(r=t.scene)!=null?r:"conversation";return Zy(eb(t,e),n,(o=t.appendedMessages)!=null?o:[])}function cg(t){var r,o,s,a,i;let e=(r=t.compareMode)!=null?r:"off",n=(o=t.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:vs(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:vs(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let d={...t,config:(s=t.baselineConfig)!=null?s:t.config,theme:(a=t.baselineTheme)!=null?a:t.theme,darkTheme:(i=t.baselineDarkTheme)!=null?i:t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:vs(d,n),shellMode:n},{mountId:"preview-current",label:"Current",config:vs(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:vs(t,n),shellMode:n}]}function dg(t,e){let n={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function u(){var T;return(T=n.device)!=null?T:"desktop"}function f(){var T;return(T=n.zoom)!=null?T:i}function g(){var H,U;let T=getComputedStyle(t),k=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),E=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),I=40,A=((H=n.compareMode)!=null?H:"off")!=="off",L=(t.clientWidth-k-I)/(A?2:1),O=t.clientHeight-E-I;if(L<=0||O<=0)return 1;let _=(U=ia[u()])!=null?U:ia.desktop;return Math.min(L/_.w,O/_.h,1)}function m(){var E,I,A;i=g();let T=Math.max(og,Math.min(sg,f()));d=T;let k=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let L of k){let O=(E=L.dataset.device)!=null?E:"desktop",_=(I=ia[O])!=null?I:ia.desktop;L.style.width=`${_.w*T}px`,L.style.height=`${_.h*T}px`,O==="mobile"&&(L.style.borderRadius=`${32*T}px`);let H=L.querySelector("iframe");H&&(H.style.width=`${_.w}px`,H.style.height=`${_.h}px`,H.style.transformOrigin="top left",H.style.transition="none",H.style.transform=`scale(${T})`)}(A=n.onScaleChange)==null||A.call(n,T)}function x(){var T;(T=n.onBeforeDestroy)==null||T.call(n);for(let k of r)k.destroy();for(let k of o)k();r=[],o=[]}function v(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){var te,xe,We,le;if(a)return;x();let T=++c,k=cg(n),E=u(),I=((te=n.compareMode)!=null?te:"off")!=="off",A=((xe=n.scene)!=null?xe:"conversation")==="minimized",L=(We=n.widgetCssPath)!=null?We:"/widget-dist/widget.css",O=(le=n.buildSrcdoc)!=null?le:lg,_=E==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",H=me=>`<div class="${_}" data-mount-id="${me.mountId}" data-device="${E}" data-shell-mode="${me.shellMode}">
|
|
195
|
+
${I?`<div class="preview-frame-meta"><span class="preview-frame-label">${fl(me.label)}</span></div>`:""}
|
|
196
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${me.mountId}"></iframe>
|
|
197
|
+
</div>`,U=I?`<div class="preview-compare-grid">${k.map(me=>`<div class="preview-compare-cell">${H(me)}</div>`).join("")}</div>`:`<div class="preview-single">${H(k[0])}</div>`;n.morphContainer?n.morphContainer(t,U):t.innerHTML=U,m();let F=v(),ee=0,Ae=F.length,pe=()=>{var re,oe,de,ze,Fe;if(a||T!==c)return;for(let G of F){let X=G.dataset.mountId;if(!X||!G.contentDocument)continue;let ve=k.find(nt=>nt.mountId===X);if(!ve)continue;let Y=()=>{},ie=bn(ve.config),Ee=ie?(()=>{var Q;let nt=(Q=G.contentDocument)==null?void 0:Q.getElementById(`preview-content-${X}`);if(!nt)return null;let wt=rg(nt,ve.config),dt=G.contentDocument.createElement("div");dt.id=X,dt.style.height="100%",dt.style.display="flex",dt.style.flexDirection="column",dt.style.flex="1",dt.style.minHeight="0",wt.host.appendChild(dt);let tt=()=>wt.syncWidgetState(Je.getState()),He=Y;return Y=()=>{wt.destroy(),He()},dt.__syncDock=tt,dt.__hostLayout=wt,dt})():G.contentDocument.getElementById(X);if(!Ee)continue;let Je=Zm(Ee,ve.config);if(r.push(Je),ie&&Ee.__syncDock){let nt=Ee.__syncDock,wt=Je.on("widget:opened",nt),dt=Je.on("widget:closed",nt),tt=Y;Y=()=>{wt(),dt(),tt()},nt()}o.push(Y),A&&Je.close()}if(((re=n.scene)!=null?re:"conversation")==="artifact"||(ze=(de=(oe=n.config)==null?void 0:oe.features)==null?void 0:de.artifacts)!=null&&ze.enabled)for(let G of r)G.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
196
198
|
|
|
197
199
|
This is a preview of the artifact sidebar.
|
|
198
200
|
|
|
@@ -200,4 +202,4 @@ This is a preview of the artifact sidebar.
|
|
|
200
202
|
|
|
201
203
|
- Markdown rendering
|
|
202
204
|
- Document toolbar
|
|
203
|
-
- Resizable panes`});(
|
|
205
|
+
- Resizable panes`});(Fe=n.onAfterMount)==null||Fe.call(n,{iframes:F,controllers:[...r]})};for(let me of F){let re=me.dataset.mountId;if(!re)continue;let oe=k.find(de=>de.mountId===re);oe&&(me.addEventListener("load",()=>{ee++,ee>=Ae&&pe()},{once:!0}),me.srcdoc=O(re,oe.shellMode,bn(oe.config),L))}Ae===0&&pe()}function R(){var E;if(a)return;let T=cg(n);if(r.length!==T.length){M();return}if(T.some(I=>{let A=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${I.mountId}"]`);return!A||A.dataset.shellMode!==I.shellMode})){M();return}r.forEach((I,A)=>{var L;I.update(T[A].config),((L=n.scene)!=null?L:"conversation")==="minimized"&&I.close()});for(let I of T){let A=t.querySelector(`iframe[data-mount-id="${I.mountId}"]`);A&&ig(A,I.shellMode)}(E=n.onAfterUpdate)==null||E.call(n,{iframes:v(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(t)),M(),{update(T){if(a)return;let k=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},k?M():R()},destroy(){a||(a=!0,x(),s==null||s.disconnect(),t.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return v()},getScale(){return d},setZoom(T){a||(n={...n,zoom:T},m())}}}0&&(module.exports={createThemePreview});
|