@runtypelabs/persona 3.37.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +4 -5
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-DgYsuwXL.d.cts → types-B_xbfvR0.d.cts} +263 -181
  5. package/dist/animations/{types-DgYsuwXL.d.ts → types-B_xbfvR0.d.ts} +263 -181
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/codegen.cjs +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/index.cjs +54 -52
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +328 -839
  13. package/dist/index.d.ts +328 -839
  14. package/dist/index.global.js +41 -39
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +54 -52
  17. package/dist/index.js.map +1 -1
  18. package/dist/install.global.js +1 -1
  19. package/dist/install.global.js.map +1 -1
  20. package/dist/smart-dom-reader.d.cts +269 -192
  21. package/dist/smart-dom-reader.d.ts +269 -192
  22. package/dist/theme-editor-preview.cjs +55 -53
  23. package/dist/theme-editor-preview.d.cts +269 -192
  24. package/dist/theme-editor-preview.d.ts +269 -192
  25. package/dist/theme-editor-preview.js +57 -55
  26. package/dist/theme-editor.d.cts +269 -192
  27. package/dist/theme-editor.d.ts +269 -192
  28. package/dist/widget.css +14 -0
  29. package/package.json +1 -1
  30. package/src/client.test.ts +446 -1041
  31. package/src/client.ts +684 -967
  32. package/src/components/message-bubble.ts +7 -0
  33. package/src/components/tool-bubble.ts +46 -33
  34. package/src/generated/runtype-openapi-contract.ts +210 -714
  35. package/src/index-core.ts +2 -3
  36. package/src/install.test.ts +1 -34
  37. package/src/install.ts +1 -26
  38. package/src/runtime/init.test.ts +8 -67
  39. package/src/runtime/init.ts +2 -17
  40. package/src/session.test.ts +8 -8
  41. package/src/session.ts +1 -1
  42. package/src/styles/widget.css +14 -0
  43. package/src/types.ts +12 -13
  44. package/src/ui.postprocess.test.ts +107 -0
  45. package/src/ui.ts +45 -5
  46. package/src/utils/__fixtures__/unified-translator.oracle.ts +62 -14
  47. package/src/utils/copy-selection.test.ts +37 -0
  48. package/src/utils/copy-selection.ts +19 -0
  49. package/src/utils/event-stream-capture.test.ts +9 -64
  50. package/src/utils/streaming-table.test.ts +100 -0
  51. package/src/utils/streaming-table.ts +103 -0
  52. package/src/utils/sequence-buffer.test.ts +0 -256
  53. package/src/utils/sequence-buffer.ts +0 -130
  54. package/src/utils/unified-event-bridge.test.ts +0 -263
  55. package/src/utils/unified-event-bridge.ts +0 -431
@@ -1,20 +1,22 @@
1
- "use strict";var vg=Object.create;var _a=Object.defineProperty;var xg=Object.getOwnPropertyDescriptor;var wg=Object.getOwnPropertyNames;var Cg=Object.getPrototypeOf,Ag=Object.prototype.hasOwnProperty;var zs=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ni=(n,t)=>{for(var e in t)_a(n,e,{get:t[e],enumerable:!0})},Kp=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of wg(t))!Ag.call(n,o)&&o!==e&&_a(n,o,{get:()=>t[o],enumerable:!(r=xg(t,o))||r.enumerable});return n};var Gp=(n,t,e)=>(e=n!=null?vg(Cg(n)):{},Kp(t||!n||!n.__esModule?_a(e,"default",{value:n,enumerable:!0}):e,n)),Sg=n=>Kp(_a({},"__esModule",{value:!0}),n);var Jp={};Ni(Jp,{DOMPurify:()=>Xp.default,Marked:()=>Qp.Marked});var Qp,Xp,Yp=zs(()=>{"use strict";Qp=require("marked"),Xp=Gp(require("dompurify"),1)});var fs,el=zs(()=>{"use strict";fs=class{constructor(t=24e3,e={}){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=t;let r=Math.max(0,(o=e.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let e=typeof window!="undefined"?window:void 0;if(!e)throw new Error("AudioPlaybackManager requires a browser environment");let r=e.AudioContext||e.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let e=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),e=o,this.remainder=null}if(e.length%2!==0&&(this.remainder=new Uint8Array([e[e.length-1]]),e=e.subarray(0,e.length-1)),e.length===0)return;let r=this.pcmToFloat32(e);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let e of t)this.scheduleSamples(e)}scheduleSamples(t){if(t.length===0)return;let e=this.ensureContext(),r=e.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=e.createBufferSource();o.buffer=r,o.connect(e.destination);let s=e.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 t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let e of t)e()}}pcmToFloat32(t){let e=Math.floor(t.length/2),r=new Float32Array(e),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<e;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Mf(n){return n.replace(/\/+$/,"")}async function kf(n){var t,e;try{let r=await n.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${n.status}`}: ${r.detail}`:(e=r.error)!=null?e:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var ri,Fu=zs(()=>{"use strict";el();ri=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,e;return(e=this.playerPromise)!=null?e:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new fs(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,e){let r=++this.generation;this.run(r,t,e)}async run(t,e,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var u;t===this.generation&&((u=r.onStart)==null||u.call(r))}),d.onFinished(()=>{var u;t===this.generation&&((u=r.onEnd)==null||u.call(r))});let c=`${Mf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,g=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:e.text,voice:(o=e.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!g.ok||!g.body)throw new Error(await kf(g));let f=g.body.getReader();for(;;){let{done:u,value:m}=await f.read();if(t!==this.generation){await f.cancel().catch(()=>{});return}if(u)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(t!==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 t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var oi,_u=zs(()=>{"use strict";oi=class{constructor(t,e,r={}){this.primary=t;this.fallback=e;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,e){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=e.onStart)==null||o.call(e)},onEnd:()=>{var o;return(o=e.onEnd)==null?void 0:o.call(e)},onError:o=>{var s,a,i;if(r){(s=e.onError)==null||s.call(e,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,e)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,e,r,o;(e=(t=this.primary).destroy)==null||e.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Ou={};Ni(Ou,{FallbackSpeechEngine:()=>oi,RuntypeSpeechEngine:()=>ri});var $u=zs(()=>{"use strict";Fu();_u()});var Hb={};Ni(Hb,{createThemePreview:()=>ug});module.exports=Sg(Hb);var Zp=null,js=null,is=null;var eu=()=>js?Promise.resolve(js):is||(Zp?(is=Zp().then(n=>(js=n,n)),is):(is=Promise.resolve().then(()=>(Yp(),Jp)).then(n=>(js=n,n)),is)),ls=()=>js;var Tg=n=>{if(n)return n},Fi=n=>{let t=null;return e=>{var o,s;let r=ls();if(!r)return ho(e);if(!t){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;t=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=Tg(n==null?void 0:n.renderer);d&&t.use({renderer:d})}return t.parse(e)}},Oa=n=>n?Fi({markedOptions:n.options,renderer:n.renderer}):Fi(),$b=Fi();var ho=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Eg={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"]},Mg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,kg=()=>{let n=null;return t=>{let e=ls();if(!e)return ho(t);if(!n){let{DOMPurify:r}=e;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:")&&!Mg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(t,Eg)}},$a=n=>n===!1?null:typeof n=="function"?n:kg();var No="webmcp:",_i=new Map,tu=n=>{var t;_i.clear();for(let e of n){let r=(t=e.title)==null?void 0:t.trim();r&&_i.set(e.name,r)}},Oi=n=>_i.get(su(n)),qa={warn(n,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...t)}},nu=null;function ou(n){if(n.length===0)return"0:empty";let t=n.map(e=>{var r,o;return[e.name,(r=e.description)!=null?r:"",e.parametersSchema?JSON.stringify(e.parametersSchema):"",(o=e.origin)!=null?o:"",e.annotations?JSON.stringify(e.annotations):""].join("")}).sort();return`${n.length}:${Lg(t.join(""))}`}function ru(n,t){let e=3735928559^t,r=1103547991^t;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);e=Math.imul(e^s,2654435761),r=Math.imul(r^s,1597334677)}return e=Math.imul(e^e>>>16,2246822507),e^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(e^e>>>13,3266489909),4294967296*(2097151&r)+(e>>>0)}function Lg(n){let t=ru(n,0).toString(36),e=ru(n,2654435761).toString(36);return`${t}.${e}`}var Ua=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var e;this.confirmHandler=(e=t.onConfirm)!=null?e:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let e;try{e=await t.getTools()}catch(o){return qa.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}tu(e);let r=typeof location!="undefined"?location.origin:"";return e.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Pg(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,e,r){if(await this.ensureReady(),this.config.enabled!==!0)return yr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return yr(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=su(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return yr(`Failed to read WebMCP registry: ${x}`)}tu(a);let i=a.find(v=>v.name===s);if(!i)return yr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return yr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let d=Oi(s),c={toolName:s,args:e,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return yr("User declined the tool call.");if(r!=null&&r.aborted)return yr("Aborted by cancel()");let g=new AbortController,f=!1,u=setTimeout(()=>{f=!0,g.abort()},this.timeoutMs),m=()=>g.abort();r&&(r.aborted?g.abort():r.addEventListener("abort",m,{once:!0}));try{let v=await o.executeTool(i,Hg(e),{signal:g.signal});return Wg(v)}catch(v){if(f)return yr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return yr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return yr(x)}finally{clearTimeout(u),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}(nu?await nu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){qa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let e=t;return typeof e.getTools!="function"||typeof e.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,qa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let e=(r=this.confirmHandler)!=null?r:Rg;try{return await e(t)}catch(o){return qa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let e=this.config.allowlist;return!e||e.length===0?!0:e.some(r=>Ig(t,r))}},su=n=>n.startsWith(No)?n.slice(No.length):n,Vs=n=>n.startsWith(No),Ig=(n,t)=>{if(t==="*")return!0;let e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n)},Pg=n=>{if(!(n===void 0||n===""))try{let t=JSON.parse(n);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Wg=n=>{if(n==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Dg(t)}]}},yr=n=>({isError:!0,content:[{type:"text",text:n}]}),Rg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Bg(n.args),e=`Allow the AI to call ${n.toolName}`+(t?`
1
+ "use strict";var wg=Object.create;var ma=Object.defineProperty;var Cg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var Sg=Object.getPrototypeOf,Tg=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 Ag(e))!Tg.call(n,o)&&o!==t&&ma(n,o,{get:()=>e[o],enumerable:!(r=Cg(e,o))||r.enumerable});return n};var Dp=(n,e,t)=>(t=n!=null?wg(Sg(n)):{},Bp(e||!n||!n.__esModule?ma(t,"default",{value:n,enumerable:!0}):t,n)),Mg=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 Wf(n){return n.replace(/\/+$/,"")}async function Rf(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,ku=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=`${Wf(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 Rf(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,Lu=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 Pu={};gi(Pu,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var Iu=Es(()=>{"use strict";ku();Lu()});var _y={};gi(_y,{createThemePreview:()=>rg});module.exports=Mg(_y);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 Eg=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=Eg(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(),Vy=fi();var so=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var kg={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"]},Lg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Pg=()=>{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:")&&!Lg.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,kg)}},fa=n=>n===!1?null:typeof n=="function"?n:Pg();var qp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zp=n=>n.includes("|"),jp=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},Ig=n=>`| ${n.join(" | ")} |`,Wg=n=>`| ${Array.from({length:n},()=>"---").join(" | ")} |`,Rg=(n,e)=>n.length>=e?n.slice(0,e):n.concat(Array.from({length:e-n.length},()=>"")),Vp=n=>{if(!n||!n.includes("|"))return n;let e=n.split(`
2
+ `),t=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!zp(o)||qp.test(o)||!qp.test(s))continue;let a=jp(o).length;if(a<1)continue;let i=Wg(a);e[r+1]!==i&&(e[r+1]=i,t=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!zp(c))break;let m=Ig(Rg(jp(c),a));e[d]!==m&&(e[d]=m,t=!0)}r=d-1}return t?e.join(`
3
+ `):n};var ko="webmcp:",hi=new Map,Kp=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(Jp(n)),ha={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Gp=null;function Xp(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}:${Hg(e.join(""))}`}function Qp(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 Hg(n){let e=Qp(n,0).toString(36),t=Qp(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),[]}Kp(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=Dg(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=Jp(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}`)}Kp(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,_g(t),{signal:m.signal});return Ng(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}(Gp?await Gp():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:Fg;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=>Bg(e,r))}},Jp=n=>n.startsWith(ko)?n.slice(ko.length):n,Jo=n=>n.startsWith(ko),Bg=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Dg=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Ng=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:$g(e)}]}},mr=n=>({isError:!0,content:[{type:"text",text:n}]}),Fg=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Og(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
2
4
 
3
5
  Arguments:
4
- ${t}`:"")+(n.description?`
6
+ ${e}`:"")+(n.description?`
5
7
 
6
- ${n.description}`:"");return window.confirm(e)},Bg=n=>{if(n==null)return"";try{let t=JSON.stringify(n,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(n)}},Hg=n=>{if(n===void 0)return"{}";try{let t=JSON.stringify(n);return t===void 0?"{}":t}catch{return"{}"}},Dg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var bo=require("partial-json");var y=(n,t)=>{let e=document.createElement(n);return t&&(e.className=t),e},Dr=(n,t,e)=>{let r=n.createElement(t);return e&&(r.className=e),r};var It=(n,t={},...e)=>{let r=document.createElement(n);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=e.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ks=(...n)=>n.filter(Boolean).join(" ");var $i="ask_user_question",Gs=8,cs="data-persona-ask-sheet-for",Ng="Other",Fg="Other\u2026",iu="Type your own answer here",lu="Send",_g="Next",Og="Back",$g="Submit all",qg="Skip",Ug=3,qi="data-ask-current-index",Ui="data-ask-question-count",cu="data-ask-answers",zi="data-ask-grouped",du="data-ask-layout",zg=n=>n.layout==="pills"?"pills":"rows",jg=n=>n.getAttribute(du)==="pills"?"pills":"rows",au=!1,pu=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===$i,ji=n=>{var t,e;return(e=(t=n==null?void 0:n.features)==null?void 0:t.askUserQuestion)!=null?e:{}},ds=n=>{let t=n.toolCall;if(!t)return{payload:null,complete:!1};let e=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:e};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:e};try{let o=r.join(""),s=(0,bo.parse)(o,bo.STR|bo.OBJ|bo.ARR);if(s&&typeof s=="object")return{payload:s,complete:e}}catch{}return{payload:null,complete:e}},Qs=n=>{let t=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return t.length>Gs&&!au&&(au=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Gs}.`)),t.slice(0,Gs)},Vg=n=>{var t;return(t=Qs(n)[0])!=null?t:null},Kg=(n,t)=>{var e;return(e=Qs(n)[t])!=null?e:null},Gg=(n,t)=>{let e=t.styles;e&&(e.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",e.sheetBackground),e.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",e.sheetBorder),e.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",e.sheetShadow),e.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",e.pillBackground),e.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",e.pillBackgroundSelected),e.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",e.pillTextColor),e.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",e.pillTextColorSelected),e.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",e.pillBorderRadius),e.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",e.customInputBackground))},uu=(n,t,e)=>{if(n!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(e+1),r.appendChild(o)}return r},Qg=(n,t,e,r)=>{let s=y("button",e==="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(t)),s.setAttribute("data-option-label",n.label),e==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=y("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=uu(e,r,t);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},Xg=n=>{let e=y("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 e.setAttribute("aria-hidden","true"),e},Jg=(n,t,e,r)=>{var g,f,u;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=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!e){for(let m=0;m<Ug;m++)s.appendChild(Xg(r));return s}if(d.forEach((m,v)=>{s.appendChild(Qg(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Ng:Fg;if(r==="rows"){let v=y("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=y("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(g=t.freeTextPlaceholder)!=null?g:iu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),x.appendChild(E),v.appendChild(x);let M=uu(r,a,d.length);M&&v.appendChild(M),s.appendChild(v)}else{let v=y("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=(u=t.freeTextLabel)!=null?u:m,s.appendChild(v)}}return s},mu=(n,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let 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:iu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:lu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Yg=n=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let e=y("button","persona-ask-multi-submit persona-pointer-events-auto");return e.type="button",e.textContent=(r=n.submitLabel)!=null?r:lu,e.setAttribute("data-ask-user-action","submit-multi"),e.disabled=!0,t.appendChild(e),t},Zg=(n,t,e)=>{var c,g,f,u;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=e.backLabel)!=null?c:Og,o.setAttribute("data-ask-user-action","back"),o.disabled=n===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=(g=e.skipLabel)!=null?g:qg,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=n===t-1;return i.textContent=d?(f=e.submitAllLabel)!=null?f:$g:(u=e.nextLabel)!=null?u:_g,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},_o=n=>{let t=n.getAttribute(cu);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}},gu=(n,t)=>{n.setAttribute(cu,JSON.stringify(t))},dr=n=>{var e;let t=Number((e=n.getAttribute(qi))!=null?e:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},ef=(n,t)=>{n.setAttribute(qi,String(Math.max(0,Math.floor(t))))},ps=n=>{var e;let t=Number((e=n.getAttribute(Ui))!=null?e:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},yo=n=>n.getAttribute(zi)==="true",tf=(n,t)=>{var o;let e=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!e||typeof e!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(e,i)){let d=e[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},nf=(n,t)=>{var r;let e=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof e!="number"||!Number.isFinite(e)?0:Math.max(0,Math.min(t-1,Math.floor(e)))},za=(n,t)=>{let{payload:e}=ds(t),r=Qs(e),o=_o(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},fu=n=>{let t=_o(n),e=dr(n),r=t[e],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:"",g=o.has(c);d.setAttribute("aria-pressed",g?"true":"false"),d.classList.toggle("persona-ask-pill-selected",g)});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=""},hu=n=>{if(!yo(n))return;let t=_o(n),e=dr(n),r=t[e],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}},Vi=(n,t,e)=>{let r=ji(e),o=jg(n),{payload:s,complete:a}=ds(t),i=yo(n),d=dr(n),c=ps(n),g=i?Kg(s,d):Vg(s),f=!!(g!=null&&g.multiSelect),u=n.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let S=typeof(g==null?void 0:g.question)=="string"?g.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let x=n.querySelector('[data-ask-pill-list="true"]');if(x){let S=Jg(g,r,a,o);x.replaceWith(S)}if(o!=="rows"){let S=n.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(mu(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!E?n.appendChild(Yg(r)):(!f||i)&&E&&E.remove(),n.setAttribute("data-multi-select",f?"true":"false");let M=n.querySelector('[data-ask-nav-row="true"]');if(i){let S=Zg(d,c,r);M?M.replaceWith(S):n.appendChild(S)}else M&&M.remove();fu(n),hu(n)},rf=(n,t,e)=>{let r=ji(t),o=zg(r),s=n.toolCall.id,a=Qs(e),i=Math.max(1,a.length),d=i>1,c=tf(n,a),g=d?nf(n,i):0,f=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(cs,s),f.setAttribute("data-tool-call-id",s),f.setAttribute("data-message-id",n.id),f.setAttribute(Ui,String(i)),f.setAttribute(qi,String(g)),f.setAttribute(zi,d?"true":"false"),f.setAttribute(du,o),gu(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`),Gg(f,r);let u=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="",u.appendChild(m);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",u.appendChild(v),f.appendChild(u);let E=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 E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),f.appendChild(E),o!=="rows"&&f.appendChild(mu(r,o)),Vi(f,n,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},of=(n,t,e)=>{let{payload:r}=ds(t),o=Math.max(1,Qs(r).length);o>ps(n)&&(n.setAttribute(Ui,String(o)),o>1&&!yo(n)&&n.setAttribute(zi,"true")),Vi(n,t,e)};var ja=(n,t,e)=>{if(!e||!Fo(n)||ji(t).enabled===!1)return;let o=n.toolCall.id;e.querySelectorAll(`[${cs}]`).forEach(c=>{c.getAttribute(cs)!==o&&c.remove()});let a=e.querySelector(`[${cs}="${pu(o)}"]`);if(a){of(a,n,t);return}let{payload:i}=ds(n),d=rf(n,t,i);e.appendChild(d)},us=(n,t)=>{if(!n)return;let e=t?`[${cs}="${pu(t)}"]`:`[${cs}]`;n.querySelectorAll(e).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)})},Ki=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),vo=(n,t)=>{let e=_o(n),r=dr(n);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete e[r]:e[r]=t,gu(n,e),fu(n),hu(n)},Va=(n,t,e,r)=>{let o=ps(n),s=Math.max(0,Math.min(o-1,r));ef(n,s),Vi(n,t,e)};var Gr="suggest_replies";var sf={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},bu={name:Gr,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:sf,origin:"sdk",annotations:{readOnlyHint:!0}},Gi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Qi=n=>{var t;return n.variant==="tool"&&((t=n.toolCall)==null?void 0:t.name)===Gr},af=n=>{let t=n;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let e=t==null?void 0:t.suggestions;if(!Array.isArray(e))return[];let r=e.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},yu=n=>{var t;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.role==="user")return null;if(!Qi(r))continue;let o=af((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},vu=n=>{var e;let t=(e=n==null?void 0:n.features)==null?void 0:e.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var lf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Gs,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},cf={name:$i,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:lf,origin:"sdk",annotations:{readOnlyHint:!0}},Xi=n=>{var r;let t=[],e=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1&&t.push(cf),vu(n)&&t.push(bu),t};var ms=require("partial-json"),xu=n=>n.replace(/\\n/g,`
7
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},df=n=>{var a,i;let t=(a=n.completedAt)!=null?a:Date.now(),e=(i=n.startedAt)!=null?i:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-e))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},wu=n=>n.status==="complete"?df(n):n.status==="pending"?"Waiting":"",pf=n=>{var o,s,a;let e=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return e<.1?"Used tool for <0.1 seconds":`Used tool for ${e>=10?Math.round(e).toString():e.toFixed(1).replace(/\.0$/,"")} seconds`};var Cu=n=>n.status==="complete"?pf(n):"Using tool...",Ka=n=>{let t=n/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=n=>{var e,r,o;let t=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ka(t)},Ga=n=>{var e,r,o;let t=n.durationMs!==void 0?n.durationMs:Math.max(0,((e=n.completedAt)!=null?e:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ka(t)},Ji=(n,t,e)=>{var s;if(!t)return e;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Js(n);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Qa=(n,t)=>{let e=n.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(e))!==null;)a.index>s&&Xs(r,e.slice(s,a.index),[]),a[1]!==void 0?Xs(r,a[1],["bold"]):a[2]!==void 0?Xs(r,a[2],["italic"]):a[3]!==void 0&&Xs(r,a[3],["dim"]),s=a.index+a[0].length;return s<e.length&&Xs(r,e.slice(s),[]),r},Xs=(n,t,e)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:e}),o<r.length-1&&n.push({text:"{duration}",styles:e,isDuration:!0})},uf=()=>{let n=null,t=0,e=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${n.description}`:"");return window.confirm(t)},Og=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)}},_g=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},$g=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",Ug="Other",qg="Other\u2026",Zp="Type your own answer here",eu="Send",zg="Next",jg="Back",Vg="Submit all",Kg="Skip",Gg=3,vi="data-ask-current-index",xi="data-ask-question-count",tu="data-ask-answers",wi="data-ask-grouped",nu="data-ask-layout",Qg=n=>n.layout==="pills"?"pills":"rows",Xg=n=>n.getAttribute(nu)==="pills"?"pills":"rows",Yp=!1,ru=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&&!Yp&&(Yp=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ps}.`)),e.slice(0,Ps)},Jg=n=>{var e;return(e=Is(n)[0])!=null?e:null},Yg=(n,e)=>{var t;return(t=Is(n)[e])!=null?t:null},Zg=(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))},ou=(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},ef=(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=ou(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},tf=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},nf=(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<Gg;u++)s.appendChild(tf(r));return s}if(d.forEach((u,v)=>{s.appendChild(ef(u,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let u=r==="rows"?Ug:qg;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:Zp,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=ou(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},su=(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:Zp,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:eu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},rf=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:eu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},of=(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:jg,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:Kg,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:Vg:(g=t.nextLabel)!=null?g:zg,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(tu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},au=(n,e)=>{n.setAttribute(tu,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},sf=(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",af=(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},lf=(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},iu=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=""},lu=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=Xg(n),{payload:s,complete:a}=Zo(e),i=io(n),d=sr(n),c=es(n),m=i?Yg(s,d):Jg(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=nf(m,r,a,o);x.replaceWith(E)}if(o!=="rows"){let E=n.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(su(r,o))}let I=n.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!I?n.appendChild(rf(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=of(d,c,r);M?M.replaceWith(E):n.appendChild(E)}else M&&M.remove();iu(n),lu(n)},cf=(n,e,t)=>{let r=Ci(e),o=Qg(r),s=n.toolCall.id,a=Is(t),i=Math.max(1,a.length),d=i>1,c=af(n,a),m=d?lf(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(nu,o),au(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`),Zg(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(su(r,o)),Ai(f,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},df=(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}="${ru(o)}"]`);if(a){df(a,n,e);return}let{payload:i}=Zo(n),d=cf(n,e,i);t.appendChild(d)},ts=(n,e)=>{if(!n)return;let t=e?`[${Yo}="${ru(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,au(n,t),iu(n),lu(n)},xa=(n,e,t,r)=>{let o=es(n),s=Math.max(0,Math.min(o-1,r));sf(n,s),Ai(n,e,t)};var $r="suggest_replies";var pf={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},cu={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:pf,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},uf=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},du=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=uf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},pu=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 mf={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},gf={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:mf,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(gf),pu(n)&&e.push(cu),e};var ns=require("partial-json"),uu=n=>n.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),rs=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},ff=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},mu=n=>n.status==="complete"?ff(n):n.status==="pending"?"Waiting":"",hf=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var gu=n=>n.status==="complete"?hf(n):"Using tool...",wa=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Rs=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return wa(e)},Ca=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return wa(e)},ki=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Rs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Aa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ws(r,t.slice(s,a.index),[]),a[1]!==void 0?Ws(r,a[1],["bold"]):a[2]!==void 0?Ws(r,a[2],["italic"]):a[3]!==void 0&&Ws(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ws(r,t.slice(s),[]),r},Ws=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},yf=()=>{let n=null,e=0,t=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<=t)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=e(r);return s!==null&&(n=s),t=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Oo=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Au=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Su=()=>{var t;let n=uf();return{processChunk:async e=>{let r=e.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(e)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},Tu=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:e=>{let r=e.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(e.length<=t)return n!==null||n===""?{text:n||"",raw:e}:null;try{let o=(0,ms.parse)(e,ms.STR|ms.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?xu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=xu(o.text)))}catch{}return t=e.length,n!==null?{text:n,raw:e}:null},close:()=>{}}};var Eu=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Xa=class{constructor(t,e=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=e}push(t,e){var s,a,i;let r=(i=(s=e==null?void 0:e.seq)!=null?s:e==null?void 0:e.sequenceIndex)!=null?i:(a=e==null?void 0:e.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,e);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,e),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,e);return}let o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.payload)),this.buffer.set(r,{payloadType:t,payload:e,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((e,r)=>e[0]-r[0]);for(let[e,r]of t)this.buffer.delete(e),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Mu="webmcp:";function ku(n){return n==="execution_start"}var Ja=class{constructor(t){this.kind="agent";this.iteration=1;this.openTurnId=null;this.openStepId=null;this.openTextBlockId=null;this.openReasoningId=null;this.mediaBuffers=new Map;var e;this.executionId=(e=t==null?void 0:t.executionId)!=null?e:""}push(t,e){var r,o,s,a,i,d,c,g,f,u,m,v,x,E,M;switch(typeof e.executionId=="string"&&e.executionId&&(this.executionId=e.executionId),typeof e.iteration=="number"&&(this.iteration=e.iteration),t){case"execution_start":return this.kind=e.kind==="flow"?"flow":"agent",this.kind!=="agent"?[]:[this.out("agent_start",{executionId:this.executionId,agentId:e.agentId,agentName:e.agentName,maxTurns:e.maxTurns,startedAt:e.startedAt})];case"turn_start":return this.openTurnId=typeof e.id=="string"?e.id:null,this.kind!=="agent"?[]:[this.out("agent_turn_start",{turnId:e.id,iteration:e.iteration})];case"turn_complete":{let S=this.kind==="agent"?[this.out("agent_turn_complete",{turnId:e.id,iteration:e.iteration,stopReason:e.stopReason,completedAt:e.completedAt})]:[];return this.openTurnId===e.id&&(this.openTurnId=null),S}case"execution_complete":return((r=e.kind)!=null?r:this.kind)==="agent"?[this.out("agent_complete",{executionId:this.executionId,success:e.success,completedAt:e.completedAt,stopReason:e.stopReason})]:[this.out("flow_complete",{success:e.success,completedAt:e.completedAt,duration:e.durationMs,finalOutput:e.finalOutput,totalSteps:e.totalSteps,successfulSteps:e.successfulSteps,failedSteps:e.failedSteps})];case"execution_error":return((o=e.kind)!=null?o:this.kind)==="agent"?[this.out("agent_error",{recoverable:!1,error:e.error})]:[this.out("flow_error",{error:e.error,code:e.code,upgradeUrl:e.upgradeUrl})];case"error":return[this.out("agent_error",{recoverable:!0,error:e.error})];case"ping":return[this.out("agent_ping",{timestamp:e.timestamp})];case"text_start":return this.openTextBlockId=typeof e.id=="string"?e.id:null,[];case"text_delta":{let S=String((s=e.delta)!=null?s:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"text",delta:S,turnId:(a=this.openTurnId)!=null?a:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("step_delta",{id:(i=this.openStepId)!=null?i:e.id,text:S,stepType:"prompt"})]}case"text_complete":return this.openTextBlockId===e.id&&(this.openTextBlockId=null),[];case"reasoning_start":return this.openReasoningId=typeof e.id=="string"?e.id:null,this.kind==="flow"?[this.out("reason_start",{id:e.id})]:[];case"reasoning_delta":{let S=String((d=e.delta)!=null?d:"");return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"thinking",delta:S,turnId:(c=this.openTurnId)!=null?c:e.id,iteration:this.iteration,executionId:this.executionId})]:[this.out("reason_delta",{id:e.id,delta:S})]}case"reasoning_complete":{let S=typeof e.text=="string"&&e.text.length>0;if(this.kind==="agent")return e.scope==="loop"||S?[this.out("agent_reflection",{reflection:(g=e.text)!=null?g:"",executionId:this.executionId,iteration:this.iteration})]:[];let B=[];return S&&B.push(this.out("reason_delta",{id:e.id,delta:e.text})),B.push(this.out("reason_complete",{id:e.id})),B}case"tool_start":return this.kind==="agent"?[this.out("agent_tool_start",{toolCallId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(f=e.iteration)!=null?f:this.iteration,startedAt:e.startedAt})]:[this.out("tool_start",{toolId:e.toolCallId,toolName:e.toolName,parameters:e.parameters,executionId:this.executionId,iteration:(u=e.iteration)!=null?u:this.iteration,startedAt:e.startedAt})];case"tool_input_delta":return this.kind==="agent"?[this.out("agent_turn_delta",{contentType:"tool_input",delta:String((m=e.delta)!=null?m:""),toolCallId:e.toolCallId})]:[];case"tool_input_complete":return[];case"tool_output_delta":{let S=String((v=e.delta)!=null?v:"");return this.kind==="agent"?[this.out("agent_tool_delta",{toolCallId:e.toolCallId,delta:S})]:[this.out("tool_delta",{toolId:e.toolCallId,delta:S})]}case"tool_complete":return this.kind==="agent"?[this.out("agent_tool_complete",{toolCallId:e.toolCallId,result:e.result,executionTime:e.executionTime,completedAt:e.completedAt})]:[this.out("tool_complete",{toolId:e.toolCallId,result:e.result,duration:e.executionTime,completedAt:e.completedAt})];case"media_start":{let S=String(e.id);return this.mediaBuffers.set(S,{mediaType:typeof e.mediaType=="string"?e.mediaType:void 0,role:typeof e.role=="string"?e.role:void 0,toolCallId:e.toolCallId,parts:[]}),[]}case"media_delta":{let S=this.mediaBuffers.get(String(e.id));return S&&typeof e.delta=="string"&&S.parts.push(e.delta),[]}case"media_complete":{let S=String(e.id),B=this.mediaBuffers.get(S);this.mediaBuffers.delete(S);let I=(E=(x=typeof e.mediaType=="string"?e.mediaType:void 0)!=null?x:B==null?void 0:B.mediaType)!=null?E:"application/octet-stream",R=typeof e.data=="string"?e.data:void 0,A=typeof e.url=="string"?e.url:B&&B.parts.length>0?B.parts.join(""):void 0,L=null;return R?L={type:"media",data:R,mediaType:I}:A&&(L={type:I.startsWith("image/")?"image-url":"file-url",url:A,mediaType:I}),L?[this.out("agent_media",{media:[L],executionId:this.executionId,iteration:this.iteration,toolCallId:(M=e.toolCallId)!=null?M:B==null?void 0:B.toolCallId})]:[]}case"approval_start":return[this.out("agent_approval_start",{approvalId:e.approvalId,toolName:e.toolName,toolType:e.toolType,description:e.description,reason:e.reason,parameters:e.parameters,executionId:this.executionId})];case"approval_complete":return[this.out("agent_approval_complete",{approvalId:e.approvalId,decision:e.decision,executionId:this.executionId,toolName:e.toolName,description:e.description})];case"await":{let S=typeof e.toolName=="string"?e.toolName:"",B=e.origin==="webmcp"&&!S.startsWith(Mu)?`${Mu}${S}`:S;return[this.out("step_await",{awaitReason:"local_tool_required",toolName:B,parameters:e.parameters,toolCallId:e.toolCallId,toolId:e.toolId,executionId:this.executionId,awaitedAt:e.awaitedAt})]}case"step_start":return this.openStepId=typeof e.id=="string"?e.id:null,[this.out("step_start",{id:e.id,name:e.name,stepType:e.stepType,index:e.index,totalSteps:e.totalSteps,startedAt:e.startedAt,outputVariable:e.outputVariable})];case"step_complete":{let S=this.out("step_complete",{id:e.id,name:e.name,stepType:e.stepType,success:e.success,duration:e.durationMs,result:e.result,stopReason:e.stopReason,completedAt:e.completedAt,unresolvedVariables:e.unresolvedVariables});return this.openStepId===e.id&&(this.openStepId=null),[S]}case"step_skip":return[];case"artifact_start":return[this.out("artifact_start",{id:e.id,artifactType:e.artifactType,title:e.title,component:e.component})];case"artifact_delta":return[this.out("artifact_delta",{id:e.id,delta:e.delta})];case"artifact_update":return[this.out("artifact_update",{id:e.id,component:e.component,props:e.props})];case"artifact_complete":return[this.out("artifact_complete",{id:e.id})];case"source":case"custom":return[];default:return[]}}out(t,e){let r={};for(let[o,s]of Object.entries(e))s!==void 0&&(r[o]=s);return{payloadType:t,payload:r}}};var Lu="3.37.0";var Ys=Lu;var gf="https://api.runtype.com/v1/dispatch",Ya="https://api.runtype.com";function ff(n){var s,a;let t=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.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 Yi=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 hf(n){switch(n){case"json":return Tu;case"regex-json":return Su;case"xml":return Eu;default:return Au}}var Iu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function bf(n,t){if(!n)return t;let e=n.trim(),r=t.trim();if(e.length===0)return t;if(r.length===0)return n;let o=Iu(e);if(!Iu(r))return n;if(!o||r===e||r.startsWith(e))return t;let a=Oo(n);return Oo(t)!==null&&a===null?t:n}var Zs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var e,r,o,s;this.apiUrl=(e=t.apiUrl)!=null?e:gf,this.headers={"Content-Type":"application/json","X-Persona-Version":Ys,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:hf(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Ua(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var e;(e=this.webMcpBridge)==null||e.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,e,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,e,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}withEventsParam(t){return this.config.events!=="unified"?t:t+(t.includes("?")?"&":"?")+"events=unified"}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,e;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(),(e=(t=this.config).onSessionInit)==null||e.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,e={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ys},body:JSON.stringify(e)});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 e;return`${((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ys},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(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:e})}async submitCSATFeedback(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:e})}async submitNPSFeedback(t,e){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:e})}async dispatch(t,e){return this.isAgentMode()?this.dispatchAgent(t,e):this.isClientTokenMode()?this.dispatchClientToken(t,e):this.dispatchProxy(t,e)}async dispatchClientToken(t,e){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({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 I=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:I}),I}let c=await this.buildPayload(t.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,f={sessionId:d.sessionId,messages:t.messages.filter(Yi).map(I=>{var R,A,L;return{id:I.id,role:I.role,content:(L=(A=(R=I.contentParts)!=null?R:I.llmContent)!=null?A:I.rawContent)!=null?L:I.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},u=c.clientTools,m=!!(u&&u.length>0),v=m?ou(u):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&x&&this.lastSentClientToolsFingerprint===v,M=!1,S=null,B;for(let I=0;;I++){let A={...f,...m&&(M||!E)&&u?{clientTools:u}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),B=await fetch(this.withEventsParam(this.getClientApiUrl("chat")),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ys},body:JSON.stringify(A),signal:r.signal}),B.status===409&&I===0&&m){let L=await B.json().catch(()=>null);if((L==null?void 0:L.error)==="client_tools_resend_required"){M=!0,this.lastSentClientToolsFingerprint=null;continue}S=L!=null?L:{error:"Chat request failed"}}break}if(!B.ok){let I=S!=null?S:await B.json().catch(()=>({error:"Chat request failed"}));if(B.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw e({type:"error",error:A}),A}if(B.status===429){let A=new Error(I.hint||"Message limit reached for this session.");throw e({type:"error",error:A}),A}let R=new Error(I.error||"Failed to send message");throw e({type:"error",error:R}),R}if(!B.body){let I=new Error("No response body received");throw e({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,e({type:"status",status:"connected"});try{await this.streamResponse(B.body,e,t.assistantMessageId)}finally{e({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")&&e({type:"error",error:c}),c}}async dispatchProxy(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildPayload(t.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.withEventsParam(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 e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(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 e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e)}finally{e({type:"status",status:"idle"})}}async dispatchAgent(t,e){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),e({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.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.withEventsParam(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 e({type:"error",error:d}),d}else a=await fetch(this.withEventsParam(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 e({type:"error",error:i}),i}e({type:"status",status:"connected"});try{await this.streamResponse(a.body,e,t.assistantMessageId)}finally{e({type:"status",status:"idle"})}}async processStream(t,e,r){e({type:"status",status:"connected"});try{await this.streamResponse(t,e,r)}finally{e({type:"status",status:"idle"})}}async resolveApproval(t,e){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ya}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:e,streamResponse:!0})})}async resumeFlow(t,e,r){var c,g;let o=this.isClientTokenMode(),s=this.withEventsParam(o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ya}/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:t,toolOutputs:e,streamResponse:(g=r==null?void 0:r.streamResponse)!=null?g:!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(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let e=t.slice().filter(Yi).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(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:e,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},o=[...Xi(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:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var s,a;let r={messages:t.slice().filter(Yi).sort((i,d)=>{let c=new Date(i.createdAt).getTime(),g=new Date(d.createdAt).getTime();return c-g}).map(i=>{var d,c,g;return{role:i.role,content:(g=(c=(d=i.contentParts)!=null?d:i.llmContent)!=null?c:i.rawContent)!=null?g:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},o=[...Xi(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:t,config:this.config});c&&typeof c=="object"&&Object.assign(i,c)}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",c)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,e,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=g=>{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(),...g!==void 0&&{partId:g}};return r.current=f,o(f),f},c=g=>r.current?r.current:d(g);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 g=c(i.partId);i.partId!==void 0&&!g.partId&&(g.partId=i.partId),g.content+=i.text,o(g)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,e({type:"status",status:"idle"})),i.error&&(a.current=null,e({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,e,r){var wr,Sn,Ke,Ft;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=q=>{let ke=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,Ce=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,_e=q.tools?q.tools.map(it=>({...it,chunks:it.chunks?[...it.chunks]:void 0})):void 0;return{...q,reasoning:ke,toolCall:Ce,tools:_e}},f=q=>{if(q.role!=="assistant"||q.variant)return!0;let ke=Array.isArray(q.contentParts)&&q.contentParts.length>0,Ce=typeof q.rawContent=="string"&&q.rawContent.trim()!=="";return typeof q.content=="string"&&q.content.trim()!==""||ke||Ce||!!q.stopReason},u=q=>{f(q)&&e({type:"message",message:g(q)})},m=null,v=null,x={current:null},E={current:null},M=!1,S=new Map,B=new Map,I=new Map,R=new Map,A={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},N=(q,ke,Ce="")=>`${q}::${ke}::${Ce}`,F=(q,ke)=>`${q}::${ke}::`,k=(q,ke,Ce,_e)=>{let it=N(q,ke,Ce),pt=I.get(it);if(pt)return pt;let ot=Ce?`-${Ce}`:"",Mt={id:`nested-${q}-${ke}${ot}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Ce?{partId:Ce}:{},agentMetadata:{executionId:_e,parentToolId:q,parentStepId:ke}};return I.set(it,Mt),u(Mt),Mt},z=q=>{if(q==null)return null;try{return String(q)}catch{return null}},j=q=>{var ke,Ce,_e,it,pt;return z((pt=(it=(_e=(Ce=(ke=q.stepId)!=null?ke:q.step_id)!=null?Ce:q.step)!=null?_e:q.parentId)!=null?it:q.flowStepId)!=null?pt:q.flow_step_id)},re=q=>{var ke,Ce,_e,it,pt,ot,Mt;return z((Mt=(ot=(pt=(it=(_e=(Ce=(ke=q.callId)!=null?ke:q.call_id)!=null?Ce:q.requestId)!=null?_e:q.request_id)!=null?it:q.toolCallId)!=null?pt:q.tool_call_id)!=null?ot:q.stepId)!=null?Mt:q.step_id)},Ie=r,Ve=!1,ve=()=>{if(m)return m;let q;return!Ve&&Ie?(q=Ie,Ve=!0):Ie&&E.current?q=`${Ie}_${E.current}`:q=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:q,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(m),m},Ne=(q,ke)=>{A.lastId=ke,q&&A.byStep.set(q,ke)},qe=(q,ke)=>{var pt;let Ce=(pt=q.reasoningId)!=null?pt:q.id,_e=j(q);if(Ce){let ot=String(Ce);return Ne(_e,ot),ot}if(_e){let ot=A.byStep.get(_e);if(ot)return A.lastId=ot,ot}if(A.lastId&&!ke)return A.lastId;if(!ke)return null;let it=`reason-${c()}`;return Ne(_e,it),it},Te=q=>{let ke=S.get(q);if(ke)return ke;let Ce={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:q,status:"streaming",chunks:[]}};return S.set(q,Ce),u(Ce),Ce},we=(q,ke)=>{L.lastId=ke,q&&L.byCall.set(q,ke)},oe=new Set,X=new Map,se=new Set,fe=new Map,pe=q=>{if(!q)return!1;let ke=q.replace(/_+/g,"_").replace(/^_|_$/g,"");return ke==="emit_artifact_markdown"||ke==="emit_artifact_component"},K=(q,ke)=>{var pt;let Ce=(pt=q.toolId)!=null?pt:q.id,_e=re(q);if(Ce){let ot=String(Ce);return we(_e,ot),ot}if(_e){let ot=L.byCall.get(_e);if(ot)return L.lastId=ot,ot}if(L.lastId&&!ke)return L.lastId;if(!ke)return null;let it=`tool-${c()}`;return we(_e,it),it},ae=q=>{let ke=B.get(q);if(ke)return ke;let Ce={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return B.set(q,Ce),u(Ce),Ce},Be=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let ke=Number(q);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let Ce=Date.parse(q);if(!Number.isNaN(Ce))return Ce}return Date.now()},ee=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},Z=new Map,ne=new Map,st=new Map,at=new Map,nt=null,Me=(q,ke,Ce)=>{var Mt;let _e=st.get(q);_e||(_e=[],st.set(q,_e));let it=0,pt=_e.length;for(;it<pt;){let V=it+pt>>>1;_e[V].seq<ke?it=V+1:pt=V}((Mt=_e[it])==null?void 0:Mt.seq)===ke?_e[it]={seq:ke,text:Ce}:_e.splice(it,0,{seq:ke,text:Ce});let ot="";for(let V=0;V<_e.length;V++)ot+=_e[V].text;return ot},he=(q,ke)=>{let Ce=ee(ke),_e=ne.get(q.id),it=bf(_e,Ce);q.rawContent=it;let pt=Z.get(q.id),ot=me=>{var ut;let Ee=(ut=q.content)!=null?ut:"";me.trim()!==""&&(Ee.trim().length===0||me.startsWith(Ee)||me.trimStart().startsWith(Ee.trim()))&&(q.content=me)},Mt=()=>{var me;if(pt){let Ee=(me=pt.close)==null?void 0:me.call(pt);Ee instanceof Promise&&Ee.catch(()=>{})}Z.delete(q.id),ne.delete(q.id),q.streaming=!1,u(q)};if(!pt){ot(Ce),Mt();return}let V=Oo(it);if(V!==null&&V.trim()!==""){ot(V),Mt();return}let St=me=>{var en;let Ee=typeof me=="string"?me:(en=me==null?void 0:me.text)!=null?en:null;if(Ee!==null&&Ee.trim()!=="")return Ee;let ut=pt.getExtractedText();return ut!==null&&ut.trim()!==""?ut:Ce},de;try{de=pt.processChunk(it)}catch{ot(Ce),Mt();return}if(de instanceof Promise){de.then(me=>{ot(St(me)),Mt()}).catch(()=>{ot(Ce),Mt()});return}ot(St(de)),Mt()},Ge=[],J=!1,ue,Le=()=>{J||(J=!0,queueMicrotask(()=>{J=!1,ue()}))},Xe=new Xa((q,ke)=>{Ge.push({payloadType:q,payload:ke}),Le()}),Gt=new Ja,Pe=this.config.events==="unified",Ue=!1,rt=null,Nt=new Map,yn=(wr=this.config.iterationDisplay)!=null?wr:"separate";for(ue=()=>{var q,ke,Ce,_e,it,pt,ot,Mt,V,St,de,me,Ee,ut,en,an,wn,Ot,et,_t,mt,tn,rr,Wn,ln,On,Cr,Ct,jn,Ar,Nr,ur,xt,Co,Sr,Ao,$n,Ko,Yr,Fr,Zr,eo,So,To,to,Tt,Vn,Kn,Rn,kt,or,sr,Gn,no,_r,ro,Qn,$t,Bn,ar,oo,Or,so,Tr,Xn,ye,gt,rn,un,Er,Es,$r,Eo,Mr,O,Go,kr,Lr,qr,Ir,mr,Qo,xa,Jn,Yn,gr,fr,Mo,Ur,Tn,Pr,Xo,ko,Jo,wa,Yo,Ca,Zo,vt,Ms,ir,qn,Aa,Sa,es,zr,ks,ao,Ls,Is,Ps,Ws,Un,ts,Wr,Rr,Rs,Ta,Bs,Hs,Lo,Ea,Ma,ka,La,Ia,io,lo,Pa,Ds,co,Wa,Ns,po,Fs,Ra,jr,Ba;for(let Br=0;Br<Ge.length;Br++){let be=Ge[Br].payloadType,w=Ge[Br].payload;if(be==="reason_start"){let $=(q=qe(w,!0))!=null?q:`reason-${c()}`,P=Te($);P.reasoning=(ke=P.reasoning)!=null?ke:{id:$,status:"streaming",chunks:[]},P.reasoning.startedAt=(_e=P.reasoning.startedAt)!=null?_e:Be((Ce=w.startedAt)!=null?Ce:w.timestamp),P.reasoning.completedAt=void 0,P.reasoning.durationMs=void 0,P.streaming=!0,P.reasoning.status="streaming",u(P)}else if(be==="reason_delta"||be==="reason_chunk"){let $=(pt=(it=qe(w,!1))!=null?it:qe(w,!0))!=null?pt:`reason-${c()}`,P=Te($);P.reasoning=(ot=P.reasoning)!=null?ot:{id:$,status:"streaming",chunks:[]},P.reasoning.startedAt=(V=P.reasoning.startedAt)!=null?V:Be((Mt=w.startedAt)!=null?Mt:w.timestamp);let G=(me=(de=(St=w.reasoningText)!=null?St:w.text)!=null?de:w.delta)!=null?me:"";if(G&&w.hidden!==!0){let ie=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(ie!==void 0){let Q=Me($,ie,String(G));P.reasoning.chunks=[Q]}else P.reasoning.chunks.push(String(G))}if(P.reasoning.status=w.done?"complete":"streaming",w.done){P.reasoning.completedAt=Be((Ee=w.completedAt)!=null?Ee:w.timestamp);let ie=(ut=P.reasoning.startedAt)!=null?ut:Date.now();P.reasoning.durationMs=Math.max(0,((en=P.reasoning.completedAt)!=null?en:Date.now())-ie)}P.streaming=P.reasoning.status!=="complete",u(P)}else if(be==="reason_complete"){let $=(wn=(an=qe(w,!1))!=null?an:qe(w,!0))!=null?wn:`reason-${c()}`,P=S.get($);if(P!=null&&P.reasoning){P.reasoning.status="complete",P.reasoning.completedAt=Be((Ot=w.completedAt)!=null?Ot:w.timestamp);let ie=(et=P.reasoning.startedAt)!=null?et:Date.now();P.reasoning.durationMs=Math.max(0,((_t=P.reasoning.completedAt)!=null?_t:Date.now())-ie),P.streaming=!1,u(P)}let G=j(w);G&&A.byStep.delete(G)}else if(be==="tool_start"){let $=(mt=K(w,!0))!=null?mt:`tool-${c()}`,P=(tn=w.toolName)!=null?tn:w.name;if(pe(P)){oe.add($);continue}let G=ae($),ie=(rr=G.toolCall)!=null?rr:{id:$,status:"pending"};ie.name=P!=null?P:ie.name,ie.status="running",w.args!==void 0?ie.args=w.args:w.parameters!==void 0&&(ie.args=w.parameters),ie.startedAt=(ln=ie.startedAt)!=null?ln:Be((Wn=w.startedAt)!=null?Wn:w.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,G.toolCall=ie,G.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(G.agentMetadata={executionId:(On=Q==null?void 0:Q.executionId)!=null?On:w.executionId,iteration:(Cr=Q==null?void 0:Q.iteration)!=null?Cr:w.iteration}),u(G)}else if(be==="tool_chunk"||be==="tool_delta"){let $=(jn=(Ct=K(w,!1))!=null?Ct:K(w,!0))!=null?jn:`tool-${c()}`;if(oe.has($))continue;let P=ae($),G=(Ar=P.toolCall)!=null?Ar:{id:$,status:"running"};G.startedAt=(ur=G.startedAt)!=null?ur:Be((Nr=w.startedAt)!=null?Nr:w.timestamp);let ie=(Sr=(Co=(xt=w.text)!=null?xt:w.delta)!=null?Co:w.message)!=null?Sr:"";ie&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ie))),G.status="running",P.toolCall=G,P.streaming=!0;let Q=w.agentContext;(Q||w.executionId)&&(P.agentMetadata=(Yr=P.agentMetadata)!=null?Yr:{executionId:($n=Q==null?void 0:Q.executionId)!=null?$n:w.executionId,iteration:(Ko=Q==null?void 0:Q.iteration)!=null?Ko:w.iteration}),u(P)}else if(be==="tool_complete"){let $=(Zr=(Fr=K(w,!1))!=null?Fr:K(w,!0))!=null?Zr:`tool-${c()}`;if(oe.has($)){oe.delete($);continue}let P=ae($),G=(eo=P.toolCall)!=null?eo:{id:$,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Be((So=w.completedAt)!=null?So:w.timestamp);let ie=(To=w.duration)!=null?To:w.executionTime;if(typeof ie=="number")G.durationMs=ie;else{let $e=(to=G.startedAt)!=null?to:Date.now();G.durationMs=Math.max(0,((Tt=G.completedAt)!=null?Tt:Date.now())-$e)}P.toolCall=G,P.streaming=!1;let Q=w.agentContext;(Q||w.executionId)&&(P.agentMetadata=(Rn=P.agentMetadata)!=null?Rn:{executionId:(Vn=Q==null?void 0:Q.executionId)!=null?Vn:w.executionId,iteration:(Kn=Q==null?void 0:Q.iteration)!=null?Kn:w.iteration}),u(P);let Re=re(w);Re&&L.byCall.delete(Re)}else if(be==="step_await"&&w.awaitReason==="local_tool_required"&&w.toolName){let $=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,P=(kt=$!=null?$:w.toolId)!=null?kt:`local-${c()}`,G=ae(P),ie=w.toolName,Q=Vs(ie),Re=(or=G.toolCall)!=null?or:{id:P,status:"pending"};Re.name=ie,Re.args=w.parameters,Re.status=Q?"running":"complete",Re.chunks=(sr=Re.chunks)!=null?sr:[],Re.startedAt=(no=Re.startedAt)!=null?no:Be((Gn=w.startedAt)!=null?Gn:w.timestamp),Q?(Re.completedAt=void 0,Re.duration=void 0,Re.durationMs=void 0):Re.completedAt=(_r=Re.completedAt)!=null?_r:Re.startedAt,G.toolCall=Re,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Qn=w.executionId)!=null?Qn:(ro=G.agentMetadata)==null?void 0:ro.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(G)}else if(be==="text_start"){if(($t=w.toolContext)!=null&&$t.toolId)continue;let $=w.partId;if($!==void 0&&E.current!==null&&$!==E.current){let P=m;P&&(P.streaming=!1,u(P),nt=P,m=null,M=!0)}$!==void 0&&(E.current=$)}else if(be==="text_end"){if((Bn=w.toolContext)!=null&&Bn.toolId)continue;let $=m;$&&($.streaming=!1,u($),nt=$,m=null,M=!0)}else if(be==="step_chunk"||be==="step_delta"){let $=w.stepType,P=w.executionType;if($==="tool"||P==="context")continue;let G=w.toolContext;if(G!=null&&G.toolId){let $e=String((oo=(ar=w.id)!=null?ar:G.stepId)!=null?oo:`step-${c()}`),lt=w.partId!==void 0&&w.partId!==null?String(w.partId):"",Ye=`${G.toolId}::${$e}`,Pt=R.get(Ye);if(lt!==""&&Pt!==void 0&&Pt!==""&&Pt!==lt){let Wt=I.get(N(G.toolId,$e,Pt));Wt&&Wt.streaming!==!1&&(Wt.streaming=!1,u(Wt))}lt!==""&&R.set(Ye,lt);let qt=k(G.toolId,$e,lt,G.executionId),vn=(Xn=(Tr=(so=(Or=w.text)!=null?Or:w.delta)!=null?so:w.content)!=null?Tr:w.chunk)!=null?Xn:"";vn&&(qt.content+=String(vn),qt.streaming=!0,u(qt)),w.isComplete&&(qt.streaming=!1,u(qt));continue}let ie=w.partId;if(ie!==void 0&&E.current!==null&&ie!==E.current){let $e=m;$e&&($e.streaming=!1,u($e),nt=$e,m=null,M=!0)}ie!==void 0&&(E.current=ie);let Q=ie!==void 0&&(ye=at.get(ie))!=null?ye:ve();ie!==void 0&&(Q.partId||(Q.partId=ie),at.set(ie,Q));let Re=(Er=(un=(rn=(gt=w.text)!=null?gt:w.delta)!=null?rn:w.content)!=null?un:w.chunk)!=null?Er:"";if(Re){let $e=typeof w.seq=="number"?w.seq:void 0,lt=ie!=null?ie:Q.id,Ye=$e!==void 0?Me(lt,$e,String(Re)):((Es=ne.get(Q.id))!=null?Es:"")+Re;Q.rawContent=Ye,Z.has(Q.id)||Z.set(Q.id,this.createStreamParser());let Pt=Z.get(Q.id),qt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(qt&&ne.set(Q.id,Ye),Pt.__isPlainTextParser===!0){Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q);continue}let Wt=Pt.processChunk(Ye);if(Wt instanceof Promise)Wt.then(Ht=>{var En;let mn=typeof Ht=="string"?Ht:(En=Ht==null?void 0:Ht.text)!=null?En:null;if(mn!==null&&mn.trim()!=="")Q.content=mn,u(Q);else if(!qt&&!Ye.trim().startsWith("<")){let Cn=m,Dt=Cn&&Cn.id===Q.id?Cn:Q;Dt.id===Q.id&&(Dt.content=$e!==void 0?Ye:Dt.content+Re,ne.delete(Dt.id),Z.delete(Dt.id),Dt.rawContent=void 0,u(Dt))}}).catch(()=>{Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q)});else{let Ht=typeof Wt=="string"?Wt:($r=Wt==null?void 0:Wt.text)!=null?$r:null;Ht!==null&&Ht.trim()!==""?(Q.content=Ht,u(Q)):!qt&&!Ye.trim().startsWith("<")&&(Q.content=$e!==void 0?Ye:Q.content+Re,ne.delete(Q.id),Z.delete(Q.id),Q.rawContent=void 0,u(Q))}}if(w.isComplete){let $e=(Mr=(Eo=w.result)==null?void 0:Eo.response)!=null?Mr:Q.content;if($e){let lt=ne.get(Q.id),Ye=lt!=null?lt:ee($e);Q.rawContent=Ye;let Pt=Z.get(Q.id),qt=null,vn=!1;if(Pt&&(qt=Pt.getExtractedText(),qt===null&&(qt=Oo(Ye)),qt===null)){let Wt=Pt.processChunk(Ye);Wt instanceof Promise?(vn=!0,Wt.then(Ht=>{var En;let mn=typeof Ht=="string"?Ht:(En=Ht==null?void 0:Ht.text)!=null?En:null;if(mn!==null){let Cn=m;Cn&&Cn.id===Q.id&&(Cn.content=mn,Cn.streaming=!1,Z.delete(Cn.id),ne.delete(Cn.id),u(Cn))}})):qt=typeof Wt=="string"?Wt:(O=Wt==null?void 0:Wt.text)!=null?O:null}if(!vn){qt!==null&&qt.trim()!==""?Q.content=qt:ne.has(Q.id)||(Q.content=ee($e));let Wt=Z.get(Q.id);if(Wt){let Ht=(Go=Wt.close)==null?void 0:Go.call(Wt);Ht instanceof Promise&&Ht.catch(()=>{}),Z.delete(Q.id)}ne.delete(Q.id),Q.streaming=!1,u(Q)}}}}else if(be==="step_complete"){let $=w.stepType,P=w.executionType;if($==="tool"||P==="context")continue;let G=w.toolContext;if(G!=null&&G.toolId){let $e=String((Lr=(kr=w.id)!=null?kr:G.stepId)!=null?Lr:"");if($e){let lt=F(G.toolId,$e);for(let[Ye,Pt]of I)Ye.startsWith(lt)&&Pt.streaming!==!1&&(Pt.streaming=!1,u(Pt));R.delete(`${G.toolId}::${$e}`)}continue}let ie=w.stopReason;if(M){if(m!==null){let Ye=m;ie&&(Ye.stopReason=ie),Z.delete(Ye.id),ne.delete(Ye.id),Ye.streaming!==!1&&(Ye.streaming=!1,u(Ye))}let $e=(qr=w.result)==null?void 0:qr.response,lt=nt;lt&&(ie&&(lt.stopReason=ie),$e!=null?he(lt,$e):(Z.delete(lt.id),ne.delete(lt.id))),nt=null;continue}let Q=(Ir=w.result)==null?void 0:Ir.response,Re=ve();if(ie&&(Re.stopReason=ie),Q!=null){let $e=Z.get(Re.id),lt=!1,Ye=!1;if($e){let Pt=$e.getExtractedText(),qt=ne.get(Re.id),vn=qt!=null?qt:ee(Q);if(Re.rawContent=vn,Pt!==null&&Pt.trim()!=="")Re.content=Pt,lt=!0;else{let Wt=Oo(vn);if(Wt!==null)Re.content=Wt,lt=!0;else{let Ht=$e.processChunk(vn);if(Ht instanceof Promise)Ye=!0,Ht.then(mn=>{var Cn;let En=typeof mn=="string"?mn:(Cn=mn==null?void 0:mn.text)!=null?Cn:null;if(En!==null&&En.trim()!==""){let Dt=m;Dt&&Dt.id===Re.id&&(Dt.content=En,Dt.streaming=!1,Z.delete(Dt.id),ne.delete(Dt.id),u(Dt))}else{let Dt=$e.getExtractedText(),cn=m;cn&&cn.id===Re.id&&(Dt!==null&&Dt.trim()!==""?cn.content=Dt:ne.has(cn.id)||(cn.content=ee(Q)),cn.streaming=!1,Z.delete(cn.id),ne.delete(cn.id),u(cn))}});else{let mn=typeof Ht=="string"?Ht:(mr=Ht==null?void 0:Ht.text)!=null?mr:null;if(mn!==null&&mn.trim()!=="")Re.content=mn,lt=!0;else{let En=$e.getExtractedText();En!==null&&En.trim()!==""&&(Re.content=En,lt=!0)}}}}}if(!Ye){if(!Re.rawContent){let Pt=ne.get(Re.id);Re.rawContent=Pt!=null?Pt:ee(Q)}if(!lt&&!ne.has(Re.id)&&(Re.content=ee(Q)),$e){let Pt=(Qo=$e.close)==null?void 0:Qo.call($e);Pt instanceof Promise&&Pt.catch(()=>{})}Z.delete(Re.id),ne.delete(Re.id),Re.streaming=!1,u(Re)}}else Z.delete(Re.id),ne.delete(Re.id),Re.streaming=!1,u(Re)}else if(be==="flow_complete"){let $=(xa=w.result)==null?void 0:xa.response;if(M){if(m!==null){let P=m;Z.delete(P.id),ne.delete(P.id),P.streaming!==!1&&(P.streaming=!1,u(P))}}else if($!=null){let P=ve(),G=ne.get(P.id),ie=G!=null?G:ee($);P.rawContent=ie;let Q=ee($),Re=Z.get(P.id);if(Re){let Ye=Oo(ie);if(Ye!==null)Q=Ye;else{let Pt=Re.processChunk(ie);Pt instanceof Promise&&Pt.then(vn=>{var Ht;let Wt=typeof vn=="string"?vn:(Ht=vn==null?void 0:vn.text)!=null?Ht:null;Wt!==null&&(P.content=Wt,P.streaming=!1,u(P))});let qt=Re.getExtractedText();qt!==null&&(Q=qt)}}Z.delete(P.id),ne.delete(P.id);let $e=Q!==P.content,lt=P.streaming!==!1;$e&&(P.content=Q),P.streaming=!1,($e||lt)&&u(P)}else if(m!==null){let P=m;Z.delete(P.id),ne.delete(P.id),P.streaming!==!1&&(P.streaming=!1,u(P))}e({type:"status",status:"idle"})}else if(be==="agent_start")rt={executionId:w.executionId,agentId:(Jn=w.agentId)!=null?Jn:"virtual",agentName:(Yn=w.agentName)!=null?Yn:"",status:"running",currentIteration:0,maxTurns:(gr=w.maxTurns)!=null?gr:1,startedAt:Be(w.startedAt)};else if(be==="agent_iteration_start"){if(rt&&(rt.currentIteration=w.iteration),yn==="separate"&&w.iteration>1){let $=m;$&&($.streaming=!1,u($),Nt.set(w.iteration-1,$),m=null)}}else if(be==="agent_turn_start")v=null;else if(be==="agent_turn_delta"){if(w.contentType==="text"){let $=ve();$.content+=(fr=w.delta)!=null?fr:"",$.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId,agentName:rt==null?void 0:rt.agentName},v=$,u($)}else if(w.contentType==="thinking"){let $=(Mo=w.turnId)!=null?Mo:`agent-think-${w.iteration}`,P=Te($);P.reasoning=(Ur=P.reasoning)!=null?Ur:{id:$,status:"streaming",chunks:[]},P.reasoning.chunks.push((Tn=w.delta)!=null?Tn:""),P.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:w.turnId},u(P)}else if(w.contentType==="tool_input"){let $=(Pr=w.toolCallId)!=null?Pr:L.lastId;if($){let P=B.get($);P!=null&&P.toolCall&&(P.toolCall.chunks=(Xo=P.toolCall.chunks)!=null?Xo:[],P.toolCall.chunks.push((ko=w.delta)!=null?ko:""),u(P))}}}else if(be==="agent_turn_complete"){let $=w.turnId;if($){let ie=S.get($);if(ie!=null&&ie.reasoning){ie.reasoning.status="complete",ie.reasoning.completedAt=Be(w.completedAt);let Q=(Jo=ie.reasoning.startedAt)!=null?Jo:Date.now();ie.reasoning.durationMs=Math.max(0,((wa=ie.reasoning.completedAt)!=null?wa:Date.now())-Q),ie.streaming=!1,u(ie)}}let P=w.stopReason,G=m!=null?m:v;if(P&&G!==null){let ie=w.turnId;(!ie||((Yo=G.agentMetadata)==null?void 0:Yo.turnId)===ie)&&(G.stopReason=P,u(G))}}else if(be==="agent_tool_start"){m&&(m.streaming=!1,u(m),m=null);let $=(Ca=w.toolCallId)!=null?Ca:`agent-tool-${c()}`;we(re(w),$);let P=ae($),G=(Zo=P.toolCall)!=null?Zo:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};G.name=(Ms=(vt=w.toolName)!=null?vt:w.name)!=null?Ms:G.name,G.status="running",w.parameters!==void 0&&(G.args=w.parameters),G.startedAt=Be((ir=w.startedAt)!=null?ir:w.timestamp),P.toolCall=G,P.streaming=!0,P.agentMetadata={executionId:w.executionId,iteration:w.iteration},u(P)}else if(be==="agent_tool_delta"){let $=(qn=w.toolCallId)!=null?qn:L.lastId;if($){let P=(Aa=B.get($))!=null?Aa:ae($);P.toolCall&&(P.toolCall.chunks=(Sa=P.toolCall.chunks)!=null?Sa:[],P.toolCall.chunks.push((es=w.delta)!=null?es:""),P.toolCall.status="running",P.streaming=!0,u(P))}}else if(be==="agent_tool_complete"){let $=(zr=w.toolCallId)!=null?zr:L.lastId;if($){let P=(ks=B.get($))!=null?ks:ae($);if(P.toolCall){P.toolCall.status="complete",w.result!==void 0&&(P.toolCall.result=w.result),typeof w.executionTime=="number"&&(P.toolCall.durationMs=w.executionTime),P.toolCall.completedAt=Be((ao=w.completedAt)!=null?ao:w.timestamp),P.streaming=!1,u(P);let G=re(w);G&&L.byCall.delete(G)}}}else if(be==="agent_media"){let $=Array.isArray(w.media)?w.media:[],P=[];for(let G of $){if(!G||typeof G!="object")continue;let ie=G,Q=typeof ie.type=="string"?ie.type:void 0,Re=typeof ie.mediaType=="string"?ie.mediaType.toLowerCase():"",$e=null,lt="";if(Q==="media"){let Ye=typeof ie.data=="string"?ie.data:void 0;if(!Ye)continue;lt=Re.length>0?Re:"application/octet-stream",$e=`data:${lt};base64,${Ye}`}else if(Q==="image-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;lt=Re,$e=Ye}else if(Q==="file-url"){let Ye=typeof ie.url=="string"?ie.url:void 0;if(!Ye)continue;lt=Re,$e=Ye}else continue;if($e)if(Q==="image-url"||lt.startsWith("image/"))P.push({type:"image",image:$e,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))P.push({type:"audio",audio:$e,mimeType:lt});else if(lt.startsWith("video/"))P.push({type:"video",video:$e,mimeType:lt});else{let Ye=lt||"application/octet-stream";P.push({type:"file",data:$e,mimeType:Ye,filename:ff(Ye)})}}if(P.length>0){let G=c(),ie=w.toolCallId,Re={id:`agent-media-${typeof ie=="string"&&ie.length>0?`${ie}-${G}`:String(G)}`,role:"assistant",content:"",contentParts:P,createdAt:new Date().toISOString(),streaming:!1,sequence:G,agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(Re);let $e=m;$e&&($e.streaming=!1,u($e)),m=null,x.current=null}}else if(be!=="agent_iteration_complete"){if(be==="agent_reflection"||be==="agent_reflect"){let $=`agent-reflection-${w.executionId}-${w.iteration}`,P={id:$,role:"assistant",content:(Ls=w.reflection)!=null?Ls:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Is=w.reflection)!=null?Is:""]},agentMetadata:{executionId:w.executionId,iteration:w.iteration}};u(P)}else if(be==="agent_complete"){rt&&(rt.status=w.success?"complete":"error",rt.completedAt=Be(w.completedAt),rt.stopReason=w.stopReason);let $=m;$&&($.streaming=!1,u($)),e({type:"status",status:"idle"})}else if(be==="agent_error"){let $=typeof w.error=="string"?w.error:(Ws=(Ps=w.error)==null?void 0:Ps.message)!=null?Ws:"Agent execution error";w.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):e({type:"error",error:new Error($)})}else if(be!=="agent_ping"){if(be==="agent_approval_start"){let $=(Un=w.approvalId)!=null?Un:`approval-${c()}`,P={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(ts=rt==null?void 0:rt.agentId)!=null?ts:"virtual",executionId:(Rr=(Wr=w.executionId)!=null?Wr:rt==null?void 0:rt.executionId)!=null?Rr:"",toolName:(Rs=w.toolName)!=null?Rs:"",toolType:w.toolType,description:(Bs=w.description)!=null?Bs:`Execute ${(Ta=w.toolName)!=null?Ta:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(P)}else if(be==="step_await"&&w.awaitReason==="approval_required"){let $=(Hs=w.approvalId)!=null?Hs:`approval-${c()}`,P={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Lo=rt==null?void 0:rt.agentId)!=null?Lo:"virtual",executionId:(Ma=(Ea=w.executionId)!=null?Ea:rt==null?void 0:rt.executionId)!=null?Ma:"",toolName:(ka=w.toolName)!=null?ka:"",toolType:w.toolType,description:(Ia=w.description)!=null?Ia:`Execute ${(La=w.toolName)!=null?La:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};u(P)}else if(be==="agent_approval_complete"){let $=w.approvalId;if($){let G={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(io=w.decision)!=null?io:"approved",agentId:(lo=rt==null?void 0:rt.agentId)!=null?lo:"virtual",executionId:(Ds=(Pa=w.executionId)!=null?Pa:rt==null?void 0:rt.executionId)!=null?Ds:"",toolName:(co=w.toolName)!=null?co:"",description:(Wa=w.description)!=null?Wa:"",resolvedAt:Date.now()}};u(G)}}else if(be==="artifact_start"||be==="artifact_delta"||be==="artifact_update"||be==="artifact_complete"){if(be==="artifact_start"){let $=w.artifactType,P=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(e({type:"artifact_start",id:P,artifactType:$,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(P,{markdown:"",title:G}),!se.has(P)){se.add(P);let ie={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:P,title:G,artifactType:$,status:"streaming"}})};X.set(P,ie),u(ie)}}else if(be==="artifact_delta"){let $=String(w.id),P=typeof w.delta=="string"?w.delta:String((Ns=w.delta)!=null?Ns:"");e({type:"artifact_delta",id:$,artDelta:P});let G=fe.get($);G&&(G.markdown+=P)}else if(be==="artifact_update"){let $=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};e({type:"artifact_update",id:String(w.id),props:$,component:typeof w.component=="string"?w.component:void 0})}else if(be==="artifact_complete"){let $=String(w.id);e({type:"artifact_complete",id:$});let P=X.get($);if(P){P.streaming=!1;try{let G=JSON.parse((po=P.rawContent)!=null?po:"{}");if(G.props){G.props.status="complete";let ie=fe.get($);ie!=null&&ie.markdown&&(G.props.markdown=ie.markdown)}P.rawContent=JSON.stringify(G)}catch{}fe.delete($),u(P),X.delete($)}}}else if(be==="transcript_insert"){let $=w.message;if(!$||typeof $!="object")continue;let P=String((Fs=$.id)!=null?Fs:`msg-${c()}`),G=$.role,Q={id:P,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:c()};if(u(Q),Q.rawContent)try{let Re=JSON.parse(Q.rawContent),$e=(Ra=Re==null?void 0:Re.props)==null?void 0:Ra.artifactId;typeof $e=="string"&&se.add($e)}catch{}m=null,x.current=null,Z.delete(P),ne.delete(P)}else if(be==="error"||be==="step_error"||be==="dispatch_error"||be==="flow_error"){let $=null;if(w.error instanceof Error)$=w.error;else if(be==="dispatch_error"){let P=(jr=w.message)!=null?jr:w.error;P!=null&&P!==""&&($=new Error(String(P)))}else if(be==="step_error"||be==="flow_error"){let P=w.error;typeof P=="string"&&P!==""?$=new Error(P):P!=null&&typeof P=="object"&&"message"in P&&($=new Error(String((Ba=P.message)!=null?Ba:P)))}else be==="error"&&w.error!=null&&w.error!==""&&($=new Error(String(w.error)));if($){e({type:"error",error:$});let P=m;P&&P.streaming&&(P.streaming=!1,u(P)),e({type:"status",status:"idle"})}}}}}Ge.length=0};;){let{done:q,value:ke}=await o.read();if(q)break;a+=s.decode(ke,{stream:!0});let Ce=a.split(`
11
+ `).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},fu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},hu=()=>{var e;let n=yf();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)}},yu=()=>{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"?uu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=uu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var bu=()=>{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 vu="4.1.0";var Bs=vu;var vf="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function xf(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 wf(n){switch(n){case"json":return yu;case"regex-json":return hu;case"xml":return bu;default:return fu}}var xu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Cf(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=xu(t);if(!xu(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:vf,this.headers={"Content-Type":"application/json","X-Persona-Version":Bs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:wf(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?Xp(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=Cf(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:xf(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(`
10
12
 
11
- `);a=(Sn=Ce.pop())!=null?Sn:"";for(let _e of Ce){let it=_e.split(`
12
- `),pt="message",ot="";for(let St of it)St.startsWith("event:")?pt=St.replace("event:","").trim():St.startsWith("data:")&&(ot+=St.replace("data:","").trim());if(!ot)continue;let Mt;try{Mt=JSON.parse(ot)}catch(St){e({type:"error",error:St instanceof Error?St:new Error("Failed to parse chat stream payload")});continue}let V=pt!=="message"?pt:(Ke=Mt.type)!=null?Ke:"message";if((Ft=this.onSSEEvent)==null||Ft.call(this,V,Mt),this.parseSSEEvent){x.current=m;let St=await this.handleCustomSSEEvent(Mt,e,x,u,c,E);if(x.current&&x.current!==m&&(m=x.current),St)continue}if(Ue||(ku(V)?(Pe=!0,Ue=!0):(V==="agent_start"||V==="flow_start"||V==="step_start")&&(Pe=!1,Ue=!0)),Pe){for(let St of Gt.push(V,Mt))Ge.push(St);ue();continue}Xe.push(V,Mt),ue()}}Xe.flushPending(),ue(),Xe.destroy()}};function Za(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function ea(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var ei="[Image]";function Zi(n){return{type:"text",text:n}}var Pu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yf=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qr=[...Pu,...yf];function vf(n){return Pu.includes(n)||n.startsWith("image/")}function ti(n){return vf(n.type)}async function Wu(n){return new Promise((t,e)=>{let r=new FileReader;r.onload=()=>{let o=r.result;ti(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>e(new Error("Failed to read file")),r.readAsDataURL(n)})}function Ru(n,t=Qr,e=10*1024*1024){return t.includes(n.type)?n.size>e?{valid:!1,error:`File too large. Maximum size: ${Math.round(e/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function xf(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function Bu(n,t){let e=xf(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||e||"FILE"}el();var Hu=16e3,wf=24e3,Cf=4096,Af=1380533830;function Sf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===Af?new Uint8Array(n,44):new Uint8Array(n)}function Tf(n){var r;let t=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ta=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,e=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!e)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:Hu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(x=>x.stop());return}this.mediaStream=c;let g=window.AudioContext||window.webkitAudioContext,f=new g({sampleRate:Hu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new fs(wf);if(o!==this.callGeneration){u.destroy(),c.getTracks().forEach(x=>x.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Tf(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(m,["runtype.bearer",e]);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 E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,e,r,o){let s=t.createMediaStreamSource(e);this.sourceNode=s;let a=t.createScriptProcessor(Cf,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 g=0;g<d.length;g++){let f=Math.max(-1,Math.min(1,d[g]));c[g]=f<0?f*32768:f*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,e){var o,s;if(e!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,e);return}let r;try{r=JSON.parse(t.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(t,e){if(e!==this.callGeneration||!this.playback)return;let r=Sf(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(e=>e(t))}emitError(t){this.errorCallbacks.forEach(e=>e(t))}emitTranscript(t,e,r){this.transcriptCallbacks.forEach(o=>o(t,e,r))}emitMetrics(t){this.metricsCallbacks.forEach(e=>e(t))}};var $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,e;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((e=this.config)==null?void 0:e.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(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function hs(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new ta(n.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(n.browser||{});case"custom":{let t=n.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let e=typeof t=="function"?t():t;if(!e||typeof e.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return e}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function Du(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return hs({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return hs({type:"runtype",runtype:n.runtype});if($o.isSupported())return hs({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function tl(n){try{return Du(n),!0}catch{return!1}}function ni(n){var e;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=n.find(s=>s.name===r);if(o)return o}return(e=n.find(r=>r.lang.startsWith("en")))!=null?e:n[0]}var bs=class n{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,e){var a;if(!n.isSupported()){(a=e.onError)==null||a.call(e,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ni(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=e.onEnd)==null?void 0:i.call(e)},o.onerror=i=>{var c,g;let d=i.error;d==="canceled"||d==="interrupted"?(c=e.onEnd)==null||c.call(e):(g=e.onError)==null||g.call(e,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=e.onStart)==null||i.call(e)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var na=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,e;return(e=(t=this.engine)==null?void 0:t.supportsPause)!=null?e:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,e){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,e)}async play(t,e){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"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(e,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,e;this.stop(),(e=(t=this.engine)==null?void 0:t.destroy)==null||e.call(t),this.engine=null,this.listeners.clear()}set(t,e){this.activeId=e==="idle"?null:t,this.state=e;for(let r of this.listeners)r(this.activeId,this.state)}};function nl(n){if(!n)return"";let t=Ef(n);return Nu(t!==null?t:n)}function Ef(n){let t=n.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(e&&(t=e[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Nu(n){if(!n)return"";let t=n;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
- `),t=t.replace(/\n{2,}/g,`
14
- `),t.trim()}var qu=null;var rl=()=>qu?qu():Promise.resolve().then(()=>($u(),Ou));var Lf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function If(n,t){return Lf.some(e=>n[e]!==t[e])}function Uu(n,t){let e=n instanceof Error?n:new Error(String(n));if(typeof t=="string")return t;if(typeof t=="function")return t(e);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 e.message?`${r}
13
+ `);a=(hr=Le.pop())!=null?hr:"";for(let Me of Le){let He=Me.split(`
14
+ `),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 wu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Af=["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=[...wu,...Af];function Sf(n){return wu.includes(n)||n.startsWith("image/")}function Ea(n){return Sf(n.type)}async function Cu(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 Au(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 Tf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Su(n,e){let t=Tf(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 Tu=16e3,Mf=24e3,Ef=4096,kf=1380533830;function Lf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===kf?new Uint8Array(n,44):new Uint8Array(n)}function Pf(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:Tu,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:Tu});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new os(Mf);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=`${Pf(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(Ef,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=Lf(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 Mu(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 Mu(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=If(n);return Eu(e!==null?e:n)}function If(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 Eu(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(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
15
+ `),e=e.replace(/\n{2,}/g,`
16
+ `),e.trim()}var Wu=null;var Hi=()=>Wu?Wu():Promise.resolve().then(()=>(Iu(),Pu));var Hf=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Bf(n,e){return Hf.some(t=>n[t]!==e[t])}function Ru(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);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 t.message?`${r}
15
17
 
16
- _Details: ${e.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]}),zu=(n,t="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:t,ju=n=>Vs(n)||n===Gr,si=class{constructor(t={},e){this.config=t;this.callbacks=e;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 na(()=>this.createSpeechEngine());this.handleEvent=t=>{var e,r,o,s,a,i,d,c,g,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(Vs(u.name)||u.name===Gr&&((r=(e=this.config.features)==null?void 0:e.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(f=(g=this.callbacks).onError)==null||f.call(g,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.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 Zs(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let e=(o=t.host)!=null?o:this.config.apiUrl,r=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId;!e||!r||!this.config.clientToken||rl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return tl((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,e,r;return(r=(e=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:e.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let e=bs.isSupported()?new bs({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(r=t.host)!=null?r:this.config.apiUrl,c=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId,g=this.config.clientToken,f=t.browserFallback!==!1;if(d&&c&&g)return rl().then(({RuntypeSpeechEngine:u,FallbackSpeechEngine:m})=>{let v=new u({host:d,agentId:c,clientToken:g,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&e?new m(v,e,{onFallback:x=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${x.message}`)}):v});if(f&&e)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),e}return e}setupVoice(t){var e,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=hs(o);let a=(r=((e=this.config.voiceRecognition)!=null?e:{}).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 g=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=g.id}if(c){this.pendingVoiceUserMessageId=null;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.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 g=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=g.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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var e,r,o,s,a,i,d,c,g,f;if(!((e=this.config.voiceRecognition)!=null&&e.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:(s=(o=t.runtype)==null?void 0:o.clientToken)!=null?s:this.config.clientToken,host:(i=(a=t.runtype)==null?void 0:a.host)!=null?i:this.config.apiUrl,voiceId:(d=t.runtype)==null?void 0:d.voiceId,createPlaybackEngine:(c=t.runtype)==null?void 0:c.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,e;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(e=(t=this.callbacks).onError)==null||e.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let e={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(e)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,e){return this.client.submitMessageFeedback(t,e)}async submitCSATFeedback(t,e){return this.client.submitCSATFeedback(t,e)}async submitNPSFeedback(t,e){return this.client.submitNPSFeedback(t,e)}updateConfig(t){let e={...this.config,...t};if(!If(this.config,e)){this.config=e,this.client.updateConfig(e);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=e,this.client=new Zs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:e,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g,rawContent:f}=t,m={id:a!=null?a:e==="user"?Za():e==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:e,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},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let e=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:f=!1,voiceProcessing:u,rawContent:m}=r,x={id:d!=null?d:o==="user"?Za():o==="assistant"?ea():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:f,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};e.push(x)}return this.messages=this.sortMessages([...this.messages,...e]),this.callbacks.onMessagesChanged([...this.messages]),e}injectComponentDirective(t){let{component:e,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:e,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(t,e){var c,g,f,u,m;let r=t.trim();if(!r&&(!(e!=null&&e.contentParts)||e.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=Za(),s=ea(),a={id:o,role:"user",content:r||ei,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(e==null?void 0:e.viaVoice)||!1,...(e==null?void 0:e.contentParts)&&e.contentParts.length>0&&{contentParts:e.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 E=Uu(v,this.config.errorMessage);if(E){let M={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(M)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(f=(g=this.callbacks).onError)==null||f.call(g,v):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=ea();this.setStreaming(!0);let e=new AbortController;this.abortController=e;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:e.signal,assistantMessageId:t},this.handleEvent)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let f=Uu(c,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(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(t,e){var o,s,a;if(this.streaming&&!(e!=null&&e.allowReentry))return;e!=null&&e.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(t,this.handleEvent,e==null?void 0:e.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 t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(e=>this.requestWebMcpApproval(e))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let e={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${e.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:e}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,e){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:e,resolvedAt:Date.now()}}),r(e==="approved")}async resolveApproval(t,e,r){var g,f,u,m,v;let o=`approval-${t.id}`,s={...t,status:e,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(g=a==null?void 0:a.createdAt)!=null?g: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:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},e,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},e),x){let E=null;if(x instanceof Response){if(!x.ok){let M=await x.json().catch(()=>null);throw new Error((u=M==null?void 0:M.error)!=null?u:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(e==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(m=this.callbacks).onError)==null||v.call(m,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:e.answers,askUserQuestionIndex:e.currentIndex}})}markAskUserQuestionResolved(t,e){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...e?{askUserQuestionAnswers:e}:{}}})}async resolveAskUserQuestion(t,e){var g,f,u,m,v,x,E,M,S,B,I,R;let r=this.messages.find(A=>A.id===t.id);if(((g=r==null?void 0:r.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0)return;let o=(f=t.agentMetadata)==null?void 0:f.executionId,s=(u=t.toolCall)==null?void 0:u.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof e=="string"?void 0:e;if(a===void 0&&typeof e=="string"){let A=(x=t.toolCall)==null?void 0:x.args,L=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(L.length===1){let N=typeof((E=L[0])==null?void 0:E.question)=="string"?L[0].question:"";N&&(a={[N]:e})}}this.markAskUserQuestionResolved(t,a),(M=this.abortController)==null||M.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(S=t.toolCall)==null?void 0:S.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof e=="string"?e:Object.entries(e).map(([L,N])=>`${L}: ${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((L,N)=>{let F=typeof(L==null?void 0:L.question)=="string"?L.question:"";if(!F)return;let k=A[F],z=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${N}`,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${N}`,role:"user",content:z||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:e});if(!A.ok){let L=await A.json().catch(()=>null);throw new Error((B=L==null?void 0:L.error)!=null?B:`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||(R=(I=this.callbacks).onError)==null||R.call(I,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(t){var s,a;let e=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!e||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(e);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(e,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let e of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(e)})}flushWebMcpAwaitBatch(t){let e=this.webMcpAwaitBatches.get(t);if(!e)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=e;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let e=this.messages.find(a=>a.id===t.id),r=[(o=e==null?void 0:e.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Gr)return!1;let e=this.messages.find(s=>s.id===t.id);return((o=(e!=null?e:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let e=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:e,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),e}markWebMcpToolComplete(t,e,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:e,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,e){var d,c,g,f;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(e.map(async u=>{var R,A,L,N,F,k,z;let m=(R=u.toolCall)==null?void 0:R.name,v=(A=u.toolCall)==null?void 0:A.id;if(!m||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(u),M=(N=(L=u.agentMetadata)==null?void 0:L.webMcpToolCallId)!=null?N:m;if(m===Gr)return{dedupeKey:x,resumeKey:M,output:Gi(),toolMessage:u,startedAt:E,completedAt:Date.now()};let S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let B=this.client.executeWebMcpToolCall(m,(F=u.toolCall)==null?void 0:F.args,S.signal),I;if(!B)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await B}catch(j){let re=j instanceof Error&&(j.name==="AbortError"||j.message.includes("aborted")||j.message.includes("abort"));return re||(z=(k=this.callbacks).onError)==null||z.call(k,j instanceof Error?j:new Error(String(j))),this.markWebMcpToolComplete(u,ra(re?"Aborted by cancel()":zu(j)),E),this.webMcpInflightKeys.delete(x),null}return S.signal.aborted?(this.markWebMcpToolComplete(u,ra("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:M,output:I,toolMessage:u,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let u={};for(let v of i)u[v.resumeKey]=v.output;let m=await this.client.resumeFlow(t,u,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.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)===Gr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(g=this.callbacks).onError)==null||f.call(g,u instanceof Error?u:new Error(String(u)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ra("Aborted by cancel()"),v.startedAt)}finally{for(let u of r)this.webMcpInflightKeys.delete(u);for(let u of o)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,E,M,S,B,I,R,A,L,N,F;let e=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!e){(S=(M=this.callbacks).onError)==null||S.call(M,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${e}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(e,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(z){(I=(B=this.callbacks).onError)==null||I.call(B,z instanceof Error?z:new Error(String(z)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${e}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Gr,g=(R=t.toolCall)==null?void 0:R.args,f=c?null:this.client.executeWebMcpToolCall(r,g,d),u="execute",m=a;try{let k;if(c?k=Gi():f?k=await f:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ra("Aborted by cancel()"),a);return}let z=(L=(A=t.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?L:r;u="resume",await this.resumeWithToolOutput(e,z,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,k,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let z=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(u==="execute"||z||d.aborted)&&this.markWebMcpToolComplete(t,ra(z||d.aborted?"Aborted by cancel()":zu(k)),a),z||(F=(N=this.callbacks).onError)==null||F.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(t,e,r,o){var a,i;let s=await this.client.resumeFlow(t,{[e]: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 t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let e=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:e,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(e,s),this.selectedArtifactId=e,this.emitArtifactsState(),s}let r={id:e,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(e,r),this.selectedArtifactId=e,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,e;(e=(t=this.callbacks).onArtifactsState)==null||e.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var e,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(e=t.component)!=null?e:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.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(t,e=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=e,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let e=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),e&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(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=nl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ni(t)}toggleReadAloud(t){let e=this.messages.find(s=>s.id===t);if(!e||e.role!=="assistant")return;let r=nl(e.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let e=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,e]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let e=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===e.id);if(r===-1){this.appendMessage(e);return}this.messages=this.messages.map((o,s)=>{var g,f,u,m,v,x,E,M,S,B,I,R,A,L,N;if(s!==r)return o;let a={...o,...e};if(((g=o.agentMetadata)==null?void 0:g.askUserQuestionAnswered)===!0&&e.agentMetadata&&(a.agentMetadata={...e.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=o.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&e.agentMetadata&&(a.agentMetadata={...(u=a.agentMetadata)!=null?u:e.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&e.approval&&o.approval.id===e.approval.id){let F=o.approval,k=e.approval;a.approval={...F,...k,executionId:k.executionId||F.executionId,toolName:k.toolName||F.toolName,description:k.description||F.description,toolType:(m=k.toolType)!=null?m:F.toolType,reason:(v=k.reason)!=null?v:F.reason,parameters:(x=k.parameters)!=null?x:F.parameters}}let i=(E=e.toolCall)==null?void 0:E.name,d=(M=e.agentMetadata)==null?void 0:M.executionId,c=(S=e.toolCall)==null?void 0:S.id;if(i&&ju(i)&&d&&c&&((B=e.agentMetadata)==null?void 0:B.awaitingLocalTool)===!0){let F=`${d}:${c}`,k=this.webMcpInflightKeys.has(F),z=this.webMcpResolvedKeys.has(F),j=(I=o.toolCall)==null?void 0:I.name,re=((R=o.agentMetadata)==null?void 0:R.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&j!==void 0&&ju(j)&&((L=o.toolCall)==null?void 0:L.status)==="complete";(k||z||re)&&(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(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((e,r)=>{var d,c;let o=new Date(e.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=e.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:e.id.localeCompare(r.id)})}};var C=require("lucide"),Pf={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},Se=(n,t=24,e="currentColor",r=2)=>{let o=Pf[n];return o?Wf(o,t,e,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 Wf(n,t,e,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",e),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,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}),o}var ai={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function Rf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Bf(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 oa=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var e,r,o;this.config={allowedTypes:(e=t.allowedTypes)!=null?e:ai.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ai.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ai.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ai.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var e,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(e=this.config).onFileRejected)==null||r.call(e,c,"count");continue}let g=Ru(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let f=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,f);continue}try{let f=await Wu(c),u=ti(c)?URL.createObjectURL(c):null,m={id:Rf(),file:c,previewUrl:u,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(t){var s,a,i;let e=this.attachments.findIndex(d=>d.id===t);if(e===-1)return;let r=this.attachments[e];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(e,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,e;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(e=(t=this.config).onAttachmentsChange)==null||e.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let e=ti(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",e&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Bf(t.file.type),d=Se(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Bu(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let 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=Se("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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,e){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:e})}};var Vu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function sa(n,t){if(!n)return t;if(!t)return n;let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];Vu(s)&&Vu(o)?e[r]=sa(s,o):e[r]=o}return e}var Xr="min(440px, calc(100vw - 24px))",Gu="440px",Hf={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:Xr,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)"},zt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Hf,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 Ku(n,t){if(!(!n&&!t))return n?t?sa(n,t):n:t}function Qu(n){var t,e,r,o,s,a,i,d,c,g,f,u,m,v,x,E,M,S,B,I,R;return n?{...zt,...n,theme:Ku(zt.theme,n.theme),darkTheme:Ku(zt.darkTheme,n.darkTheme),launcher:{...zt.launcher,...n.launcher,dock:{...(t=zt.launcher)==null?void 0:t.dock,...(e=n.launcher)==null?void 0:e.dock},clearChat:{...(r=zt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...zt.copy,...n.copy},sendButton:{...zt.sendButton,...n.sendButton},statusIndicator:{...zt.statusIndicator,...n.statusIndicator},voiceRecognition:{...zt.voiceRecognition,...n.voiceRecognition},features:(()=>{var oe,X,se,fe,pe,K,ae,Be,ee,Z;let A=(oe=zt.features)==null?void 0:oe.artifacts,L=(X=n.features)==null?void 0:X.artifacts,N=(se=zt.features)==null?void 0:se.scrollToBottom,F=(fe=n.features)==null?void 0:fe.scrollToBottom,k=(pe=zt.features)==null?void 0:pe.scrollBehavior,z=(K=n.features)==null?void 0:K.scrollBehavior,j=(ae=zt.features)==null?void 0:ae.streamAnimation,re=(Be=n.features)==null?void 0:Be.streamAnimation,Ie=(ee=zt.features)==null?void 0:ee.askUserQuestion,Ve=(Z=n.features)==null?void 0:Z.askUserQuestion,ve=A===void 0&&L===void 0?void 0:{...A,...L,layout:{...A==null?void 0:A.layout,...L==null?void 0:L.layout}},Ne=N===void 0&&F===void 0?void 0:{...N,...F},qe=k===void 0&&z===void 0?void 0:{...k,...z},Te=j===void 0&&re===void 0?void 0:{...j,...re},we=Ie===void 0&&Ve===void 0?void 0:{...Ie,...Ve,styles:{...Ie==null?void 0:Ie.styles,...Ve==null?void 0:Ve.styles}};return{...zt.features,...n.features,...Ne!==void 0?{scrollToBottom:Ne}:{},...qe!==void 0?{scrollBehavior:qe}:{},...ve!==void 0?{artifacts:ve}:{},...Te!==void 0?{streamAnimation:Te}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:zt.suggestionChips,suggestionChipsConfig:{...zt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...zt.layout,...n.layout,header:{...(a=zt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=zt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(f=(g=zt.layout)==null?void 0:g.messages)==null?void 0:f.avatar,...(m=(u=n.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(x=(v=zt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(M=(E=n.layout)==null?void 0:E.messages)==null?void 0:M.timestamp}},slots:{...(S=zt.layout)==null?void 0:S.slots,...(B=n.layout)==null?void 0:B.slots}},markdown:{...zt.markdown,...n.markdown,options:{...(I=zt.markdown)==null?void 0:I.options,...(R=n.markdown)==null?void 0:R.options}},messageActions:{...zt.messageActions,...n.messageActions}}:zt}var Df={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"}},Nf={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"}},Ff={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:Xr,maxWidth:Gu,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 ys(n,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let e=t.split("."),r=n;for(let o of e){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?ys(n,r):r}function Xu(n){let t={};function e(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ys(n,a);d!==void 0&&(t[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&&e(a,i)}}return e(n.palette,"palette"),e(n.semantic,"semantic"),e(n.components,"components"),t}function _f(n){let t=[],e=[];return n.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||e.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||e.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:e}}function Ju(n,t){let e={...n};for(let[r,o]of Object.entries(t)){let s=e[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?e[r]=Ju(s,o):e[r]=o}return e}function Of(n,t){return t?Ju(n,t):n}function qo(n,t={}){var o,s,a,i,d,c,g,f,u,m,v,x,E;let e={palette:Df,semantic:Nf,components:Ff},r={palette:{...e.palette,...n==null?void 0:n.palette,colors:{...e.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...e.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...e.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...e.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...e.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...e.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...e.semantic,...n==null?void 0:n.semantic,colors:{...e.semantic.colors,...(g=n==null?void 0:n.semantic)==null?void 0:g.colors,interactive:{...e.semantic.colors.interactive,...(u=(f=n==null?void 0:n.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...e.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...e.semantic.spacing,...(x=n==null?void 0:n.semantic)==null?void 0:x.spacing},typography:{...e.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Of(e.components,n==null?void 0:n.components)};if(t.validate!==!1){let M=_f(r);if(!M.valid)throw new Error(`Theme validation failed: ${M.errors.map(S=>S.message).join(", ")}`)}if(t.plugins)for(let M of t.plugins)r=M.transform(r);return r}function Yu(n){var x,E,M,S,B,I,R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe,X,se,fe,pe,K,ae,Be,ee,Z,ne,st,at,nt,Me,he,Ge,J,ue,Le,Xe,Gt,Pe,Ue,rt,Nt,yn,wr,Sn,Ke,Ft,q,ke,Ce,_e,it,pt,ot,Mt,V,St,de,me,Ee,ut,en,an,wn,Ot,et,_t,mt,tn,rr,Wn,ln,On,Cr,Ct,jn,Ar,Nr,ur,xt,Co,Sr,Ao,$n,Ko,Yr,Fr,Zr,eo,So,To,to,Tt,Vn,Kn,Rn,kt,or,sr,Gn,no,_r,ro,Qn,$t,Bn,ar,oo,Or,so,Tr,Xn;let t=Xu(n),e={};for(let[ye,gt]of Object.entries(t)){let rn=ye.replace(/\./g,"-");e[`--persona-${rn}`]=gt.value}e["--persona-primary"]=(x=e["--persona-semantic-colors-primary"])!=null?x:e["--persona-palette-colors-primary-500"],e["--persona-secondary"]=(E=e["--persona-semantic-colors-secondary"])!=null?E:e["--persona-palette-colors-secondary-500"],e["--persona-accent"]=(M=e["--persona-semantic-colors-accent"])!=null?M:e["--persona-palette-colors-accent-500"],e["--persona-surface"]=(S=e["--persona-semantic-colors-surface"])!=null?S:e["--persona-palette-colors-gray-50"],e["--persona-background"]=(B=e["--persona-semantic-colors-background"])!=null?B:e["--persona-palette-colors-gray-50"],e["--persona-container"]=(I=e["--persona-semantic-colors-container"])!=null?I:e["--persona-palette-colors-gray-100"],e["--persona-text"]=(R=e["--persona-semantic-colors-text"])!=null?R:e["--persona-palette-colors-gray-900"],e["--persona-text-muted"]=(A=e["--persona-semantic-colors-text-muted"])!=null?A:e["--persona-palette-colors-gray-500"],e["--persona-text-inverse"]=(L=e["--persona-semantic-colors-text-inverse"])!=null?L:e["--persona-palette-colors-gray-50"],e["--persona-border"]=(N=e["--persona-semantic-colors-border"])!=null?N:e["--persona-palette-colors-gray-200"],e["--persona-divider"]=(F=e["--persona-semantic-colors-divider"])!=null?F:e["--persona-palette-colors-gray-200"],e["--persona-muted"]=e["--persona-text-muted"],e["--persona-voice-recording-indicator"]=(k=e["--persona-components-voice-recording-indicator"])!=null?k:e["--persona-palette-colors-error-500"],e["--persona-voice-recording-bg"]=(z=e["--persona-components-voice-recording-background"])!=null?z:e["--persona-palette-colors-error-50"],e["--persona-voice-processing-icon"]=(j=e["--persona-components-voice-processing-icon"])!=null?j:e["--persona-palette-colors-primary-500"],e["--persona-voice-speaking-icon"]=(re=e["--persona-components-voice-speaking-icon"])!=null?re:e["--persona-palette-colors-success-500"],e["--persona-approval-bg"]=(Ie=e["--persona-components-approval-requested-background"])!=null?Ie:e["--persona-palette-colors-warning-50"],e["--persona-approval-border"]=(Ve=e["--persona-components-approval-requested-border"])!=null?Ve:e["--persona-palette-colors-warning-200"],e["--persona-approval-text"]=(ve=e["--persona-components-approval-requested-text"])!=null?ve:e["--persona-palette-colors-gray-900"],e["--persona-approval-shadow"]=(Ne=e["--persona-components-approval-requested-shadow"])!=null?Ne:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-approval-approve-bg"]=(qe=e["--persona-components-approval-approve-background"])!=null?qe:e["--persona-palette-colors-success-500"],e["--persona-approval-deny-bg"]=(Te=e["--persona-components-approval-deny-background"])!=null?Te:e["--persona-palette-colors-error-500"],e["--persona-attachment-image-bg"]=(we=e["--persona-components-attachment-image-background"])!=null?we:e["--persona-palette-colors-gray-100"],e["--persona-attachment-image-border"]=(oe=e["--persona-components-attachment-image-border"])!=null?oe:e["--persona-palette-colors-gray-200"],e["--persona-font-family"]=(X=e["--persona-semantic-typography-fontFamily"])!=null?X:e["--persona-palette-typography-fontFamily-sans"],e["--persona-font-size"]=(se=e["--persona-semantic-typography-fontSize"])!=null?se:e["--persona-palette-typography-fontSize-base"],e["--persona-font-weight"]=(fe=e["--persona-semantic-typography-fontWeight"])!=null?fe:e["--persona-palette-typography-fontWeight-normal"],e["--persona-line-height"]=(pe=e["--persona-semantic-typography-lineHeight"])!=null?pe:e["--persona-palette-typography-lineHeight-normal"],e["--persona-input-font-family"]=e["--persona-font-family"],e["--persona-input-font-weight"]=e["--persona-font-weight"],e["--persona-radius-sm"]=(K=e["--persona-palette-radius-sm"])!=null?K:"0.125rem",e["--persona-radius-md"]=(ae=e["--persona-palette-radius-md"])!=null?ae:"0.375rem",e["--persona-radius-lg"]=(Be=e["--persona-palette-radius-lg"])!=null?Be:"0.5rem",e["--persona-radius-xl"]=(ee=e["--persona-palette-radius-xl"])!=null?ee:"0.75rem",e["--persona-radius-full"]=(Z=e["--persona-palette-radius-full"])!=null?Z:"9999px",e["--persona-launcher-radius"]=(st=(ne=e["--persona-components-launcher-borderRadius"])!=null?ne:e["--persona-palette-radius-full"])!=null?st:"9999px",e["--persona-launcher-bg"]=(at=e["--persona-components-launcher-background"])!=null?at:e["--persona-primary"],e["--persona-launcher-fg"]=(nt=e["--persona-components-launcher-foreground"])!=null?nt:e["--persona-text-inverse"],e["--persona-launcher-border"]=(Me=e["--persona-components-launcher-border"])!=null?Me:e["--persona-border"],e["--persona-button-primary-bg"]=(he=e["--persona-components-button-primary-background"])!=null?he:e["--persona-primary"],e["--persona-button-primary-fg"]=(Ge=e["--persona-components-button-primary-foreground"])!=null?Ge:e["--persona-text-inverse"],e["--persona-button-radius"]=(ue=(J=e["--persona-components-button-primary-borderRadius"])!=null?J:e["--persona-palette-radius-full"])!=null?ue:"9999px",e["--persona-panel-radius"]=(Xe=(Le=e["--persona-components-panel-borderRadius"])!=null?Le:e["--persona-radius-xl"])!=null?Xe:"0.75rem",e["--persona-panel-border"]=(Gt=e["--persona-components-panel-border"])!=null?Gt:`1px solid ${e["--persona-border"]}`,e["--persona-panel-shadow"]=(Ue=(Pe=e["--persona-components-panel-shadow"])!=null?Pe:e["--persona-palette-shadows-xl"])!=null?Ue:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",e["--persona-launcher-shadow"]=(rt=e["--persona-components-launcher-shadow"])!=null?rt:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",e["--persona-input-radius"]=(yn=(Nt=e["--persona-components-input-borderRadius"])!=null?Nt:e["--persona-radius-lg"])!=null?yn:"0.5rem",e["--persona-message-user-radius"]=(Sn=(wr=e["--persona-components-message-user-borderRadius"])!=null?wr:e["--persona-radius-lg"])!=null?Sn:"0.5rem",e["--persona-message-assistant-radius"]=(Ft=(Ke=e["--persona-components-message-assistant-borderRadius"])!=null?Ke:e["--persona-radius-lg"])!=null?Ft:"0.5rem",e["--persona-header-bg"]=(q=e["--persona-components-header-background"])!=null?q:e["--persona-surface"],e["--persona-header-border"]=(ke=e["--persona-components-header-border"])!=null?ke:e["--persona-divider"],e["--persona-header-icon-bg"]=(Ce=e["--persona-components-header-iconBackground"])!=null?Ce:e["--persona-primary"],e["--persona-header-icon-fg"]=(_e=e["--persona-components-header-iconForeground"])!=null?_e:e["--persona-text-inverse"],e["--persona-header-title-fg"]=(it=e["--persona-components-header-titleForeground"])!=null?it:e["--persona-primary"],e["--persona-header-subtitle-fg"]=(pt=e["--persona-components-header-subtitleForeground"])!=null?pt:e["--persona-text-muted"],e["--persona-header-action-icon-fg"]=(ot=e["--persona-components-header-actionIconForeground"])!=null?ot:e["--persona-muted"];let r=(Mt=n.components)==null?void 0:Mt.header;r!=null&&r.shadow&&(e["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(e["--persona-header-border-bottom"]=r.borderBottom);let o=(V=n.components)==null?void 0:V.introCard;e["--persona-intro-card-bg"]=(St=e["--persona-components-introCard-background"])!=null?St:e["--persona-surface"],e["--persona-intro-card-radius"]=(de=e["--persona-components-introCard-borderRadius"])!=null?de:"1rem",e["--persona-intro-card-padding"]=(me=e["--persona-components-introCard-padding"])!=null?me:"1.5rem",e["--persona-intro-card-shadow"]=(ut=(Ee=o==null?void 0:o.shadow)!=null?Ee:e["--persona-components-introCard-shadow"])!=null?ut:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-input-background"]=(en=e["--persona-components-input-background"])!=null?en:e["--persona-surface"],e["--persona-input-placeholder"]=(an=e["--persona-components-input-placeholder"])!=null?an:e["--persona-text-muted"],e["--persona-message-user-bg"]=(wn=e["--persona-components-message-user-background"])!=null?wn:e["--persona-accent"],e["--persona-message-user-text"]=(Ot=e["--persona-components-message-user-text"])!=null?Ot:e["--persona-text-inverse"],e["--persona-message-user-shadow"]=(et=e["--persona-components-message-user-shadow"])!=null?et:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-message-assistant-bg"]=(_t=e["--persona-components-message-assistant-background"])!=null?_t:e["--persona-surface"],e["--persona-message-assistant-text"]=(mt=e["--persona-components-message-assistant-text"])!=null?mt:e["--persona-text"],e["--persona-message-assistant-border"]=(tn=e["--persona-components-message-assistant-border"])!=null?tn:e["--persona-border"],e["--persona-message-assistant-shadow"]=(rr=e["--persona-components-message-assistant-shadow"])!=null?rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-bg"]=(ln=(Wn=e["--persona-components-scrollToBottom-background"])!=null?Wn:e["--persona-button-primary-bg"])!=null?ln:e["--persona-accent"],e["--persona-scroll-to-bottom-fg"]=(Cr=(On=e["--persona-components-scrollToBottom-foreground"])!=null?On:e["--persona-button-primary-fg"])!=null?Cr:e["--persona-text-inverse"],e["--persona-scroll-to-bottom-border"]=(Ct=e["--persona-components-scrollToBottom-border"])!=null?Ct:e["--persona-primary"],e["--persona-scroll-to-bottom-size"]=(jn=e["--persona-components-scrollToBottom-size"])!=null?jn:"40px",e["--persona-scroll-to-bottom-radius"]=(ur=(Nr=(Ar=e["--persona-components-scrollToBottom-borderRadius"])!=null?Ar:e["--persona-button-radius"])!=null?Nr:e["--persona-radius-full"])!=null?ur:"9999px",e["--persona-scroll-to-bottom-shadow"]=(Co=(xt=e["--persona-components-scrollToBottom-shadow"])!=null?xt:e["--persona-palette-shadows-sm"])!=null?Co:"0 1px 2px 0 rgb(0 0 0 / 0.05)",e["--persona-scroll-to-bottom-padding"]=(Sr=e["--persona-components-scrollToBottom-padding"])!=null?Sr:"0.5rem 0.875rem",e["--persona-scroll-to-bottom-gap"]=(Ao=e["--persona-components-scrollToBottom-gap"])!=null?Ao:"0.5rem",e["--persona-scroll-to-bottom-font-size"]=(Ko=($n=e["--persona-components-scrollToBottom-fontSize"])!=null?$n:e["--persona-palette-typography-fontSize-sm"])!=null?Ko:"0.875rem",e["--persona-scroll-to-bottom-icon-size"]=(Yr=e["--persona-components-scrollToBottom-iconSize"])!=null?Yr:"14px",e["--persona-tool-bubble-shadow"]=(Fr=e["--persona-components-toolBubble-shadow"])!=null?Fr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-reasoning-bubble-shadow"]=(Zr=e["--persona-components-reasoningBubble-shadow"])!=null?Zr:"0 5px 15px rgba(15, 23, 42, 0.08)",e["--persona-composer-shadow"]=(eo=e["--persona-components-composer-shadow"])!=null?eo:"none",e["--persona-md-inline-code-bg"]=(So=e["--persona-components-markdown-inlineCode-background"])!=null?So:e["--persona-container"],e["--persona-md-inline-code-color"]=(To=e["--persona-components-markdown-inlineCode-foreground"])!=null?To:e["--persona-text"],e["--persona-md-link-color"]=(Tt=(to=e["--persona-components-markdown-link-foreground"])!=null?to:e["--persona-accent"])!=null?Tt:"#0f0f0f";let s=e["--persona-components-markdown-heading-h1-fontSize"];s&&(e["--persona-md-h1-size"]=s);let a=e["--persona-components-markdown-heading-h1-fontWeight"];a&&(e["--persona-md-h1-weight"]=a);let i=e["--persona-components-markdown-heading-h2-fontSize"];i&&(e["--persona-md-h2-size"]=i);let d=e["--persona-components-markdown-heading-h2-fontWeight"];d&&(e["--persona-md-h2-weight"]=d);let c=e["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(e["--persona-md-prose-font-family"]=c),e["--persona-md-code-block-bg"]=(Vn=e["--persona-components-markdown-codeBlock-background"])!=null?Vn:e["--persona-container"],e["--persona-md-code-block-border-color"]=(Kn=e["--persona-components-markdown-codeBlock-borderColor"])!=null?Kn:e["--persona-border"],e["--persona-md-code-block-text-color"]=(Rn=e["--persona-components-markdown-codeBlock-textColor"])!=null?Rn:"inherit",e["--persona-md-table-header-bg"]=(kt=e["--persona-components-markdown-table-headerBackground"])!=null?kt:e["--persona-container"],e["--persona-md-table-border-color"]=(or=e["--persona-components-markdown-table-borderColor"])!=null?or:e["--persona-border"],e["--persona-md-hr-color"]=(sr=e["--persona-components-markdown-hr-color"])!=null?sr:e["--persona-divider"],e["--persona-md-blockquote-border-color"]=(Gn=e["--persona-components-markdown-blockquote-borderColor"])!=null?Gn:e["--persona-palette-colors-gray-900"],e["--persona-md-blockquote-bg"]=(no=e["--persona-components-markdown-blockquote-background"])!=null?no:"transparent",e["--persona-md-blockquote-text-color"]=(_r=e["--persona-components-markdown-blockquote-textColor"])!=null?_r:e["--persona-palette-colors-gray-500"],e["--cw-container"]=(ro=e["--persona-components-collapsibleWidget-container"])!=null?ro:e["--persona-surface"],e["--cw-surface"]=(Qn=e["--persona-components-collapsibleWidget-surface"])!=null?Qn:e["--persona-surface"],e["--cw-border"]=($t=e["--persona-components-collapsibleWidget-border"])!=null?$t:e["--persona-border"],e["--persona-message-border"]=(Bn=e["--persona-components-message-border"])!=null?Bn:e["--persona-border"];let g=n.components,f=g==null?void 0:g.iconButton;f&&(f.background&&(e["--persona-icon-btn-bg"]=f.background),f.border&&(e["--persona-icon-btn-border"]=f.border),f.color&&(e["--persona-icon-btn-color"]=f.color),f.padding&&(e["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(e["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(e["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(e["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(e["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(e["--persona-icon-btn-active-border"]=f.activeBorder));let u=g==null?void 0:g.labelButton;u&&(u.background&&(e["--persona-label-btn-bg"]=u.background),u.border&&(e["--persona-label-btn-border"]=u.border),u.color&&(e["--persona-label-btn-color"]=u.color),u.padding&&(e["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(e["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(e["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(e["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(e["--persona-label-btn-gap"]=u.gap));let m=g==null?void 0:g.toggleGroup;m&&(m.gap&&(e["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(e["--persona-toggle-group-radius"]=m.borderRadius));let v=g==null?void 0:g.artifact;if(v!=null&&v.toolbar){let ye=v.toolbar;ye.iconHoverColor&&(e["--persona-artifact-toolbar-icon-hover-color"]=ye.iconHoverColor),ye.iconHoverBackground&&(e["--persona-artifact-toolbar-icon-hover-bg"]=ye.iconHoverBackground),ye.iconPadding&&(e["--persona-artifact-toolbar-icon-padding"]=ye.iconPadding),ye.iconBorderRadius&&(e["--persona-artifact-toolbar-icon-radius"]=ye.iconBorderRadius),ye.iconBorder&&(e["--persona-artifact-toolbar-icon-border"]=ye.iconBorder),ye.toggleGroupGap&&(e["--persona-artifact-toolbar-toggle-group-gap"]=ye.toggleGroupGap),ye.toggleBorderRadius&&(e["--persona-artifact-toolbar-toggle-radius"]=ye.toggleBorderRadius),ye.copyBackground&&(e["--persona-artifact-toolbar-copy-bg"]=ye.copyBackground),ye.copyBorder&&(e["--persona-artifact-toolbar-copy-border"]=ye.copyBorder),ye.copyColor&&(e["--persona-artifact-toolbar-copy-color"]=ye.copyColor),ye.copyBorderRadius&&(e["--persona-artifact-toolbar-copy-radius"]=ye.copyBorderRadius),ye.copyPadding&&(e["--persona-artifact-toolbar-copy-padding"]=ye.copyPadding),ye.copyMenuBackground&&(e["--persona-artifact-toolbar-copy-menu-bg"]=ye.copyMenuBackground,e["--persona-dropdown-bg"]=(ar=e["--persona-dropdown-bg"])!=null?ar:ye.copyMenuBackground),ye.copyMenuBorder&&(e["--persona-artifact-toolbar-copy-menu-border"]=ye.copyMenuBorder,e["--persona-dropdown-border"]=(oo=e["--persona-dropdown-border"])!=null?oo:ye.copyMenuBorder),ye.copyMenuShadow&&(e["--persona-artifact-toolbar-copy-menu-shadow"]=ye.copyMenuShadow,e["--persona-dropdown-shadow"]=(Or=e["--persona-dropdown-shadow"])!=null?Or:ye.copyMenuShadow),ye.copyMenuBorderRadius&&(e["--persona-artifact-toolbar-copy-menu-radius"]=ye.copyMenuBorderRadius,e["--persona-dropdown-radius"]=(so=e["--persona-dropdown-radius"])!=null?so:ye.copyMenuBorderRadius),ye.copyMenuItemHoverBackground&&(e["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ye.copyMenuItemHoverBackground,e["--persona-dropdown-item-hover-bg"]=(Tr=e["--persona-dropdown-item-hover-bg"])!=null?Tr:ye.copyMenuItemHoverBackground),ye.iconBackground&&(e["--persona-artifact-toolbar-icon-bg"]=ye.iconBackground),ye.toolbarBorder&&(e["--persona-artifact-toolbar-border"]=ye.toolbarBorder)}if(v!=null&&v.tab){let ye=v.tab;ye.background&&(e["--persona-artifact-tab-bg"]=ye.background),ye.activeBackground&&(e["--persona-artifact-tab-active-bg"]=ye.activeBackground),ye.activeBorder&&(e["--persona-artifact-tab-active-border"]=ye.activeBorder),ye.borderRadius&&(e["--persona-artifact-tab-radius"]=ye.borderRadius),ye.textColor&&(e["--persona-artifact-tab-color"]=ye.textColor),ye.hoverBackground&&(e["--persona-artifact-tab-hover-bg"]=ye.hoverBackground),ye.listBackground&&(e["--persona-artifact-tab-list-bg"]=ye.listBackground),ye.listBorderColor&&(e["--persona-artifact-tab-list-border-color"]=ye.listBorderColor),ye.listPadding&&(e["--persona-artifact-tab-list-padding"]=ye.listPadding)}if(v!=null&&v.pane){let ye=v.pane;if(ye.toolbarBackground){let gt=(Xn=ys(n,ye.toolbarBackground))!=null?Xn:ye.toolbarBackground;e["--persona-artifact-toolbar-bg"]=gt}}return e}var $f={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"}}},Zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},ol=()=>{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"},qf=n=>{var e;let t=(e=n==null?void 0:n.colorScheme)!=null?e:"light";return t==="light"?"light":t==="dark"?"dark":ol()},Uf=n=>qf(n),zf=n=>qo(n),jf=n=>{var e;let t=qo(void 0,{validate:!1});return qo({...n,palette:{...t.palette,colors:{...$f.colors,...(e=n==null?void 0:n.palette)==null?void 0:e.colors}}},{validate:!1})},ii=n=>{let t=Uf(n),e=Zu(n==null?void 0:n.theme),r=Zu(n==null?void 0:n.darkTheme);return t==="dark"?jf(sa(e!=null?e:{},r!=null?r:{})):zf(e)},Vf=n=>Yu(n),vs=(n,t)=>{let e=ii(t),r=Vf(e);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},em=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let e=new MutationObserver(()=>{n(ol())});e.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>e.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let e=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(ol());e.addEventListener?(e.addEventListener("change",r),t.push(()=>e.removeEventListener("change",r))):e.addListener&&(e.addListener(r),t.push(()=>e.removeListener(r)))}return()=>{t.forEach(e=>e())}};var tm=require("idiomorph"),li=(n,t,e={})=>{let{preserveTypingAnimation:r=!0}=e;tm.Idiomorph.morph(n,t.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 ci={index:-1,draft:""};function nm(n){let{direction:t,history:e,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(e.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=e.length-1;return{handled:!0,value:e[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<e.length-1){let i=s.index+1;return{handled:!0,value:e[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ci}}}function rm(n,t){var e,r,o,s,a,i,d,c,g,f,u,m,v,x,E,M,S,B,I,R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe,X,se;return[n.id,n.role,(r=(e=n.content)==null?void 0:e.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,(g=(c=n.llmContent)==null?void 0:c.length)!=null?g:0,(u=(f=n.approval)==null?void 0:f.status)!=null?u:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(E=(x=n.toolCall)==null?void 0:x.name)!=null?E:"",(B=(S=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:S.length)!=null?B:0,(L=(A=(R=(I=n.toolCall)==null?void 0:I.chunks)==null?void 0:R[n.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?L:"",typeof((N=n.toolCall)==null?void 0:N.args)=="string"?n.toolCall.args.length:(F=n.toolCall)!=null&&F.args?JSON.stringify(n.toolCall.args).length:0,(j=(z=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:z.length)!=null?j:0,(ve=(Ve=(Ie=(re=n.reasoning)==null?void 0:re.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:Ve.length)!=null?ve:0,(we=(Te=(qe=(Ne=n.reasoning)==null?void 0:Ne.chunks)==null?void 0:qe[n.reasoning.chunks.length-1])==null?void 0:Te.slice(-32))!=null?we:"",(X=(oe=n.contentParts)==null?void 0:oe.length)!=null?X:0,(se=n.stopReason)!=null?se:"",t].join("\0")}function om(){return new Map}function sm(n,t,e){let r=n.get(t);return r&&r.fingerprint===e?r.wrapper:null}function am(n,t,e,r){n.set(t,{fingerprint:e,wrapper:r})}function im(n,t){for(let e of n.keys())t.has(e)||n.delete(e)}function di(n=!0){let t=n;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Jr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function Uo(n,t){return Jr(n)-n.scrollTop<=t}function pi(n){let{following:t,currentScrollTop:e,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,g=e-r;return a||Math.abs(g)<s?{action:"none",delta:g,nextLastScrollTop:e}:!t&&o&&(!c||g>0)?{action:"resume",delta:g,nextLastScrollTop:e}:t&&i&&g<0?{action:"pause",delta:g,nextLastScrollTop:e}:t&&d&&!o?{action:"pause",delta:g,nextLastScrollTop:e}:{action:"none",delta:g,nextLastScrollTop:e}}function ui(n){let{following:t,deltaY:e,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return t&&e<0?"pause":!t&&o&&e>0&&r?"resume":"none"}function lm(n,t){return!n||n.isCollapsed?!1:t.contains(n.anchorNode)||t.contains(n.focusNode)}function cm(n){let t=Math.max(0,n.anchorOffsetTop-n.topOffset),e=Math.max(0,t+n.viewportHeight-n.contentHeight);return{targetScrollTop:t,spacerHeight:e}}function dm(n){let t=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-t)}var Ln={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},In=1e5,xo=In+1;var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Kf=["pre","code","a","script","style"],mi=n=>{var t,e,r,o,s;return{type:(t=n==null?void 0:n.type)!=null?t:aa.type,placeholder:(e=n==null?void 0:n.placeholder)!=null?e:aa.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:aa.speed,duration:(o=n==null?void 0:n.duration)!=null?o:aa.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:aa.buffer}},Gf=[{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"}],um=new Map;for(let n of Gf)um.set(n.name,n);var ia=(n,t)=>{var e,r;return n==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,n)?(e=t[n])!=null?e:null:(r=um.get(n))!=null?r:null},gi=(n,t,e,r,o)=>{if(!o)return n;if(e!=null&&e.bufferContent)return e.bufferContent(n,r);if(!n)return n;if(t==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(t==="line"){let s=n.lastIndexOf(`
17
- `);return s<0?"":n.slice(0,s)}return n},Qf=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${e}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Xf=(n,t,e,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${e}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},sl=/\s/,Jf=(n,t)=>{let e=n.parentNode;for(;e;){if(e.nodeType===1){let r=e;if(t.has(r.tagName.toLowerCase()))return!0}e=e.parentNode}return!1},Yf=(n,t,e)=>{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(sl.test(s[i])){let c=i;for(;c<s.length&&sl.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 g=i;for(;g<s.length&&!sl.test(s[g]);)c.appendChild(Qf(r,s[g],t,e.value)),e.value+=1,g+=1;a.appendChild(c),i=g}o.replaceChild(a,n)},Zf=(n,t,e)=>{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(Xf(r,c,t,e.value)),e.value+=1));o.replaceChild(a,n)},la=(n,t,e,r)=>{var f,u;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:Kf).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Jf(d,s)||i.push(d),d=a.nextNode();let c={value:(u=r==null?void 0:r.startIndex)!=null?u:0},g=t==="char"?Yf:Zf;for(let m of i)g(m,e,c);return o.innerHTML},fi=(n=document)=>{let t=n.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ca=(n=document)=>{let t=n.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let e=n.createElement("div");return e.className="persona-stream-skeleton-line",t.appendChild(e),t},pm=new WeakMap,eh=(n,t)=>{var s;if(!n.styles)return;let e=pm.get(t);if(e||(e=new Set,pm.set(t,e)),e.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;e.delete(n.name)}e.add(n.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,t.appendChild(o)},al=new WeakMap,th=(n,t)=>{if(!n.onAttach)return;let e=al.get(t);if(e||(e=new Map,al.set(t,e)),e.has(n.name))return;let r=n.onAttach(t);e.set(n.name,r)},mm=n=>{let t=al.get(n);if(t){for(let e of t.values())typeof e=="function"&&e();t.clear()}},il=(n,t)=>{eh(n,t),th(n,t)};function ll(n,t=In){let e=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(t),n.style.isolation="isolate",()=>{a&&(n.style.position=e),n.style.zIndex=r,n.style.isolation=o}}var da=0,wo=null;function cl(n=document){var e;if(da++,da===1){let r=n.body,s=((e=n.defaultView)!=null?e:window).scrollY||n.documentElement.scrollTop;wo={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 t=!1;return()=>{var r;if(!t&&(t=!0,da=Math.max(0,da-1),da===0&&wo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=wo.originalOverflow,o.style.position=wo.originalPosition,o.style.top=wo.originalTop,o.style.width=wo.originalWidth,s.scrollTo(0,wo.scrollY),wo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},An=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="docked"},ua=n=>{var t,e;return((e=(t=n==null?void 0:n.launcher)==null?void 0:t.mountMode)!=null?e:"floating")==="composer-bar"},vr=n=>{var e,r,o,s,a,i;let t=(e=n==null?void 0:n.launcher)==null?void 0:e.dock;return{side:(r=t==null?void 0:t.side)!=null?r:pa.side,width:(o=t==null?void 0:t.width)!=null?o:pa.width,animate:(s=t==null?void 0:t.animate)!=null?s:pa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:pa.maxHeight}};var xr={"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 nh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",hi=(n,t={})=>{var E,M,S,B,I,R;let{showClose:e=!0,wrapperClassName:r=nh,buttonSize:o,iconSize:s="28px"}=t,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(M=o!=null?o:a.closeButtonSize)!=null?M:"32px",d=y("div",r),c=(S=a.closeButtonTooltipText)!=null?S:"Close chat",g=(B=a.closeButtonShowTooltip)!=null?B:!0,f=(I=a.closeButtonIconName)!=null?I:"x",u=(R=a.closeButtonIconText)!=null?R:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=It("button",{className:Ks("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:e?void 0:"none",color:a.closeButtonColor||_n.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}}),x=Se(f,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=u,d.appendChild(v),g&&c){let A=null,L=()=>{if(A)return;let F=v.ownerDocument,k=F.body;if(!k)return;A=Dr(F,"div","persona-clear-chat-tooltip"),A.textContent=c;let z=Dr(F,"div");z.className="persona-clear-chat-tooltip-arrow",A.appendChild(z);let j=v.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(xo),A.style.left=`${j.left+j.width/2}px`,A.style.top=`${j.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",L),d.addEventListener("mouseleave",N),v.addEventListener("focus",L),v.addEventListener("blur",N),d._cleanupTooltip=()=>{N(),d.removeEventListener("mouseenter",L),d.removeEventListener("mouseleave",N),v.removeEventListener("focus",L),v.removeEventListener("blur",N)}}return{button:v,wrapper:d}},rh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bi=(n,t={})=>{var A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe;let{wrapperClassName:e=rh,buttonSize:r,iconSize:o="20px"}=t,a=(L=((A=n==null?void 0:n.launcher)!=null?A:{}).clearChat)!=null?L:{},i=(N=r!=null?r:a.size)!=null?N:"32px",d=(F=a.iconName)!=null?F:"refresh-cw",c=(k=a.iconColor)!=null?k:"",g=(z=a.backgroundColor)!=null?z:"",f=(j=a.borderWidth)!=null?j:"",u=(re=a.borderColor)!=null?re:"",m=(Ie=a.borderRadius)!=null?Ie:"",v=(Ve=a.paddingX)!=null?Ve:"",x=(ve=a.paddingY)!=null?ve:"",E=(Ne=a.tooltipText)!=null?Ne:"Clear chat",M=(qe=a.showTooltip)!=null?qe:!0,S=y("div",e),B=!!(f||u),I=It("button",{className:Ks("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!g&&"hover:persona-bg-gray-100",!B&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||_n.actionIconColor,backgroundColor:g||void 0,border:B?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),R=Se(d,o,"currentColor",1);if(R&&(R.style.display="block",I.appendChild(R)),S.appendChild(I),M&&E){let Te=null,we=()=>{if(Te)return;let X=I.ownerDocument,se=X.body;if(!se)return;Te=Dr(X,"div","persona-clear-chat-tooltip"),Te.textContent=E;let fe=Dr(X,"div");fe.className="persona-clear-chat-tooltip-arrow",Te.appendChild(fe);let pe=I.getBoundingClientRect();Te.style.position="fixed",Te.style.zIndex=String(xo),Te.style.left=`${pe.left+pe.width/2}px`,Te.style.top=`${pe.top-8}px`,Te.style.transform="translate(-50%, -100%)",se.appendChild(Te)},oe=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};S.addEventListener("mouseenter",we),S.addEventListener("mouseleave",oe),I.addEventListener("focus",we),I.addEventListener("blur",oe),S._cleanupTooltip=()=>{oe(),S.removeEventListener("mouseenter",we),S.removeEventListener("mouseleave",oe),I.removeEventListener("focus",we),I.removeEventListener("blur",oe)}}return{button:I,wrapper:S}};var _n={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))"},zo=n=>{var R,A,L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we;let{config:t,showClose:e=!0}=n,r=It("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=t==null?void 0:t.launcher)!=null?R:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(L=o.closeButtonPlacement)!=null?L:"inline",i=(N=o.headerIconHidden)!=null?N:!1,d=o.headerIconName,c=It("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 oe=parseFloat(s)||24,X=Se(d,oe*.6,"currentColor",1);X?c.replaceChildren(X):c.textContent=(k=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?k:"\u{1F4AC}"}else if((z=t==null?void 0:t.launcher)!=null&&z.iconUrl){let oe=y("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(re=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?re:"\u{1F4AC}";let g=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=It("span",{className:"persona-text-base persona-font-semibold",text:(Ve=(Ie=t==null?void 0:t.launcher)==null?void 0:Ie.title)!=null?Ve:"Chat Assistant",style:{color:_n.titleColor}}),u=It("span",{className:"persona-text-xs",text:(Ne=(ve=t==null?void 0:t.launcher)==null?void 0:ve.subtitle)!=null?Ne:"Here to help you get answers fast",style:{color:_n.subtitleColor}});g.append(f,u),i?r.append(g):r.append(c,g);let m=(qe=o.clearChat)!=null?qe:{},v=(Te=m.enabled)!=null?Te:!0,x=(we=m.placement)!=null?we:"inline",E=null,M=null;if(v){let X=bi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=X.button,M=X.wrapper,x==="top-right"&&(M.style.right="48px"),x==="inline"&&r.appendChild(M)}let S=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:B,wrapper:I}=hi(t,{showClose:e,wrapperClassName:S});return a!=="top-right"&&r.appendChild(I),{header:r,iconHolder:c,headerTitle:f,headerSubtitle:u,closeButton:B,closeButtonWrapper:I,clearChatButton:E,clearChatButtonWrapper:M}},ma=(n,t,e)=>{var a,i,d,c;let r=(a=e==null?void 0:e.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(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};function xs(n){let{items:t,onSelect:e,anchor:r,position:o="bottom-left",portal:s}=n,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(xo)):(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 t){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let E=Se(m.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=m.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),g(),e(m.id)}),a.appendChild(v)}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=v=>{!a.contains(v.target)&&!r.contains(v.target)&&g()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function g(){a.classList.add("persona-hidden"),i==null||i(),i=null}function f(){a.classList.contains("persona-hidden")?c():g()}function u(){g(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:g,toggle:f,destroy:u}}function Pn(n){let{icon:t,label:e,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",e),d.title=e;let c=Se(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[g,f]of Object.entries(i))d.setAttribute(g,f);return d}function dl(n){let{icon:t,label:e,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 g=y("button",c);if(g.type="button",g.setAttribute("aria-label",e),t){let u=Se(t,s!=null?s:14,"currentColor",2);u&&g.appendChild(u)}let f=y("span");if(f.textContent=e,g.appendChild(f),i&&g.addEventListener("click",i),d)for(let[u,m]of Object.entries(d))g.setAttribute(u,m);return g}function gm(n){var m,v;let{label:t,icon:e="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let g=y("span","persona-combo-btn-label");g.textContent=t,c.appendChild(g);let f=Se(e,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=(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,E;c.style.backgroundColor=(x=d.background)!=null?x:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let u=xs({items:r,onSelect:x=>{c.setAttribute("aria-expanded","false"),o(x)},anchor:c,position:s,portal:a});return a||c.appendChild(u.element),c.addEventListener("click",x=>{x.stopPropagation();let E=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),u.toggle()}),c.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),c.click())}),{element:c,setLabel:x=>{g.textContent=x,c.setAttribute("aria-label",x)},open:()=>{c.setAttribute("aria-expanded","true"),u.show()},close:()=>{c.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let x=!u.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",x?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),c.remove()}}}var oh=n=>{var r;let t=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),e=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(e){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>e()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),e())}))}return t};function sh(n,t,e){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=Se(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=xs({items:a.menuItems,onSelect:g=>e==null?void 0:e(g),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",g=>{g.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>e==null?void 0:e(a.id)),n.appendChild(i)}}var ah=n=>{var S,B,I,R,A,L,N,F,k;let{config:t,showClose:e=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(S=t==null?void 0:t.launcher)!=null?S:{},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,g;if(d)c=gm({label:(B=a.title)!=null?B:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=_n.titleColor,g=(I=c.querySelector(".persona-combo-btn-label"))!=null?I:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),g=y("span","persona-text-base persona-font-semibold persona-truncate"),g.style.color=_n.titleColor,g.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(g),sh(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 j=o.onTitleClick;c.addEventListener("click",re=>{re.target.closest("button")||j()}),c.addEventListener("keydown",re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),j())})}let z=o==null?void 0:o.titleRowHover;z&&(c.style.borderRadius=(L=z.borderRadius)!=null?L:"10px",c.style.padding=(N=z.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 j,re;c.style.backgroundColor=(j=z.background)!=null?j:"",c.style.borderColor=(re=z.border)!=null?re:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let f=(F=a.closeButtonSize)!=null?F:"32px",u=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=e?"":"none",m.style.color=a.closeButtonColor||_n.actionIconColor;let v=(k=a.closeButtonIconName)!=null?k:"x",x=Se(v,"28px","currentColor",1);x?m.appendChild(x):m.textContent="\xD7",r&&m.addEventListener("click",r),u.appendChild(m),i.appendChild(u);let E=y("div");E.style.display="none";let M=y("span");return M.style.display="none",{header:i,iconHolder:E,headerTitle:g,headerSubtitle:M,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},fm={default:oh,minimal:ah},ih=n=>{var t;return(t=fm[n])!=null?t:fm.default},yi=(n,t,e)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),g=y("div");g.style.display="none";let f=y("span"),u=y("span"),m=y("button");m.style.display="none";let v=y("div");return v.style.display="none",{header:c,iconHolder:g,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=ih(r)({config:n,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:e==null?void 0:e.showClose)!=null?d:!0,onClose:e==null?void 0:e.onClose,onClearChat:e==null?void 0:e.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var vi=n=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let e=3,r=20;t.style.maxHeight=`${e*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:e*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},xi=n=>{var R,A,L,N,F,k,z,j,re,Ie,Ve,ve;let t=(R=n==null?void 0:n.sendButton)!=null?R:{},e=(A=t.useIcon)!=null?A:!1,r=(L=t.iconText)!=null?L:"\u2191",o=t.iconName,s=(N=t.stopIconName)!=null?N:"square",a=(F=t.tooltipText)!=null?F:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(j=(z=n==null?void 0:n.copy)==null?void 0:z.sendButtonLabel)!=null?j:"Send",c=(Ie=(re=n==null?void 0:n.copy)==null?void 0:re.stopButtonLabel)!=null?Ie:"Stop",g=(Ve=t.showTooltip)!=null?Ve:!1,f=(ve=t.size)!=null?ve:"40px",u=t.backgroundColor,m=t.textColor,v=y("div","persona-send-button-wrapper"),x=It("button",{className:Ks("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",e?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",e&&!u&&"persona-bg-persona-primary",!e&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:e?f:void 0,height:e?f:void 0,minWidth:e?f:void 0,minHeight:e?f:void 0,fontSize:e?"18px":void 0,lineHeight:e?"1":void 0,color:e?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:e&&u||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,M=null;if(e){let Ne=parseFloat(f)||24,qe=(m==null?void 0:m.trim())||"currentColor";o?(E=Se(o,Ne,qe,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,M=Se(s,Ne,qe,2)}else x.textContent=d;let S=null;g&&a&&(S=y("div","persona-send-button-tooltip"),S.textContent=a,v.appendChild(S)),x.setAttribute("aria-label",a),v.appendChild(x);let B="send";return{button:x,wrapper:v,setMode:Ne=>{if(Ne===B)return;B=Ne;let qe=Ne==="stop"?i:a;if(x.setAttribute("aria-label",qe),S&&(S.textContent=qe),e){if(E&&M){let Te=Ne==="stop"?M:E;x.replaceChildren(Te)}}else x.textContent=Ne==="stop"?c:d}}},wi=n=>{var S,B,I,R,A,L,N,F,k,z,j,re;let t=(S=n==null?void 0:n.voiceRecognition)!=null?S:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((B=t.provider)==null?void 0:B.type)==="runtype";if(!(r||o))return null;let a=(R=(I=n==null?void 0:n.sendButton)==null?void 0:I.size)!=null?R:"40px",i=(A=t.iconName)!=null?A:"mic",d=(L=t.iconSize)!=null?L:a,c=parseFloat(d)||24,g=(F=t.backgroundColor)!=null?F:(N=n==null?void 0:n.sendButton)==null?void 0:N.backgroundColor,f=(z=t.iconColor)!=null?z:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,u=y("div","persona-send-button-wrapper"),m=It("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:g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=Se(i,c,f||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",u.appendChild(m);let E=(j=t.tooltipText)!=null?j:"Start voice recognition";if(((re=t.showTooltip)!=null?re:!1)&&E){let Ie=y("div","persona-send-button-tooltip");Ie.textContent=E,u.appendChild(Ie)}return{button:m,wrapper:u}},Ci=n=>{var v,x,E,M,S,B,I,R;let t=(v=n==null?void 0:n.attachments)!=null?v:{};if(t.enabled!==!0)return null;let e=(E=(x=n==null?void 0:n.sendButton)==null?void 0:x.size)!=null?E:"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=((M=t.allowedTypes)!=null?M:Qr).join(","),o.multiple=((S=t.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(B=t.buttonIconName)!=null?B:"paperclip",a=e,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),g=It("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":(I=t.buttonTooltipText)!=null?I:"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"}});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 f=Se(s,d,"currentColor",1.5);f?g.appendChild(f):g.textContent="\u{1F4CE}",g.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(g);let u=(R=t.buttonTooltipText)!=null?R:"Attach file",m=y("div","persona-send-button-tooltip");return m.textContent=u,c.appendChild(m),{button:g,wrapper:c,input:o,previewsContainer:r}},Ai=n=>{var a,i,d;let t=(a=n==null?void 0:n.statusIndicator)!=null?a:{},e=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${e} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Si=()=>It("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ti=n=>{var v,x,E,M,S,B;let{config:t}=n,e=It("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=Si(),o=It("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}=vi(t);a();let i=xi(t),d=wi(t),c=Ci(t),g=Ai(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let f=It("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=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&&u.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),f.append(u,m),o.append(f),o.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),e.append(r,o,g),{footer:e,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:g,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(B=c==null?void 0:c.previewsContainer)!=null?B:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var hm=()=>{let n=It("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),e=Se("message-square",16,"currentColor",1.5);e&&t.appendChild(e);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=Se("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(t,r,o),{root:n,textNode:r}},bm=n=>{var v,x,E,M,S,B;let{config:t}=n,e=It("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Si();r.style.display="none";let o=Ai(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=vi(t);s.style.maxHeight="100px",a();let i=xi(t),d=wi(t),c=Ci(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let g=It("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 u=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&u.append(d.wrapper),u.append(i.wrapper),g.addEventListener("click",I=>{I.target!==i.button&&I.target!==i.wrapper&&I.target!==(d==null?void 0:d.button)&&I.target!==(d==null?void 0:d.wrapper)&&I.target!==(c==null?void 0:c.button)&&I.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&g.append(c.input),g.append(f,s,u),c&&e.append(c.previewsContainer),e.append(g,r,o);let m=g;return{footer:e,suggestions:r,composerForm:g,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:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(M=c==null?void 0:c.wrapper)!=null?M:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(B=c==null?void 0:c.previewsContainer)!=null?B:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var ym=n=>{var g,f,u,m,v,x,E,M,S,B,I,R,A,L,N,F,k;let t=(f=(g=n==null?void 0:n.launcher)==null?void 0:g.enabled)!=null?f:!0,e=An(n);if(ua(n)){let z=(m=(u=n==null?void 0:n.launcher)==null?void 0:u.composerBar)!=null?m:{},j=y("div","persona-widget-wrapper persona-fixed persona-transition");j.setAttribute("data-persona-composer-bar",""),j.dataset.state="collapsed",j.dataset.expandedSize=(v=z.expandedSize)!=null?v:"anchored",j.style.zIndex=String((E=(x=n==null?void 0:n.launcher)==null?void 0:x.zIndex)!=null?E:In);let re=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");re.style.width="100%",j.appendChild(re);let Ie=y("div","persona-widget-pill-root");return Ie.setAttribute("data-persona-composer-bar",""),Ie.dataset.state="collapsed",Ie.dataset.expandedSize=(M=z.expandedSize)!=null?M:"anchored",Ie.style.zIndex=String((B=(S=n==null?void 0:n.launcher)==null?void 0:S.zIndex)!=null?B:In),{wrapper:j,panel:re,pillRoot:Ie}}if(e){let z=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return z.appendChild(j),{wrapper:z,panel:j}}if(!t){let z=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),re=(R=(I=n==null?void 0:n.launcher)==null?void 0:I.width)!=null?R:"100%";return z.style.width=re,j.style.width="100%",z.appendChild(j),{wrapper:z,panel:j}}let o=(A=n==null?void 0:n.launcher)!=null?A:{},s=o.position&&xr[o.position]?xr[o.position]:xr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((N=(L=n==null?void 0:n.launcher)==null?void 0:L.zIndex)!=null?N:In);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(F=n==null?void 0:n.launcher)==null?void 0:F.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:Xr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},lh=(n,t)=>{var I,R,A,L,N,F,k,z,j;let e=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");e.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=hi(n,{showClose:t,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=(I=n==null?void 0:n.launcher)==null?void 0:I.clearChat)==null?void 0:R.enabled)!=null?A:!0,a=null,i=null;if(s){let re=bi(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=re.button,i=re.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=It("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=It("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 g=It("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(N=(L=n==null?void 0:n.copy)==null?void 0:L.welcomeTitle)!=null?N:"Hello \u{1F44B}"}),f=It("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(F=n==null?void 0:n.copy)==null?void 0:F.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),u=It("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))"}},g,f),m=y("div","persona-flex persona-flex-col persona-gap-3"),v=(z=n==null?void 0:n.layout)==null?void 0:z.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((j=n==null?void 0:n.copy)==null?void 0:j.showWelcomeCard)!==!1||(u.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(u,m);let E=It("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=bm({config:n}),{root:S,textNode:B}=hm();return e.append(d,o,c,E),i&&e.appendChild(i),{container:e,body:c,messagesWrapper:m,composerOverlay:E,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:g,introSubtitle:f,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("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:S,peekTextNode:B}},vm=(n,t=!0)=>{var E,M,S,B,I,R,A,L,N;if(ua(n))return lh(n,t);let e=It("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=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=((M=n==null?void 0:n.layout)==null?void 0:M.showHeader)!==!1,s=r?yi(n,r,{showClose:t}):zo({config:n,showClose:t}),a=It("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=It("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(B=(S=n==null?void 0:n.copy)==null?void 0:S.welcomeTitle)!=null?B:"Hello \u{1F44B}"}),d=It("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(I=n==null?void 0:n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),c=It("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:An(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),g=y("div","persona-flex persona-flex-col persona-gap-3"),f=(A=n==null?void 0:n.layout)==null?void 0:A.contentMaxWidth;f&&(g.style.maxWidth=f,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((L=n==null?void 0:n.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,g);let m=Ti({config:n}),v=((N=n==null?void 0:n.layout)==null?void 0:N.showFooter)!==!1;o?ma(e,s,n):(s.header.style.display="none",ma(e,s,n)),e.append(a);let x=It("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||(m.footer.style.display="none"),e.append(m.footer),e.append(x),{container:e,body:a,messagesWrapper:g,composerOverlay:x,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 pl=(n,t)=>{let e=y("button");e.type="button",e.innerHTML=`
18
+ _Details: ${t.message}_`:r}var _s=n=>({isError:!0,content:[{type:"text",text:n}]}),Hu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Bu=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(!Bf(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=Ru(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=Ru(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()":Hu(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()":Hu(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&&Bu(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&&Bu(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"),Df={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=Df[n];return o?Nf(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 Nf(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 Ff(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Of(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=Au(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 Cu(c),g=Ea(c)?URL.createObjectURL(c):null,u={id:Ff(),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=Of(e.file.type),d=Ae(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Su(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 Du=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];Du(s)&&Du(o)?t[r]=Us(s,o):t[r]=o}return t}var qr="min(440px, calc(100vw - 24px))",Fu="440px",_f={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:_f,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 Nu(n,e){if(!(!n&&!e))return n?e?Us(n,e):n:e}function Ou(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:Nu(Nt.theme,n.theme),darkTheme:Nu(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 $f={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"}},Uf={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"}},qf={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:Fu,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 _u(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 zf(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 $u(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]=$u(s,o):t[r]=o}return t}function jf(n,e){return e?$u(n,e):n}function Wo(n,e={}){var o,s,a,i,d,c,m,f,g,u,v,x,I;let t={palette:$f,semantic:Uf,components:qf},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:jf(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let M=zf(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 Uu(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=_u(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 Vf={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"}}},qu=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"},Kf=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Bi()},Gf=n=>Kf(n),Qf=n=>Wo(n),Xf=n=>{var t;let e=Wo(void 0,{validate:!1});return Wo({...n,palette:{...e.palette,colors:{...Vf.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ra=n=>{let e=Gf(n),t=qu(n==null?void 0:n.theme),r=qu(n==null?void 0:n.darkTheme);return e==="dark"?Xf(Us(t!=null?t:{},r!=null?r:{})):Qf(t)},Jf=n=>Uu(n),ls=(n,e)=>{let t=Ra(e),r=Jf(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},zu=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 ju=require("idiomorph"),Ha=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;ju.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 Vu=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Ba={index:-1,draft:""};function Ku(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 Gu(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 Qu(){return new Map}function Xu(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Ju(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Yu(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 Zu(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function em(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 tm(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"},Yf=["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}},Zf=[{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"}],rm=new Map;for(let n of Zf)rm.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=rm.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(`
19
+ `);return s<0?"":n.slice(0,s)}return n},eh=(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},th=(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/,nh=(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},rh=(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(eh(r,s[m],e,t.value)),t.value+=1,m+=1;a.appendChild(c),i=m}o.replaceChild(a,n)},oh=(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(th(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:Yf).map(u=>u.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)nh(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},m=e==="char"?rh:oh;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},nm=new WeakMap,sh=(n,e)=>{var s;if(!n.styles)return;let t=nm.get(e);if(t||(t=new Set,nm.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,ah=(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)},om=n=>{let e=Ni.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Fi=(n,e)=>{sh(n,e),ah(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 ih="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=ih,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}},lh="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=lh,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 sm(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 ch=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 dh(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 ph=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=sm({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),dh(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}},am={default:ch,minimal:ph},uh=n=>{var e;return(e=am[n])!=null?e:am.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=uh(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 im=()=>{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}},lm=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 cm=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}},mh=(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=lm({config:n}),{root:E,textNode:F}=im();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}},dm=(n,e=!0)=>{var I,M,E,F,L,R,A,W,N;if(Qs(n))return mh(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
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: ${e.message}_`:r}var ra=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
- `,e.addEventListener("click",t);let r=s=>{var B,I,R,A,L,N,F,k,z,j,re,Ie,Ve;let a=(B=s.launcher)!=null?B:{},i=An(s),d=e.querySelector("[data-role='launcher-title']");if(d){let ve=(I=a.title)!=null?I:"Chat Assistant";d.textContent=ve,d.setAttribute("title",ve)}let c=e.querySelector("[data-role='launcher-subtitle']");if(c){let ve=(R=a.subtitle)!=null?R:"Here to help you get answers fast";c.textContent=ve,c.setAttribute("title",ve)}let g=e.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let f=e.querySelector("[data-role='launcher-icon']");if(f)if(a.agentIconHidden)f.style.display="none";else{let ve=(A=a.agentIconSize)!=null?A:"40px";if(f.style.height=ve,f.style.width=ve,f.innerHTML="",a.agentIconName){let Ne=parseFloat(ve)||24,qe=Se(a.agentIconName,Ne*.6,"var(--persona-text-inverse, #ffffff)",2);qe?(f.appendChild(qe),f.style.display=""):(f.textContent=(L=a.agentIconText)!=null?L:"\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 u=e.querySelector("[data-role='launcher-image']");if(u){let ve=(F=a.agentIconSize)!=null?F:"40px";u.style.height=ve,u.style.width=ve,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(u.src=a.iconUrl,u.style.display="block"):u.style.display="none"}let m=e.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ve=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=ve,m.style.width=ve,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 Ne=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Ne=(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 qe=parseFloat(ve)||24,Te=Math.max(qe-Ne,8),we=Se(a.callToActionIconName,Te,"currentColor",2);we?m.appendChild(we):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(j=a.callToActionIconText)!=null?j:"\u2197"}let v=a.position&&xr[a.position]?xr[a.position]:xr["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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";e.className=i?E:`${x} ${v}`,i||(e.style.zIndex=String((re=a.zIndex)!=null?re:In));let M="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";e.style.border=(Ie=a.border)!=null?Ie:M,e.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:S,i?(e.style.width="0",e.style.minWidth="0",e.style.maxWidth="0",e.style.padding="0",e.style.overflow="hidden",e.style.border="none",e.style.boxShadow="none"):(e.style.width="",e.style.minWidth="",e.style.maxWidth=(Ve=a.collapsedMaxWidth)!=null?Ve:"",e.style.justifyContent="",e.style.padding="",e.style.overflow="")},o=()=>{e.removeEventListener("click",t),e.remove()};return n&&r(n),{element:e,update:r,destroy:o}};var xm=({config:n,showClose:t})=>{let{wrapper:e,panel:r,pillRoot:o}=ym(n),s=vm(n,t),a={wrapper:e,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:u=>(d.element.replaceWith(u.header),d.element=u.header,d.iconHolder=u.iconHolder,d.headerTitle=u.headerTitle,d.headerSubtitle=u.headerSubtitle,d.closeButton=u.closeButton,d.closeButtonWrapper=u.closeButtonWrapper,d.clearChatButton=u.clearChatButton,d.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{c.footer.replaceWith(u),c.footer=u}}},ul=({config:n,plugins:t,onToggle:e})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>pl(n,e).element,onToggle:e});if(s)return{instance:null,element:s}}let o=pl(n,e);return{instance:o,element:o.element}};var ch=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}},dh=(n,t)=>{if(!n)return null;let e=ch(n);if(e===null)return null;let r=t==null?void 0:t[n],o=r!==void 0?r:e;return o||null},ph=(n,t)=>{let e=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return e.setAttribute("data-stop-reason",n),e.setAttribute("role","note"),e.style.opacity="0.75",e.textContent=t,e},uh=n=>{let t=n.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:image/")||!n.includes(":"))},ml=n=>{let t=n.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||t.startsWith("data:")||!n.includes(":"))},gl=320,Cm=320,mh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),gh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),fh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),hh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),bh=(n,t,e)=>{if(n.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),e==null||e())};return n.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=`${gl}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 g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),uh(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return e==null||e(),null}},yh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let e=0;return n.forEach(r=>{if(!ml(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=`${gl}px`,t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},vh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let e=0;return n.forEach(r=>{if(!ml(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=`${gl}px`,o.style.maxHeight=`${Cm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},xh=n=>{if(n.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let e=0;return n.forEach(r=>{if(!ml(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",t.appendChild(o),e+=1}),e===0?(t.remove(),null):t}catch{return null}},ga=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let 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="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(t),n.appendChild(e),n.appendChild(r),n.appendChild(o),n},wh=(n,t,e)=>{let r={config:e!=null?e:{},streaming:!0,location:n,defaultRenderer:ga};if(t){let o=t(r);if(o!==null)return o}return ga()},Ch=(n,t)=>{let e=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",e.appendChild(o)}else e.textContent=r,e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else e.textContent=t==="user"?"U":"A",e.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return e},wm=(n,t,e="div")=>{let r=y(e,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Ah=(n,t="bubble")=>{let e=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):e.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":e.push("persona-text-sm","persona-leading-relaxed"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):e.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:e.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?e.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):e.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 e},Sh=(n,t,e)=>{var v,x,E,M,S,B,I;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(M=t.showReadAloud)!=null?M:!1;if(!r&&!o&&!s&&!a){let R=y("div");return R.style.display="none",R.id=`actions-${n.id}`,R.setAttribute("data-actions-for",n.id),R}let i=(S=t.visibility)!=null?S:"hover",d=(B=t.align)!=null?B:"right",c=(I=t.layout)!=null?I:"pill-inside",g={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],u=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${g} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${n.id}`,u.setAttribute("data-actions-for",n.id);let m=(R,A,L)=>{let N=Pn({icon:R,label:A,size:14,className:"persona-message-action-btn"});return N.setAttribute("data-action",L),N};return r&&u.appendChild(m("copy","Copy message","copy")),a&&u.appendChild(m("volume-2","Read aloud","read-aloud")),o&&u.appendChild(m("thumbs-up","Upvote","upvote")),s&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},fl=(n,t,e,r,o,s)=>{var oe,X,se,fe,pe,K,ae,Be,ee,Z,ne,st,at,nt,Me,he,Ge;let a=e!=null?e:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,g=(X=d==null?void 0:d.show)!=null?X:!1,f=(se=c==null?void 0:c.show)!=null?se:!1,u=(fe=d==null?void 0:d.position)!=null?fe:"left",m=(pe=c==null?void 0:c.position)!=null?pe:"below",v=Ah(n.role,i),x=y("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 E=mh(n),M=(ae=(K=n.content)==null?void 0:K.trim())!=null?ae:"",B=E.length>0&&M===ei,I=mi((ee=(Be=s==null?void 0:s.widgetConfig)==null?void 0:Be.features)==null?void 0:ee.streamAnimation),R=(st=(ne=(Z=s==null?void 0:s.widgetConfig)==null?void 0:Z.features)==null?void 0:ne.streamAnimation)==null?void 0:st.plugins,A=n.role==="assistant"&&I.type!=="none"?ia(I.type,R):null,L=n.role==="assistant"&&((at=A==null?void 0:A.isAnimating)==null?void 0:at.call(A,n))===!0,N=n.role==="assistant"&&A!==null&&(!!n.streaming||L);N&&(A!=null&&A.bubbleClass)&&x.classList.add(A.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),N&&A&&(A.containerClass&&F.classList.add(A.containerClass),F.style.setProperty("--persona-stream-step",`${I.speed}ms`),F.style.setProperty("--persona-stream-duration",`${I.duration}ms`));let k=N?gi((nt=n.content)!=null?nt:"",I.buffer,A,n,!!n.streaming):(Me=n.content)!=null?Me:"",z=t({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),j=z;N&&(A==null?void 0:A.wrap)==="char"?j=la(z,"char",n.id,{skipTags:A.skipTags}):N&&(A==null?void 0:A.wrap)==="word"&&(j=la(z,"word",n.id,{skipTags:A.skipTags}));let re=null;if(B?(re=document.createElement("div"),re.innerHTML=j,re.style.display="none",F.appendChild(re)):F.innerHTML=j,N&&(A!=null&&A.useCaret)&&!B&&M){let J=fi(),ue=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Le=ue[ue.length-1];if(Le!=null&&Le.parentNode)Le.parentNode.insertBefore(J,Le.nextSibling);else{let Xe=F.lastElementChild;Xe?Xe.appendChild(J):F.appendChild(J)}}if(f&&m==="inline"&&n.createdAt){let J=wm(n,c,"span");J.classList.add("persona-timestamp-inline");let ue=F.lastElementChild;ue?ue.appendChild(J):F.appendChild(J)}if(E.length>0){let J=bh(E,!B&&!!M,()=>{B&&re&&(re.style.display="")});J?x.appendChild(J):B&&re&&(re.style.display="")}let Ie=gh(n);if(Ie.length>0){let J=yh(Ie);J&&x.appendChild(J)}let Ve=fh(n);if(Ve.length>0){let J=vh(Ve);J&&x.appendChild(J)}let ve=hh(n);if(ve.length>0){let J=xh(ve);J&&x.appendChild(J)}if(x.appendChild(F),f&&m==="below"&&n.createdAt){let J=wm(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ne=n.role==="assistant"?dh(n.stopReason,(Ge=(he=s==null?void 0:s.widgetConfig)==null?void 0:he.copy)==null?void 0:Ge.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let J=!!(k&&k.trim()),ue=I.placeholder==="skeleton",Le=ue&&I.buffer==="line"&&J;if(J)Le&&x.appendChild(ca());else if(ue)x.appendChild(ca());else{let Xe=wh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Xe&&x.appendChild(Xe)}}if(Ne&&n.stopReason&&!n.streaming&&(M||(F.style.display="none"),x.appendChild(ph(n.stopReason,Ne))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Sh(n,r,o);x.appendChild(J)}if(!g||n.role==="system")return x;let Te=y("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),we=Ch(d,n.role);return u==="right"||u==="left"&&n.role==="user"?Te.append(x,we):Te.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Te};var ws=new Set,Th=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),Eh=(n,t)=>{var r,o;let e=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return e?e.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
26
- `):""},Am=(n,t)=>{let e=ws.has(n),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",e?"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=Se(e?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=e?"Hide":"Show"}o.style.display=e?"":"none",s&&(s.style.display=e?"none":s.textContent||s.childNodes.length?"":"none")},hl=(n,t)=>{var Ve,ve,Ne,qe,Te,we,oe,X,se,fe,pe;let e=n.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-${n.id}`,r.setAttribute("data-message-id",n.id),!e)return r;let o=(ve=(Ve=t==null?void 0:t.features)==null?void 0:Ve.reasoningDisplay)!=null?ve:{},s=o.expandable!==!1,a=s&&ws.has(n.id),i=e.status!=="complete",d=Eh(n,(Ne=o.previewMaxLines)!=null?Ne: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 g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(qe=t==null?void 0:t.reasoning)!=null?qe:{},v=String((Te=e.startedAt)!=null?Te:Date.now()),x=()=>{let K=y("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ga(e),K},E=(we=m.renderCollapsedSummary)==null?void 0:we.call(m,{message:n,reasoning:e,defaultSummary:u,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ga(e),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=u,g.appendChild(f));let M=y("span","persona-text-xs persona-text-persona-primary");M.textContent=wu(e),g.appendChild(M);let S=(oe=o.loadingAnimation)!=null?oe:"none",B=m.activeTextTemplate,I=m.completeTextTemplate,R=i?B:I,A=E instanceof HTMLElement,L=(K,ae,Be)=>{let ee=Be;for(let Z of ae){let ne=y("span","persona-tool-char");ne.style.setProperty("--char-index",String(ee)),ne.textContent=Z===" "?"\xA0":Z,K.appendChild(ne),ee++}return ee},N=(K,ae)=>{f.textContent="";let Be=Qa(K,""),ee=0;for(let Z of Be){let ne=Z.styles.length>0?(()=>{let st=y("span",Z.styles.map(at=>`persona-tool-text-${at}`).join(" "));return f.appendChild(st),st})():f;if(Z.isDuration&&i)ne.appendChild(x());else{let st=Z.isDuration?Ga(e):Z.text;ae?ee=L(ne,st,ee):ne.appendChild(document.createTextNode(st))}}};if(!A&&R)if(M.style.display="none",f.style.display="",i&&S!=="none"){let K=(X=m.loadingAnimationDuration)!=null?X:2e3;f.setAttribute("data-preserve-animation","true"),S==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),N(R,!1)):(f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="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)),N(R,!0))}else N(R,!1);else if(!A&&i&&S!=="none"){f.style.display="";let K=(se=m.loadingAnimationDuration)!=null?se:2e3;if(f.setAttribute("data-preserve-animation","true"),S==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${S}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="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 ae=f.textContent||u;f.textContent="",L(f,ae,0)}e.status==="complete"&&(f.style.display="none")}else A||(e.status==="complete"?f.style.display="none":f.style.display="");let F=null;if(s){F=y("div","persona-flex persona-items-center");let ae=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show";let Be=y("div","persona-flex persona-items-center persona-ml-auto");Be.append(F),c.append(g,Be)}else c.append(g);let k=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(pe=(fe=t==null?void 0:t.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:pe.call(fe,{message:n,reasoning:e,defaultPreview:d,isActive:i,config:t!=null?t:{}});Th(k,K)||(k.textContent=d),k.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,k),r;let z=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");z.style.display=a?"":"none";let j=e.chunks.join(""),re=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return re.textContent=j||(e.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),z.appendChild(re),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),F){F.innerHTML="";let ae=Se(a?"chevron-up":"chevron-down",16,"currentColor",2);ae?F.appendChild(ae):F.textContent=a?"Hide":"Show"}z.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,z),r};var Cs=new Set,Mh=(n,t)=>t==null?!1:typeof t=="string"?(n.textContent=t,!0):(n.appendChild(t),!0),kh=(n,t)=>{var s;let e=n.toolCall;if(!e)return"";let r=((s=e.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
27
- `);let o=gs(e.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},Lh=(n,t)=>{var g,f,u,m,v;let e=n.toolCall,r=(g=t==null?void 0:t.features)==null?void 0:g.toolCallDisplay,o=(f=r==null?void 0:r.collapsedMode)!=null?f:"tool-call",s=kh(n,(u=r==null?void 0:r.previewMaxLines)!=null?u:3),a=e?Cu(e):"";if(!e)return{summary:a,previewText:s,isActive:!1};let i=e.status!=="complete",d=(m=t==null?void 0:t.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((v=e.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ji(e,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ji(e,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Sm=(n,t,e)=>{var g;let r=Cs.has(n),o=(g=e==null?void 0:e.toolCall)!=null?g:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",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||"currentColor",u=Se(r?"chevron-up":"chevron-down",16,f,2);u?c.appendChild(u):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},bl=(n,t)=>{var j,re,Ie,Ve,ve,Ne,qe,Te,we;let e=n.toolCall,r=(j=t==null?void 0:t.toolCall)!=null?j:{},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-${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))",!e)return o;let s=(Ie=(re=t==null?void 0:t.features)==null?void 0:re.toolCallDisplay)!=null?Ie:{},a=s.expandable!==!1,i=a&&Cs.has(n.id),{summary:d,previewText:c,isActive:g}=Lh(n,t),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 u=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 v=String((Ve=e.startedAt)!=null?Ve:Date.now()),x=()=>{let oe=y("span","");return oe.setAttribute("data-tool-elapsed",v),oe.textContent=Js(e),oe},E=(Ne=r.renderCollapsedSummary)==null?void 0:Ne.call(r,{message:n,toolCall:e,defaultSummary:d,previewText:c,collapsedMode:(ve=s.collapsedMode)!=null?ve:"tool-call",isActive:g,config:t!=null?t:{},elapsed:Js(e),createElapsedElement:x});typeof E=="string"&&E.trim()?(m.textContent=E,u.appendChild(m)):E instanceof HTMLElement?u.appendChild(E):(m.textContent=d,u.appendChild(m));let M=(qe=s.loadingAnimation)!=null?qe:"none",S=r.activeTextTemplate,B=r.completeTextTemplate,I=g?S:B,R=E instanceof HTMLElement,A=(oe,X,se)=>{let fe=se;for(let pe of X){let K=y("span","persona-tool-char");K.style.setProperty("--char-index",String(fe)),K.textContent=pe===" "?"\xA0":pe,oe.appendChild(K),fe++}return fe},L=(oe,X)=>{var K;m.textContent="";let se=((K=e.name)==null?void 0:K.trim())||"tool",fe=Qa(oe,se),pe=0;for(let ae of fe){let Be=ae.styles.length>0?(()=>{let ee=y("span",ae.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return m.appendChild(ee),ee})():m;if(ae.isDuration&&g)Be.appendChild(x());else{let ee=ae.isDuration?Js(e):ae.text;X?pe=A(Be,ee,pe):Be.appendChild(document.createTextNode(ee))}}};if(!R)if(g&&M!=="none"){let oe=(Te=r.loadingAnimationDuration)!=null?Te:2e3;if(m.setAttribute("data-preserve-animation","true"),M==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I&&L(I,!1);else if(m.classList.add(`persona-tool-loading-${M}`),m.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),M==="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)),I)L(I,!0);else{let X=m.textContent||d;m.textContent="",A(m,X,0)}}else I&&L(I,!1);let N=null;if(a){N=y("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,oe,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show";let se=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(N),f.append(u,se)}else f.append(u);let F=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!i&&g&&s.activePreview&&c){let oe=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:n,toolCall:e,defaultPreview:c,isActive:g,config:t!=null?t:{}});Mh(F,oe)||(F.textContent=c),F.style.display=""}if(!i&&g&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(f,F),o;let k=y("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),e.name){let oe=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=e.name,k.appendChild(oe)}if(e.args!==void 0){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Arguments";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=gs(e.args),oe.append(X,se),k.appendChild(oe)}if(e.chunks&&e.chunks.length){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Activity";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=e.chunks.join(""),oe.append(X,se),k.appendChild(oe)}if(e.status==="complete"&&e.result!==void 0){let oe=y("div","persona-space-y-1"),X=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(X.style.color=r.labelTextColor),X.textContent="Result";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(se.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(se.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(se.style.color=r.codeBlockTextColor),se.textContent=gs(e.result),oe.append(X,se),k.appendChild(oe)}if(e.status==="complete"&&typeof e.duration=="number"){let oe=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${e.duration}ms`,k.appendChild(oe)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),N){N.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"currentColor",X=Se(i?"chevron-up":"chevron-down",16,oe,2);X?N.appendChild(X):N.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",F.style.display=i?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(f,F,k),o};var Ei=new Map,Ih=n=>{let e=(n.startsWith(No)?n.slice(No.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(e.length===0)return n;let r=e.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Tm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Em=(n,t)=>{var r,o,s;let e=(o=(r=Tm(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ei.get(n))!=null?s:e==="expanded"},Mm=(n,t,e)=>{var a,i;let r=Tm(e);n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=Se(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},km=(n,t,e)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Em(n,e);Mm(r,s,e),o.style.display=s?"":"none"};var Mi=(n,t)=>{var L,N,F,k,z,j,re,Ie,Ve,ve,Ne,qe,Te,we,oe;let e=n.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(e==null?void 0:e.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-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(L=r==null?void 0:r.backgroundColor)!=null?L:"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))",!e)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=e.status==="denied"?"shield-x":e.status==="timeout"?"shield-alert":"shield-check",c=e.status==="approved"?"var(--persona-feedback-success, #16a34a)":e.status==="denied"?"var(--persona-feedback-error, #dc2626)":e.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(F=r==null?void 0:r.titleColor)!=null?F:"currentColor",g=Se(d,20,c,2);g&&i.appendChild(g);let f=y("div","persona-flex-1 persona-min-w-0"),u=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=(k=r==null?void 0:r.title)!=null?k:"Approval Required",u.appendChild(m),!o){let X=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");X.setAttribute("data-approval-status",e.status),e.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"):e.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"):e.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"),u.appendChild(X)}f.appendChild(u);let x=e.toolType==="webmcp"||e.toolName.startsWith(No)?Oi(e.toolName):void 0,E=(z=r==null?void 0:r.formatDescription)==null?void 0:z.call(r,{toolName:e.toolName,toolType:e.toolType,description:e.description,parameters:e.parameters,...x?{displayTitle:x}:{},...e.reason?{reason:e.reason}:{}}),M=!e.toolName,S=E||(M?e.description:`The assistant wants to use \u201C${x!=null?x:Ih(e.toolName)}\u201D.`),B=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(B.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(B.style.color=r.descriptionColor),B.textContent=S,f.appendChild(B),e.reason){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");X.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?X.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor);let se=y("span","persona-font-medium");se.textContent=`${(j=r==null?void 0:r.reasonLabel)!=null?j:"Agent's stated reason:"} `,X.appendChild(se),X.appendChild(document.createTextNode(e.reason)),f.appendChild(X)}let I=(re=r==null?void 0:r.detailsDisplay)!=null?re:"collapsed",R=!!e.description&&!M,A=R||!!e.parameters;if(I!=="hidden"&&A){let X=Em(n.id,t),se=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");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let fe=y("span");fe.setAttribute("data-approval-details-label","true");let pe=y("span","persona-inline-flex persona-items-center");pe.setAttribute("data-approval-details-chevron","true"),se.append(fe,pe),Mm(se,X,t),f.appendChild(se);let K=y("div");if(K.setAttribute("data-approval-details","true"),K.style.display=X?"":"none",R){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor),ae.textContent=e.description,K.appendChild(ae)}if(e.parameters){let ae=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&&(ae.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ae.style.color=r.parameterTextColor),ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",ae.textContent=gs(e.parameters),K.appendChild(ae)}f.appendChild(K)}if(o){let X=y("div","persona-flex persona-gap-2 persona-mt-2");X.setAttribute("data-approval-buttons","true");let se=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");se.type="button",se.style.backgroundColor=(Ie=r==null?void 0:r.approveButtonColor)!=null?Ie:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(Ve=r==null?void 0:r.approveButtonTextColor)!=null?Ve:"#ffffff",se.setAttribute("data-approval-action","approve");let fe=Se("shield-check",14,(ve=r==null?void 0:r.approveButtonTextColor)!=null?ve:"#ffffff",2);fe&&(fe.style.marginRight="4px",se.appendChild(fe));let pe=document.createTextNode((Ne=r==null?void 0:r.approveLabel)!=null?Ne:"Approve");se.appendChild(pe);let K=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");K.type="button",K.style.backgroundColor=(qe=r==null?void 0:r.denyButtonColor)!=null?qe:"transparent",K.style.color=(Te=r==null?void 0:r.denyButtonTextColor)!=null?Te:"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 ae=Se("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);ae&&(ae.style.marginRight="4px",K.appendChild(ae));let Be=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");K.appendChild(Be),X.append(se,K),f.appendChild(X)}return a.append(i,f),s.appendChild(a),s};var Lm=n=>{let t=[],e=null;return{buttons:t,render:(o,s,a,i,d,c)=>{n.innerHTML="",t.length=0;let g=(c==null?void 0:c.agentPushed)===!0;if(g||(e=null),!o||!o.length||!g&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let f=document.createDocumentFragment(),u=s?s.isStreaming():!1,m=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=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");x.type="button",x.textContent=v,x.disabled=u,d!=null&&d.fontFamily&&(x.style.fontFamily=m(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="",g&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),f.appendChild(x),t.push(x)}),n.appendChild(f),g){let v=JSON.stringify(o);v!==e&&(e=v,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(t=2e3,e=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=e}push(t){var e;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(e=this.store)==null||e.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let e=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of e)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,e.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let e=this.getAll();return t>=e.length?e:e.slice(e.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ha=class{constructor(t="persona-event-stream",e="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=e}open(){return new Promise((t,e)=>{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,t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,e)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{e(a.error)}}catch(r){e(r)}})}getCount(){return new Promise((t,e)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}clear(){return new Promise((t,e)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{e(s.error)}}catch(r){e(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,e)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{e(r.error)}}catch(r){e(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var Ph=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Wh=new Set(["step_start","execution_start"]),Rh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Bh=new Set(["step_complete","agent_turn_complete"]),Hh=new Set(["flow_complete","agent_complete"]),Im=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),nr=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,jo=(n,t)=>{let e=n[t];return Wm(e)?e:void 0};function yl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function ki(n,t){if(!(n<=0||t===void 0||t<250))return n/(t/1e3)}function Dh(n,t){return typeof t.type=="string"?t.type:n}function Nh(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 Fh(n,t){return n==="step_delta"||n==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Pm(n){var r,o,s,a,i;let t=jo(n,"result"),e=[jo(n,"tokens"),jo(n,"totalTokens"),t?jo(t,"tokens"):void 0,jo(n,"usage"),t?jo(t,"usage"):void 0];for(let d of e){if(!d)continue;let c=(o=(r=nr(d.output))!=null?r:nr(d.outputTokens))!=null?o:nr(d.completionTokens);if(c!==void 0)return c}return(i=(s=nr(n.outputTokens))!=null?s:nr(n.completionTokens))!=null?i:t?(a=nr(t.outputTokens))!=null?a:nr(t.completionTokens):void 0}function _h(n){var e,r,o,s,a;let t=jo(n,"result");return(a=(o=(r=(e=nr(n.executionTime))!=null?e:nr(n.executionTimeMs))!=null?r:nr(n.execution_time))!=null?o:nr(n.duration))!=null?a:t?(s=nr(t.executionTime))!=null?s:nr(t.executionTimeMs):void 0}function Oh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ba=class{constructor(t=Oh){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let e=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:e,tokensPerSecond:ki(this.metric.outputTokens,e)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,e){var s;if(!Wm(e)){Im.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Dh(t,e),o=this.now();if(Ph.has(r)){this.startRun(o);return}if(Wh.has(r)){this.run||this.startRun(o);return}if(Rh.has(r)){if(!Fh(r,e))return;let a=Nh(e);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+yl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ki(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Bh.has(r)){if(!this.run)return;let a=this.run,i=Pm(e);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+yl(a.visibleCharCount),g=this.resolveDuration(a,e,o);this.metric={status:"running",tokensPerSecond:ki(c,g),outputTokens:c,durationMs:g,source:d?"usage":"estimate"};return}if(Hh.has(r)){if(!this.run)return;let a=this.run,i=Pm(e),d=i!=null?i:a.exactOutputTokens+yl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",g=this.resolveDuration(a,e,o);this.metric={status:"complete",tokensPerSecond:ki(d,g),outputTokens:d,durationMs:g,source:c},this.run=null;return}if(Im.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,e,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=_h(e);return s!=null?s:r-t.startedAt}};function As(n,t){t&&t.split(/\s+/).forEach(e=>e&&n.classList.add(e))}var $h={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)"}},qh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Uh=["flowName","stepName","reasoningText","text","name","tool","toolName"],zh=100;function jh(n,t){let e={...$h,...t};if(e[n])return e[n];for(let r of Object.keys(e))if(r.endsWith("_")&&n.startsWith(r))return e[r];return qh}function Vh(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function Kh(n){let t=new Date(n),e=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${e}:${r}:${o}.${s}`}function Gh(n,t){try{let e=JSON.parse(n);if(typeof e!="object"||e===null)return null;for(let r of t){let o=r.split("."),s=e;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 Qh(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(e=>{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),e()})}function Xh(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Jh(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function Yh(n){let t=[];return n.outputTokens!==void 0&&t.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&t.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&t.push(n.source),t.join(" \xB7 ")}function Zh(n,t,e){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&e){let i=s.renderEventStreamPayload({event:n,config:e,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 vl(n,t,e,r,o,s,a,i){var u;let d=o.has(n.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");As(c,(u=r.classNames)==null?void 0:u.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:n,index:t,config:i,defaultRenderer:()=>f(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(f()),c;function f(){var j,re;let m=y("div",""),v=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");v.setAttribute("data-event-id",n.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=Se(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let M=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(j=r.timestampFormat)!=null?j:"relative";M.textContent=S==="relative"?Vh(n.timestamp,e):Kh(n.timestamp);let B=null;r.showSequenceNumbers!==!1&&(B=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),B.textContent=String(t+1));let I=jh(n.type,r.badgeColors),R=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");R.style.backgroundColor=I.bg,R.style.color=I.text,R.style.borderColor=I.text+"50",R.textContent=n.type;let A=(re=r.descriptionFields)!=null?re:Uh,L=Gh(n.payload,A),N=null;L&&(N=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),N.textContent=L);let F=y("div","persona-flex-1 persona-min-w-0"),k=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"),z=Se("clipboard","12px","currentColor",1.5);return z&&k.appendChild(z),k.addEventListener("click",async Ie=>{Ie.stopPropagation(),await Qh(Xh(n)),k.innerHTML="";let Ve=Se("check","12px","currentColor",1.5);Ve&&k.appendChild(Ve),setTimeout(()=>{k.innerHTML="";let ve=Se("clipboard","12px","currentColor",1.5);ve&&k.appendChild(ve)},1500)}),v.appendChild(x),v.appendChild(M),B&&v.appendChild(B),v.appendChild(R),N&&v.appendChild(N),v.appendChild(F),v.appendChild(k),m.appendChild(v),d&&m.appendChild(Zh(n,a,i)),m}}function Rm(n){var v,x,E,M,S;let{buffer:t,getFullHistory:e,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",g=(E=i==null?void 0:i.label)!=null?E:"",f=(S=(M=o==null?void 0:o.features)==null?void 0:M.eventStream)!=null?S:{},u=s.find(B=>B.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&o){let B=u.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>m().element,onClose:r});if(B)return{element:B,update:()=>{},destroy:()=>{}}}return m();function m(){let B=f.classNames,I=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");As(I,B==null?void 0:B.panel);let R=[],A="",L="",N=null,F=[],k={},z=0,j=di(),re=0,Ie=0,Ve=!1,ve=null,Ne=!1,qe=0,Te=new Set,we=new Map,oe="",X="",se=null,fe,pe,K,ae,Be,ee=null,Z=null,ne=null;function st(){let de=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),me=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");As(me,B==null?void 0:B.headerBar);let Ee=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ee.textContent="Events",fe=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"),fe.textContent="0",a){Z=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),Z.style.cursor="help";let rr=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");rr.textContent="Throughput",ee=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"),ee.textContent="-- tok/s",ne=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"),ne.style.display="none",ne.style.pointerEvents="none";let Wn=Z,ln=ne,On=()=>{if(!ln.textContent)return;let Ct=Wn.getBoundingClientRect(),jn=de.getBoundingClientRect();ln.style.left=`${Ct.left-jn.left}px`,ln.style.top=`${Ct.bottom-jn.top+4}px`,ln.style.display="block"},Cr=()=>{ln.style.display="none"};Z.addEventListener("mouseenter",On),Z.addEventListener("mouseleave",Cr),Z.appendChild(rr),Z.appendChild(ee)}let ut=y("div","persona-flex-1");pe=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 en=y("option","");en.value="",en.textContent="All events",pe.appendChild(en),K=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"),K.type="button",K.title="Copy All";let wn=Se("clipboard-copy","12px","currentColor",1.5);wn&&K.appendChild(wn);let Ot=y("span","persona-text-xs");Ot.textContent="Copy All",K.appendChild(Ot),me.appendChild(Ee),me.appendChild(fe),Z&&me.appendChild(Z),me.appendChild(ut),me.appendChild(pe),me.appendChild(K);let et=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");As(et,B==null?void 0:B.searchBar);let _t=Se("search","14px","var(--persona-muted, #9ca3af)",1.5),mt=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");_t&&mt.appendChild(_t),ae=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"),As(ae,B==null?void 0:B.searchInput),ae.type="text",ae.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let tn=Se("x","12px","currentColor",2);return tn&&Be.appendChild(tn),et.appendChild(mt),et.appendChild(ae),et.appendChild(Be),de.appendChild(me),de.appendChild(et),ne&&de.appendChild(ne),de}let at,nt=s.find(de=>de.renderEventStreamToolbar);if(nt!=null&&nt.renderEventStreamToolbar&&o){let de=nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>st(),eventCount:t.getSize(),filteredCount:0,onFilterChange:me=>{A=me,Nt(),Sn()},onSearchChange:me=>{L=me,Nt(),Sn()}});at=de!=null?de:st()}else at=st();let Me=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");Me.style.display="none";function he(){if(!a||!ee||!Z)return;let de=a();ee.textContent=Jh(de);let me=Yh(de);ne&&(ne.textContent=me,me||(ne.style.display="none")),me?Z.setAttribute("aria-label",me):Z.removeAttribute("aria-label")}let Ge=y("div","persona-flex-1 persona-min-h-0 persona-relative"),J=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ue=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");As(ue,B==null?void 0:B.scrollIndicator),ue.style.display="none",ue.setAttribute("data-persona-scroll-to-bottom-has-label",g?"true":"false");let Le=Se(c,"14px","currentColor",2);Le&&ue.appendChild(Le);let Xe=y("span","");Xe.textContent=g,ue.appendChild(Xe);let Gt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Gt.style.display="none",Ge.appendChild(J),Ge.appendChild(Gt),Ge.appendChild(ue),I.setAttribute("tabindex","0"),I.appendChild(at),I.appendChild(Me),I.appendChild(Ge);function Pe(){let de=t.getAll(),me={};for(let Ot of de)me[Ot.type]=(me[Ot.type]||0)+1;let Ee=Object.keys(me).sort(),ut=Ee.length!==F.length||!Ee.every((Ot,et)=>Ot===F[et]),en=!ut&&Ee.some(Ot=>me[Ot]!==k[Ot]),an=de.length!==Object.values(k).reduce((Ot,et)=>Ot+et,0);if(!ut&&!en&&!an||(F=Ee,k=me,!pe))return;let wn=pe.value;if(pe.options[0].textContent="All events",ut){for(;pe.options.length>1;)pe.remove(1);for(let Ot of Ee){let et=y("option","");et.value=Ot,et.textContent=`${Ot} (${me[Ot]||0})`,pe.appendChild(et)}wn&&Ee.includes(wn)?pe.value=wn:wn&&(pe.value="",A="")}else for(let Ot=1;Ot<pe.options.length;Ot++){let et=pe.options[Ot];et.textContent=`${et.value} (${me[et.value]||0})`}}function Ue(){let de=t.getAll();if(A&&(de=de.filter(me=>me.type===A)),L){let me=L.toLowerCase();de=de.filter(Ee=>Ee.type.toLowerCase().includes(me)||Ee.payload.toLowerCase().includes(me))}return de}function rt(){return A!==""||L!==""}function Nt(){z=0,re=0,j.resume(),ue.style.display="none"}function yn(de){Te.has(de)?Te.delete(de):Te.add(de),se=de;let me=J.scrollTop,Ee=j.isFollowing();Ne=!0,j.pause(),Sn(),J.scrollTop=me,Ee&&j.resume(),Ne=!1}function wr(){return Uo(J,50)}function Sn(){Ie=Date.now(),Ve=!1,he(),Pe();let de=t.getEvictedCount();de>0?(Me.textContent=`${de.toLocaleString()} older events truncated`,Me.style.display=""):Me.style.display="none",R=Ue();let me=R.length,Ee=t.getSize()>0;fe&&(fe.textContent=String(t.getSize())),me===0&&Ee&&rt()?(Gt.textContent=L?`No events matching '${L}'`:"No events matching filter",Gt.style.display="",J.style.display="none"):(Gt.style.display="none",J.style.display=""),K&&(K.title=rt()?`Copy Filtered (${me})`:"Copy All"),d&&!j.isFollowing()&&me>z&&(re+=me-z,Xe.textContent=g?`${g}${re>0?` (${re})`:""}`:"",ue.style.display=""),z=me;let ut=t.getAll(),en=ut.length>0?ut[0].timestamp:0,an=new Set(R.map(et=>et.id));for(let et of Te)an.has(et)||Te.delete(et);let wn=A!==oe||L!==X,Ot=we.size===0&&R.length>0;if(wn||Ot||R.length===0){J.innerHTML="",we.clear();let et=document.createDocumentFragment();for(let _t=0;_t<R.length;_t++){let mt=vl(R[_t],_t,en,f,Te,yn,s,o);we.set(R[_t].id,mt),et.appendChild(mt)}J.appendChild(et),oe=A,X=L,se=null}else{if(se!==null){let _t=we.get(se);if(_t&&_t.parentNode===J){let mt=R.findIndex(tn=>tn.id===se);if(mt>=0){let tn=vl(R[mt],mt,en,f,Te,yn,s,o);J.insertBefore(tn,_t),_t.remove(),we.set(se,tn)}}se=null}let et=new Set(R.map(_t=>_t.id));for(let[_t,mt]of we)et.has(_t)||(mt.remove(),we.delete(_t));for(let _t=0;_t<R.length;_t++){let mt=R[_t];if(!we.has(mt.id)){let tn=vl(mt,_t,en,f,Te,yn,s,o);we.set(mt.id,tn),J.appendChild(tn)}}}j.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Ke(){if(Date.now()-Ie>=zh){ve!==null&&(cancelAnimationFrame(ve),ve=null),Sn();return}Ve||(Ve=!0,ve=requestAnimationFrame(()=>{ve=null,Sn()}))}let Ft=(de,me)=>{if(!K)return;K.innerHTML="";let Ee=Se(de,"12px","currentColor",1.5);Ee&&K.appendChild(Ee);let ut=y("span","persona-text-xs");ut.textContent="Copy All",K.appendChild(ut),setTimeout(()=>{K.innerHTML="";let en=Se("clipboard-copy","12px","currentColor",1.5);en&&K.appendChild(en);let an=y("span","persona-text-xs");an.textContent="Copy All",K.appendChild(an),K.disabled=!1},me)},q=async()=>{if(K){K.disabled=!0;try{let de;rt()?de=R:e?(de=await e(),de.length===0&&(de=t.getAll())):de=t.getAll();let me=de.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(me,null,2)),Ft("check",1500)}catch{Ft("x",1500)}}},ke=()=>{pe&&(A=pe.value,Nt(),Sn())},Ce=()=>{!ae||!Be||(Be.style.display=ae.value?"":"none",N&&clearTimeout(N),N=setTimeout(()=>{L=ae.value,Nt(),Sn()},150))},_e=()=>{!ae||!Be||(ae.value="",L="",Be.style.display="none",N&&clearTimeout(N),Nt(),Sn())},it=()=>{if(Ne)return;let de=J.scrollTop,{action:me,nextLastScrollTop:Ee}=pi({following:j.isFollowing(),currentScrollTop:de,lastScrollTop:qe,nearBottom:wr(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});qe=Ee,me==="resume"?(j.resume(),re=0,ue.style.display="none"):me==="pause"&&(j.pause(),d&&(Xe.textContent=g,ue.style.display=""))},pt=de=>{let me=ui({following:j.isFollowing(),deltaY:de.deltaY,nearBottom:wr(),resumeWhenNearBottom:!0});me==="pause"?(j.pause(),d&&(Xe.textContent=g,ue.style.display="")):me==="resume"&&(j.resume(),re=0,ue.style.display="none")},ot=()=>{d&&(J.scrollTop=J.scrollHeight,j.resume(),re=0,ue.style.display="none")},Mt=de=>{let me=de.target;if(!me||me.closest("button"))return;let Ee=me.closest("[data-event-id]");if(!Ee)return;let ut=Ee.getAttribute("data-event-id");ut&&yn(ut)},V=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),ae==null||ae.focus(),ae==null||ae.select();return}de.key==="Escape"&&(ae&&document.activeElement===ae?(_e(),ae.blur(),I.focus()):r&&r())};K&&K.addEventListener("click",q),pe&&pe.addEventListener("change",ke),ae&&ae.addEventListener("input",Ce),Be&&Be.addEventListener("click",_e),J.addEventListener("scroll",it),J.addEventListener("wheel",pt,{passive:!0}),J.addEventListener("click",Mt),ue.addEventListener("click",ot),I.addEventListener("keydown",V);function St(){N&&clearTimeout(N),ve!==null&&(cancelAnimationFrame(ve),ve=null),Ve=!1,we.clear(),K&&K.removeEventListener("click",q),pe&&pe.removeEventListener("change",ke),ae&&ae.removeEventListener("input",Ce),Be&&Be.removeEventListener("click",_e),J.removeEventListener("scroll",it),J.removeEventListener("wheel",pt),J.removeEventListener("click",Mt),ue.removeEventListener("click",ot),I.removeEventListener("keydown",V)}return{element:I,update:Ke,destroy:St}}}function Bm(n,t){let e=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 ${e} 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 g=document.createElement("div");g.className="persona-truncate persona-text-sm persona-font-medium",g.style.color="var(--persona-text, #1f2937)",g.textContent=e;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 u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,f.appendChild(m)}else f.textContent=a;if(c.append(g,f),i.append(d,c),o==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${e}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",r),i.append(u)}return i}var Hm=(n,t)=>{var r,o,s;let e=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(e){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",g=e({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>Bm(n,t)});if(g)return g}return Bm(n,t)};var xl=class{constructor(){this.components=new Map}register(t,e){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,e)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([e,r])=>{this.register(e,r)})}},Vo=new xl;Vo.register("PersonaArtifactCard",Hm);function eb(n){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),e=y("div","persona-font-semibold persona-text-sm persona-mb-2");e.textContent=n.component?`Component: ${n.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=n.props)!=null?o:{},null,2),t.appendChild(e),t.appendChild(r),t}function Dm(n,t){var pe,K,ae,Be;let e=(K=(pe=n.features)==null?void 0:pe.artifacts)==null?void 0:K.layout,o=((ae=e==null?void 0:e.toolbarPreset)!=null?ae:"default")==="document",s=(Be=e==null?void 0:e.panePadding)==null?void 0:Be.trim(),a=n.markdown?Oa(n.markdown):null,i=$a(n.sanitize),d=ee=>{let Z=a?a(ee):ho(ee);return i?i(Z):Z},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,g=()=>{c==null||c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var ee;g(),(ee=t.onDismiss)==null||ee.call(t)});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 u=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");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&u.classList.add("persona-artifact-toolbar-document");let m=y("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=y("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 ee;g(),(ee=t.onDismiss)==null||ee.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),M=o?Pn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Pn({icon:"eye",label:"Rendered view"}),S=o?Pn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Pn({icon:"code-2",label:"Source"}),B=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),I=(e==null?void 0:e.documentToolbarShowCopyLabel)===!0,R=(e==null?void 0:e.documentToolbarShowCopyChevron)===!0,A=e==null?void 0:e.documentToolbarCopyMenuItems,L=!!(R&&A&&A.length>0),N=null,F,k=null,z=null;if(o&&(I||R)&&!L){if(F=I?dl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let ee=Se("chevron-down",14,"currentColor",2);ee&&F.appendChild(ee)}}else o&&L?(N=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),F=I?dl({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Pn({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(F,k)):o?F=Pn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):F=Pn({icon:"copy",label:"Copy"});let j=o?Pn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Pn({icon:"refresh-cw",label:"Refresh"}),re=o?Pn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Pn({icon:"x",label:"Close"}),Ie=()=>{var at,nt,Me;let ee=(at=we.find(he=>he.id===oe))!=null?at:we[we.length-1],Z=(nt=ee==null?void 0:ee.id)!=null?nt:null,ne=(ee==null?void 0:ee.artifactType)==="markdown"&&(Me=ee.markdown)!=null?Me:"",st=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:ne,jsonPayload:st,id:Z}},Ve=async()=>{var at;let{markdown:ee,jsonPayload:Z}=Ie(),ne=(at=we.find(nt=>nt.id===oe))!=null?at:we[we.length-1],st=(ne==null?void 0:ne.artifactType)==="markdown"?ee:ne?Z:"";try{await navigator.clipboard.writeText(st)}catch{}};if(F.addEventListener("click",async()=>{let ee=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;if(ee&&L){let{markdown:Z,jsonPayload:ne,id:st}=Ie();try{await ee({actionId:"primary",artifactId:st,markdown:Z,jsonPayload:ne})}catch{}return}await Ve()}),k&&(A!=null&&A.length)){let ee=()=>{var ne;return(ne=f.closest("[data-persona-root]"))!=null?ne:document.body},Z=()=>{z=xs({items:A.map(ne=>({id:ne.id,label:ne.label})),onSelect:async ne=>{let{markdown:st,jsonPayload:at,id:nt}=Ie(),Me=e==null?void 0:e.onDocumentToolbarCopyMenuSelect;try{Me?await Me({actionId:ne,artifactId:nt,markdown:st,jsonPayload:at}):ne==="markdown"||ne==="md"?await navigator.clipboard.writeText(st):ne==="json"||ne==="source"?await navigator.clipboard.writeText(at):await navigator.clipboard.writeText(st||at)}catch{}},anchor:N!=null?N:k,position:"bottom-right",portal:ee()})};f.isConnected?Z():requestAnimationFrame(Z),k.addEventListener("click",ne=>{ne.stopPropagation(),z==null||z.toggle()})}j.addEventListener("click",async()=>{var ee;try{await((ee=e==null?void 0:e.onDocumentToolbarRefresh)==null?void 0:ee.call(e))}catch{}se()}),re.addEventListener("click",()=>{var ee;g(),(ee=t.onDismiss)==null||ee.call(t)});let ve=()=>{o&&(M.setAttribute("aria-pressed",x==="rendered"?"true":"false"),S.setAttribute("aria-pressed",x==="source"?"true":"false"))};M.addEventListener("click",()=>{x="rendered",ve(),se()}),S.addEventListener("click",()=>{x="source",ve(),se()});let Ne=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?(u.replaceChildren(),E.append(M,S),N?B.append(N,j,re):B.append(F,j,re),u.append(E,Ne,B),ve()):(u.appendChild(m),u.appendChild(v)),s&&(u.style.paddingLeft=s,u.style.paddingRight=s);let qe=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"),Te=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(qe.style.paddingLeft=s,qe.style.paddingRight=s,Te.style.padding=s),f.appendChild(u),f.appendChild(qe),f.appendChild(Te);let we=[],oe=null,X=!1,se=()=>{var st,at,nt,Me;let ee=o&&we.length<=1;qe.classList.toggle("persona-hidden",ee),qe.replaceChildren();for(let he of we){let Ge=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");Ge.type="button",Ge.textContent=he.title||he.id.slice(0,8),he.id===oe&&Ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ge.addEventListener("click",()=>t.onSelect(he.id)),qe.appendChild(Ge)}Te.replaceChildren();let Z=oe&&we.find(he=>he.id===oe)||we[we.length-1];if(!Z)return;if(o){let he=Z.artifactType==="markdown"?"MD":(st=Z.component)!=null?st:"Component",J=(Z.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ne.textContent=`${J} \xB7 ${he}`}else m.textContent="Artifacts";if(Z.artifactType==="markdown"){if(o&&x==="source"){let Ge=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ge.textContent=(at=Z.markdown)!=null?at:"",Te.appendChild(Ge);return}let he=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");he.innerHTML=d((nt=Z.markdown)!=null?nt:""),Te.appendChild(he);return}let ne=Z.component?Vo.get(Z.component):void 0;if(ne){let Ge={message:{id:Z.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let J=ne((Me=Z.props)!=null?Me:{},Ge);if(J){Te.appendChild(J);return}}catch{}}Te.appendChild(eb(Z))},fe=()=>{var Z;let ee=we.length>0;if(f.classList.toggle("persona-hidden",!ee),c){let ne=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,at=((Z=ne==null?void 0:ne.classList.contains("persona-artifact-narrow-host"))!=null?Z:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;ee&&at&&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(ee){var Z,ne,st;we=ee.artifacts,oe=(st=(ne=ee.selectedId)!=null?ne:(Z=ee.artifacts[ee.artifacts.length-1])==null?void 0:Z.id)!=null?st:null,we.length>0&&(X=!0),se(),fe()},setMobileOpen(ee){X=ee,!ee&&c?(c.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):fe()}}}function pr(n){var t,e;return((e=(t=n==null?void 0:n.features)==null?void 0:t.artifacts)==null?void 0:e.enabled)===!0}function Nm(n,t){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"),!pr(t))return;let e=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=e==null?void 0:e.paneBorder)==null?void 0:i.trim(),o=(d=e==null?void 0:e.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 tb(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 Li(n,t){var d,c,g,f,u,m,v,x,E,M;if(!pr(t)){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"),tb(n),Nm(n,t);return}let e=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(g=e==null?void 0:e.splitGap)!=null?g:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(f=e==null?void 0:e.paneWidth)!=null?f:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(u=e==null?void 0:e.paneMaxWidth)!=null?u:"28rem"),e!=null&&e.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",e.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=e==null?void 0:e.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(v=e==null?void 0:e.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=e==null?void 0:e.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=(E=e==null?void 0:e.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(M=e==null?void 0:e.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"),Nm(n,t)}var Fm=["panel","seamless"];function Ii(n,t){var i,d,c,g,f,u;for(let m of Fm)n.classList.remove(`persona-artifact-appearance-${m}`);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"),!pr(t))return;let e=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=e==null?void 0:e.paneAppearance)!=null?c:"panel",o=Fm.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(g=e==null?void 0:e.paneBorderRadius)==null?void 0:g.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(f=e==null?void 0:e.paneShadow)==null?void 0:f.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(e==null?void 0:e.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((u=e.unifiedSplitOuterRadius)==null?void 0:u.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function _m(n,t){var e,r,o;return!t||!pr(n)?!1:((o=(r=(e=n.features)==null?void 0:e.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function nb(n,t){if(!(n!=null&&n.trim()))return t;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):t}function rb(n){if(!(n!=null&&n.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):null}function ob(n,t,e){return e<t?t:Math.min(e,Math.max(t,n))}function sb(n,t,e,r){let o=n-r-2*t-e;return Math.max(0,o)}function Om(n,t){var a;let r=(a=(t.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 $m(n,t,e,r,o,s){let a=nb(o,200),i=sb(t,e,r,200);i=Math.max(a,i);let d=rb(s);return d!==null&&(i=Math.min(i,d)),ob(n,a,i)}var qm={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"}},wl=(n,t,e,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=qm[a])!=null?x:qm.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 M=y("p","persona-text-sm persona-text-persona-muted");M.textContent=i.description,d.appendChild(M)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(M=>{var A,L;let S=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${t.id}-${a}-${M.name}`;let B=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");B.textContent=M.label,S.appendChild(B);let I=(A=M.type)!=null?A:"text",R;I==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=I),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=`${t.id}-${a}-${M.name}`,R.name=M.name,R.placeholder=(L=M.placeholder)!=null?L:"",M.required&&(R.required=!0),S.appendChild(R),g.appendChild(S)});let f=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=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=(E=i.submitLabel)!=null?E:"Submit",f.appendChild(u),f.appendChild(m),g.appendChild(f),s.replaceChildren(d,g),g.addEventListener("submit",async M=>{var R,A;M.preventDefault();let S=(R=e.formEndpoint)!=null?R:"/form",B=new FormData(g),I={};B.forEach((L,N)=>{I[N]=L}),I.type=a,m.disabled=!0,u.textContent="Submitting\u2026";try{let L=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!L.ok)throw new Error(`Form submission failed (${L.status})`);let N=await L.json();u.textContent=(A=N.message)!=null?A:"Thanks! We'll be in touch soon.",N.success&&N.nextPrompt&&await r.sendMessage(String(N.nextPrompt))}catch(L){u.textContent=L instanceof Error?L.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Cl=class{constructor(){this.plugins=new Map}register(t){var e;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(e=t.onRegister)==null||e.call(t)}unregister(t){var r;let e=this.plugins.get(t);e&&((r=e.onUnregister)==null||r.call(e),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,e)=>{var r,o;return((r=e.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let e=this.getAll();if(!t||t.length===0)return e;let r=new Set(t.map(s=>s.id));return[...e.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var e;return(e=t.onUnregister)==null?void 0:e.call(t)}),this.plugins.clear()}},Al=new Cl;var Um=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>e(o,s)),e=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:t,off:e,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 ab=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},ib=n=>{let t=n.trim(),e=t.indexOf("{");if(e===-1)return null;let r=0;for(let o=e;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(e,o+1)}return null},Tl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=ab(n),e=ib(t);if(!e)return null;let r=JSON.parse(e);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=n=>typeof n=="string"?n:n==null?"":String(n),ya={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Sl(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let e=n.payload,r=Sl(e.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.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(e.text)}}},zm=n=>Array.isArray(n)?n.map(t=>String(t)):[],El=n=>{let t=new Set(zm(n.getSessionMetadata().processedActionMessageIds)),e=()=>{t=new Set(zm(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="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,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;t.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 g=()=>{n.emit("action:resubmit",d)},f=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:g});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:e}};var lb=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},cb=n=>n.map(t=>({...t,streaming:!1})),db=n=>n.map(t=>({...t,status:"complete"})),jm=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let e=t();return e?lb(e.getItem(n)):null},save:e=>{let r=t();if(r)try{let o={...e,messages:e.messages?cb(e.messages):void 0,artifacts:e.artifacts?db(e.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let e=t();if(e)try{e.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Ml=require("partial-json");function Vm(n,t){let{config:e,message:r,onPropsUpdate:o}=t,s=Vo.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:e,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 Km(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let t=n.content.trim();if(t.startsWith("{")||t.startsWith("["))return n.content}return null}function Gm(n){let t=Km(n);if(!t)return!1;try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"}catch{return!1}}function Qm(n){let t=Km(n);if(!t)return null;try{let e=JSON.parse(t);if(typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"){let r=e;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var pb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xm(n){let{onSubmit:t,onDismiss:e,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=pb}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,m.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,m.appendChild(x),u.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let M=[];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=`
27
+ `,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 pm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=cm(n),s=dm(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 gh=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}},fh=(n,e)=>{if(!n)return null;let t=gh(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},hh=(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},yh=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,mm=320,bh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),vh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),wh=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Ch=(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=`${mm}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}),yh(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}},Ah=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}},Sh=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=`${mm}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}},Th=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},Mh=(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()},Eh=(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},um=(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},kh=(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},Lh=(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=kh(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=bh(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.streaming&&D.classList.add("persona-content-streaming"),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=um(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=Ch(I,!F&&!!M,()=>{F&&ne&&(ne.style.display="")});J?x.appendChild(J):F&&ne&&(ne.style.display="")}let Re=vh(n);if(Re.length>0){let J=Ah(Re);J&&x.appendChild(J)}let Ue=xh(n);if(Ue.length>0){let J=Sh(Ue);J&&x.appendChild(J)}let xe=wh(n);if(xe.length>0){let J=Th(xe);J&&x.appendChild(J)}if(x.appendChild(D),f&&u==="below"&&n.createdAt){let J=um(n,c);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ie=n.role==="assistant"?fh(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=Mh("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(hh(n.stopReason,Ie))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=Lh(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=Eh(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,Ph=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Ih=(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(`
28
+ `):""},gm=(n,e)=>{let t=ds.has(n),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",t?"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=Ae(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},Ki=(n,e)=>{var Ue,xe,Ie,_e,Se,ve,re,X,ie,he,oe;let t=n.reasoning,r=b("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-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let o=(xe=(Ue=e==null?void 0:e.features)==null?void 0:Ue.reasoningDisplay)!=null?xe:{},s=o.expandable!==!1,a=s&&ds.has(n.id),i=t.status!=="complete",d=Ih(n,(Ie=o.previewMaxLines)!=null?Ie:3),c=b("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 m=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",u=(_e=e==null?void 0:e.reasoning)!=null?_e:{},v=String((Se=t.startedAt)!=null?Se:Date.now()),x=()=>{let K=b("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=Ca(t),K},I=(ve=u.renderCollapsedSummary)==null?void 0:ve.call(u,{message:n,reasoning:t,defaultSummary:g,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ca(t),createElapsedElement:x});typeof I=="string"&&I.trim()?(f.textContent=I,m.appendChild(f)):I instanceof HTMLElement?m.appendChild(I):(f.textContent=g,m.appendChild(f));let M=b("span","persona-text-xs persona-text-persona-primary");M.textContent=mu(t),m.appendChild(M);let E=(re=o.loadingAnimation)!=null?re:"none",F=u.activeTextTemplate,L=u.completeTextTemplate,R=i?F:L,A=I instanceof HTMLElement,W=(K,te,qe)=>{let Y=qe;for(let le of te){let Pe=b("span","persona-tool-char");Pe.style.setProperty("--char-index",String(Y)),Pe.textContent=le===" "?"\xA0":le,K.appendChild(Pe),Y++}return Y},N=(K,te)=>{f.textContent="";let qe=Aa(K,""),Y=0;for(let le of qe){let Pe=le.styles.length>0?(()=>{let it=b("span",le.styles.map(lt=>`persona-tool-text-${lt}`).join(" "));return f.appendChild(it),it})():f;if(le.isDuration&&i)Pe.appendChild(x());else{let it=le.isDuration?Ca(t):le.text;te?Y=W(Pe,it,Y):Pe.appendChild(document.createTextNode(it))}}};if(!A&&R)if(M.style.display="none",f.style.display="",i&&E!=="none"){let K=(X=u.loadingAnimationDuration)!=null?X:2e3;f.setAttribute("data-preserve-animation","true"),E==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),N(R,!1)):(f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor)),N(R,!0))}else N(R,!1);else if(!A&&i&&E!=="none"){f.style.display="";let K=(ie=u.loadingAnimationDuration)!=null?ie:2e3;if(f.setAttribute("data-preserve-animation","true"),E==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{f.classList.add(`persona-tool-loading-${E}`),f.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(u.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",u.loadingAnimationColor),u.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",u.loadingAnimationSecondaryColor));let te=f.textContent||g;f.textContent="",W(f,te,0)}t.status==="complete"&&(f.style.display="none")}else A||(t.status==="complete"?f.style.display="none":f.style.display="");let D=null;if(s){D=b("div","persona-flex persona-items-center");let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show";let qe=b("div","persona-flex persona-items-center persona-ml-auto");qe.append(D),c.append(m,qe)}else c.append(m);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=(oe=(he=e==null?void 0:e.reasoning)==null?void 0:he.renderCollapsedPreview)==null?void 0:oe.call(he,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});Ph(k,K)||(k.textContent=d),k.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,k),r;let j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=a?"":"none";let V=t.chunks.join(""),ne=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return ne.textContent=V||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(ne),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),D){D.innerHTML="";let te=Ae(a?"chevron-up":"chevron-down",16,"currentColor",2);te?D.appendChild(te):D.textContent=a?"Hide":"Show"}j.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,j),r};var ps=new Set,Wh=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Rh=(n,e)=>{var s;let t=n.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
29
+ `);let o=rs(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
30
+ `):""},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)"},Hh=(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=Rh(n,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=t?gu(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}},fm=(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}=Hh(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:{}});Wh(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,Bh=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)},hm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,ym=(n,e)=>{var r,o,s;let t=(o=(r=hm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ya.get(n))!=null?s:t==="expanded"},bm=(n,e,t)=>{var a,i;let r=hm(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)}},vm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=ym(n,t);bm(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:Bh(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=ym(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),bm(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 xm=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 Dh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Nh=new Set(["step_start","execution_start"]),Fh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Oh=new Set(["step_complete","agent_turn_complete"]),_h=new Set(["flow_complete","agent_complete"]),wm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Am=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 Am(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 $h(n,e){return typeof e.type=="string"?e.type:n}function Uh(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 qh(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 Cm(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 zh(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 jh(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ea=class{constructor(e=jh){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(!Am(t)){wm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=$h(e,t),o=this.now();if(Dh.has(r)){this.startRun(o);return}if(Nh.has(r)){this.run||this.startRun(o);return}if(Fh.has(r)){if(!qh(r,t))return;let a=Uh(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(Oh.has(r)){if(!this.run)return;let a=this.run,i=Cm(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(_h.has(r)){if(!this.run)return;let a=this.run,i=Cm(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(wm.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=zh(t);return s!=null?s:r-e.startedAt}};function us(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var Vh={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)"}},Kh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Gh=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qh=100;function Xh(n,e){let t={...Vh,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return Kh}function Jh(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function Yh(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 Zh(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 ey(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 ty(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 ny(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function ry(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 oy(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"?Jh(n.timestamp,t):Yh(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=Xh(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:Gh,W=Zh(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 ey(ty(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(oy(n,a,i)),u}}function Sm(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=ny(G);let de=ry(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>=Qh){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 Tm(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 Mm=(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:()=>Tm(n,e)});if(m)return m}return Tm(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",Mm);function sy(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 Em(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(sy(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&&lt&&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 km(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 ay(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"),ay(n),km(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"),km(n,e)}var Lm=["panel","seamless"];function ni(n,e){var i,d,c,m,f,g;for(let u of Lm)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=Lm.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 Pm(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 iy(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 ly(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 cy(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function dy(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Im(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 Wm(n,e,t,r,o,s){let a=iy(o,200),i=dy(e,t,r,200);i=Math.max(a,i);let d=ly(s);return d!==null&&(i=Math.min(i,d)),cy(n,a,i)}var Rm={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=Rm[a])!=null?x:Rm.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 Hm=()=>{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 py=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},uy=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=py(n),t=uy(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)}}},Bm=n=>Array.isArray(n)?n.map(e=>String(e)):[],ol=n=>{let e=new Set(Bm(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Bm(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 my=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}},gy=n=>n.map(e=>({...e,streaming:!1})),fy=n=>n.map(e=>({...e,status:"complete"})),Dm=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?my(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?gy(t.messages):void 0,artifacts:t.artifacts?fy(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 Nm(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 Fm(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 Om(n){let e=Fm(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 _m(n){let e=Fm(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 hy=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function $m(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=hy}=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=`
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
- `,L.addEventListener("click",()=>{f=A,M.forEach((N,F)=>{let k=F<A;N.classList.toggle("selected",k),N.setAttribute("aria-checked",F===A-1?"true":"false")})}),M.push(L),E.appendChild(L)}u.appendChild(E);let S=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),A.appendChild(S),u.appendChild(A)}let B=document.createElement("div");B.className="persona-feedback-actions";let I=document.createElement("button");I.type="button",I.className="persona-feedback-btn persona-feedback-btn-skip",I.textContent=i,I.addEventListener("click",()=>{e==null||e(),g.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){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let A=(S==null?void 0:S.value.trim())||void 0;await t(f,A),g.remove()}catch(A){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),B.appendChild(I),B.appendChild(R),u.appendChild(B),g.appendChild(u),g}function Jm(n){let{onSubmit:t,onDismiss:e,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:g="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 u=null,m=document.createElement("div");m.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 E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),m.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 S=document.createElement("div");S.className="persona-feedback-labels";let B=document.createElement("span");B.className="persona-feedback-label-low",B.textContent=c;let I=document.createElement("span");I.className="persona-feedback-label-high",I.textContent=g,S.appendChild(B),S.appendChild(I);let R=document.createElement("div");R.className="persona-feedback-numbers";let A=[];for(let z=0;z<=10;z++){let j=document.createElement("button");j.type="button",j.className="persona-feedback-rating-btn persona-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${z} out of 10`),j.textContent=String(z),j.dataset.rating=String(z),z<=6?j.classList.add("persona-feedback-detractor"):z<=8?j.classList.add("persona-feedback-passive"):j.classList.add("persona-feedback-promoter"),j.addEventListener("click",()=>{u=z,A.forEach((re,Ie)=>{re.classList.toggle("selected",Ie===z),re.setAttribute("aria-checked",Ie===z?"true":"false")})}),A.push(j),R.appendChild(j)}M.appendChild(S),M.appendChild(R),m.appendChild(M);let L=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(L),m.appendChild(z)}let N=document.createElement("div");N.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=i,F.addEventListener("click",()=>{e==null||e(),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(u===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let z=(L==null?void 0:L.value.trim())||void 0;await t(u,z),f.remove()}catch(z){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),N.appendChild(F),N.appendChild(k),m.appendChild(N),f.appendChild(m),f}var Ss="persona-chat-history",ub=30*1e3,mb={"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 gb(n){var r,o,s;if(!n)return[];let t=[],e=Array.from((r=n.items)!=null?r:[]);for(let a of e){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=mb[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Pi(n){if(!n)return!1;let t=n.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function fb(n){var t,e,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:(t=n.storage)!=null?t:"session",keyPrefix:(e=n.keyPrefix)!=null?e:"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 hb(n){try{let t=n==="local"?localStorage:sessionStorage,e="__persist_test__";return t.setItem(e,"1"),t.removeItem(e),t}catch{return null}}var kl=n=>!n||typeof n!="object"?{}:{...n},Ym=n=>n.map(t=>({...t,streaming:!1})),Zm=(n,t,e)=>{let r=n!=null&&n.markdown?Oa(n.markdown):null,o=$a(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 c,g,f;let a=(c=s.text)!=null?c:"",i=(g=s.message.rawContent)!=null?g:null;if(t){let u=t.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&&e&&e())}let d;return n!=null&&n.postprocessMessage?d=n.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""}):r?d=r(a):d=ho(a),o?o(d):d}};function eg(n){var i,d,c,g;let t=y("div","persona-attachment-drop-overlay");n!=null&&n.background&&t.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&t.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&t.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let e=(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=(g=n==null?void 0:n.iconStrokeWidth)!=null?g:.5,a=Se(e,r,o,s);if(a&&t.appendChild(a),n!=null&&n.label){let f=y("span","persona-drop-overlay-label");f.textContent=n.label,t.appendChild(f)}return t}var tg=(n,t,e)=>{var Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,bc,yc,vc,xc,wc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Ic,Pc,Wc,Rc,Bc,Hc,Dc,Nc,Fc,_c,Oc,$c,qc,Uc,zc,jc,Vc,Kc;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=Qu(t),o=Al.getForInstance(r.plugins);r.components&&Vo.registerAll(r.components);let s=Um(),i=r.persistState===!1?null:(Yl=r.storageAdapter)!=null?Yl:jm(),d={},c=null,g=!1,f=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(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=kl(h.metadata)),(Zl=h.messages)!=null&&Zl.length&&(r={...r,initialMessages:h.messages}),(ec=h.artifacts)!=null&&ec.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(tc=h.selectedArtifactId)!=null?tc: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:{}});(nc=l.messages)!=null&&nc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>d,m=l=>{var h;d=(h=l({...d}))!=null?h:{},es()},v=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Tl],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick],E=El({parsers:v,handlers:x,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let M=(oc=(rc=r.launcher)==null?void 0:rc.enabled)!=null?oc:!0,S=(ac=(sc=r.launcher)==null?void 0:sc.autoExpand)!=null?ac:!1,B=(ic=r.autoFocusInput)!=null?ic:!1,I=S,R=M,A=(cc=(lc=r.layout)==null?void 0:lc.header)==null?void 0:cc.layout,L=!1,N=()=>ua(r),F=()=>M||N(),k=N()?!1:M?S:!0,z=!1,j=null,re=()=>{z=!0,j&&clearTimeout(j),j=setTimeout(()=>{z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),z=!1)},1e4)},Ie=Zm(r,E,re),Ve=(pc=(dc=r.features)==null?void 0:dc.showReasoning)!=null?pc:!0,ve=(mc=(uc=r.features)==null?void 0:uc.showToolCalls)!=null?mc:!0,Ne=(fc=(gc=r.features)==null?void 0:gc.showEventStreamToggle)!=null?fc:!1,qe=(bc=(hc=r.features)==null?void 0:hc.scrollToBottom)!=null?bc:{},Te=(vc=(yc=r.features)==null?void 0:yc.scrollBehavior)!=null?vc:{},oe=`${(wc=typeof r.persistState=="object"?(xc=r.persistState)==null?void 0:xc.keyPrefix:void 0)!=null?wc:"persona-"}event-stream`,X=Ne?new ha(oe):null,se=(Sc=(Ac=(Cc=r.features)==null?void 0:Cc.eventStream)==null?void 0:Ac.maxEvents)!=null?Sc:2e3,fe=Ne?new fa(se,X):null,pe=Ne?new ba:null,K=null,ae=!1,Be=null,ee=0;X==null||X.open().then(()=>fe==null?void 0:fe.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Z={onCopy:l=>{var p,h;s.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.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;s.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.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)}},ne=(Tc=r.statusIndicator)!=null?Tc:{},st=l=>{var p,h,b,T;return l==="idle"?(p=ne.idleText)!=null?p:Ln.idle:l==="connecting"?(h=ne.connectingText)!=null?h:Ln.connecting:l==="connected"?(b=ne.connectedText)!=null?b:Ln.connected:l==="error"?(T=ne.errorText)!=null?T:Ln.error:Ln[l]};function at(l,p,h,b){if(b==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=p,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=p}let nt=xm({config:r,showClose:F()}),{wrapper:Me,panel:he,pillRoot:Ge}=nt.shell,J=nt.panelElements,{container:ue,body:Le,messagesWrapper:Xe,suggestions:Gt,textarea:Pe,sendButton:Ue,sendButtonWrapper:rt,composerForm:Nt,statusText:yn,introTitle:wr,introSubtitle:Sn,closeButton:Ke,iconHolder:Ft,headerTitle:q,headerSubtitle:ke,header:Ce,footer:_e,actionsRow:it,leftActions:pt,rightActions:ot}=J,Mt=J.setSendButtonMode,V=J.micButton,St=J.micButtonWrapper,de=J.attachmentButton,me=J.attachmentButtonWrapper,Ee=J.attachmentInput,ut=J.attachmentPreviewsContainer;ue.classList.add("persona-relative"),Le.classList.add("persona-relative");let en=12,an=()=>{var l;return(l=qe.label)!=null?l:""},wn=()=>{var l;return(l=qe.iconName)!=null?l:"arrow-down"},Ot=()=>qe.enabled!==!1,et=()=>{var l;return(l=Te.mode)!=null?l:"follow"},_t=()=>{var l;return(l=Te.anchorTopOffset)!=null?l:16},mt=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");mt.type="button",mt.style.display="none",mt.setAttribute("data-persona-scroll-to-bottom","true");let tn=y("span","persona-flex persona-items-center"),rr=y("span",""),Wn=y("span","");Wn.setAttribute("data-persona-scroll-to-bottom-count",""),Wn.style.display="none",mt.append(tn,rr,Wn),ue.appendChild(mt);let ln=y("div","persona-stream-anchor-spacer");ln.setAttribute("aria-hidden","true"),ln.setAttribute("data-persona-anchor-spacer",""),ln.style.flexShrink="0",ln.style.pointerEvents="none",ln.style.height="0px",Le.appendChild(ln);let On=()=>{let p=_e.style.display==="none"?0:_e.offsetHeight;mt.style.bottom=`${p+en}px`};On();let Cr=()=>{let l=!!an();mt.setAttribute("aria-label",an()||"Jump to latest"),mt.title=an(),mt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),tn.innerHTML="";let p=Se(wn(),"14px","currentColor",2);p?(tn.appendChild(p),tn.style.display=""):tn.style.display="none",rr.textContent=an(),rr.style.display=l?"":"none"};Cr();let Ct=null,jn=null,Ar=o.find(l=>l.renderHeader);if(Ar!=null&&Ar.renderHeader){let l=Ar.renderHeader({config:r,defaultRenderer:()=>{let p=zo({config:r,showClose:F()});return ma(ue,p,r),p.header},onClose:()=>be(!1,"user")});if(l){let p=ue.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Ce=l,nt.header.element=l)}}let Nr=()=>{var p,h,b,T;if(!fe)return;if(ae=!0,!K&&fe&&(K=Rm({buffer:fe,getFullHistory:()=>fe.getAllFromStore(),onClose:()=>ur(),config:r,plugins:o,getThroughput:()=>{var D;return(D=pe==null?void 0:pe.getMetric())!=null?D:{status:"idle"}}})),K&&(Le.style.display="none",(p=_e.parentNode)==null||p.insertBefore(K.element,_e),K.update()),xt){xt.style.boxShadow=`inset 0 0 0 1.5px ${_n.actionIconColor}`;let D=(T=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(U=>U&&xt.classList.add(U))}let l=()=>{if(!ae)return;let D=Date.now();D-ee>=200&&(K==null||K.update(),ee=D),Be=requestAnimationFrame(l)};ee=0,Be=requestAnimationFrame(l),Un(),s.emit("eventStream:opened",{timestamp:Date.now()})},ur=()=>{var l,p,h;if(ae){if(ae=!1,K&&K.element.remove(),Le.style.display="",xt){xt.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(T=>T&&xt.classList.remove(T))}Be!==null&&(cancelAnimationFrame(Be),Be=null),Un(),s.emit("eventStream:closed",{timestamp:Date.now()})}},xt=null;if(Ne){let l=(Mc=(Ec=r.features)==null?void 0:Ec.eventStream)==null?void 0:Mc.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:"");xt=y("button",p),xt.style.width="28px",xt.style.height="28px",xt.style.color=_n.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let h=Se("activity","18px","currentColor",1.5);h&&xt.appendChild(h);let b=J.clearChatButtonWrapper,T=J.closeButtonWrapper,D=b||T;D&&D.parentNode===Ce?Ce.insertBefore(xt,D):Ce.appendChild(xt),xt.addEventListener("click",()=>{ae?ur():Nr()})}let Co=l=>{var T,D,U,_,H;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let le=l.querySelector("[data-persona-composer-form]");le!=null&&le.parentNode?le.parentNode.insertBefore(h,le):l.insertBefore(h,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let le=y("input");le.type="file",le.setAttribute("data-persona-composer-attachment-input",""),le.accept=((U=p.allowedTypes)!=null?U:Qr).join(","),le.multiple=((_=p.maxFiles)!=null?_:4)>1,le.style.display="none",le.setAttribute("aria-label",(H=p.buttonTooltipText)!=null?H:"Attach files"),l.appendChild(le)}},Sr=o.find(l=>l.renderComposer);if(Sr!=null&&Sr.renderComposer){let l=r.composer,p=Sr.renderComposer({config:r,defaultRenderer:()=>Ti({config:r}).footer,onSubmit:h=>{var U;if(!O||O.isStreaming())return;let b=h.trim(),T=(U=Ct==null?void 0:Ct.hasAttachments())!=null?U:!1;if(!b&&!T)return;Re();let D;T&&(D=[],D.push(...Ct.getContentParts()),b&&D.push(Zi(b))),O.sendMessage(b,{contentParts:D}),T&&Ct.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ee==null||Ee.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:((kc=r.voiceRecognition)==null?void 0:kc.enabled)===!0?()=>{jn==null||jn()}:void 0});p&&(nt.replaceComposer(p),_e=nt.composer.footer)}let Ao=l=>{let p=(...ce)=>{for(let Y of ce){let xe=l.querySelector(Y);if(xe)return xe}return null},h=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Nt=h),b&&(Pe=b),T&&(Ue=T),D&&(V=D,St=D.parentElement),U&&(yn=U);let _=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Gt=_);let H=p("[data-persona-composer-attachment-button]",".persona-attachment-button");H&&(de=H,me=H.parentElement),Ee=p("[data-persona-composer-attachment-input]",'input[type="file"]'),ut=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(it=le)};Co(_e),Ao(_e);let $n=(Rc=(Lc=r.layout)==null?void 0:Lc.contentMaxWidth)!=null?Rc:N()?(Wc=(Pc=(Ic=r.launcher)==null?void 0:Ic.composerBar)==null?void 0:Pc.contentMaxWidth)!=null?Wc:"720px":void 0;if($n&&(Xe.style.maxWidth=$n,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%"),$n&&Nt&&!N()&&(Nt.style.maxWidth=$n,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),$n&&Gt&&!N()&&(Gt.style.maxWidth=$n,Gt.style.marginLeft="auto",Gt.style.marginRight="auto"),$n&&ut&&!N()&&(ut.style.maxWidth=$n,ut.style.marginLeft="auto",ut.style.marginRight="auto"),(Bc=r.attachments)!=null&&Bc.enabled&&Ee&&ut){Ct=oa.fromConfig(r.attachments),Ct.setPreviewsContainer(ut),Ee.addEventListener("change",h=>{let b=h.target;Ct==null||Ct.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,p=eg(l);ue.appendChild(p)}(()=>{var b,T;let l=(T=(b=r.layout)==null?void 0:b.slots)!=null?T:{},p=D=>{switch(D){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Xe;case"footer-top":return Gt;case"composer":return Nt;case"footer-bottom":return yn;default:return null}},h=(D,U)=>{var _;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Ce.insertBefore(U,Ce.firstChild);else if(D==="header-right")Ce.appendChild(U);else{let H=Ce.querySelector(".persona-flex-col");H?(_=H.parentNode)==null||_.insertBefore(U,H.nextSibling):Ce.appendChild(U)}break;case"body-top":{let H=Le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(U):Le.insertBefore(U,Le.firstChild);break}case"body-bottom":Le.appendChild(U);break;case"footer-top":Gt.replaceWith(U);break;case"footer-bottom":yn.replaceWith(U);break;default:break}};for(let[D,U]of Object.entries(l))if(U)try{let _=U({config:r,defaultContent:()=>p(D)});_&&h(D,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,_)}})();let Yr=l=>{var U,_;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")ws.has(T)?ws.delete(T):ws.add(T),Am(T,b);else if(D==="tool")Cs.has(T)?Cs.delete(T):Cs.add(T),Sm(T,b,r);else if(D==="approval"){let H=r.approval!==!1?r.approval:void 0,le=((U=H==null?void 0:H.detailsDisplay)!=null?U:"collapsed")==="expanded",ce=(_=Ei.get(T))!=null?_:le;Ei.set(T,!ce),km(T,b,r)}Lr.delete(T)};Xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))}),Xe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Yr(l))});let Fr=new Map,Zr=null,eo="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(l,p)=>{let{icon:h,label:b}=So[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 T=Se(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},to=()=>{Xe.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;To(p,b&&b===Zr?eo:"idle")})};Xe.addEventListener("click",l=>{var U;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let T=b.getAttribute("data-actions-for");if(!T)return;let D=h.getAttribute("data-action");if(D==="copy"){let H=O.getMessages().find(le=>le.id===T);if(H&&Z.onCopy){let le=H.content||"";navigator.clipboard.writeText(le).then(()=>{h.classList.add("persona-message-action-success");let ce=Se("check",14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=Se("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ce=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ce)}),Z.onCopy(H)}}else if(D==="read-aloud")O.toggleReadAloud(T);else if(D==="upvote"||D==="downvote"){let H=((U=Fr.get(T))!=null?U:null)===D,le=D==="upvote"?"thumbs-up":"thumbs-down";if(H){Fr.delete(T),h.classList.remove("persona-message-action-active");let ce=Se(le,14,"currentColor",2);ce&&(h.innerHTML="",h.appendChild(ce))}else{let ce=D==="upvote"?"downvote":"upvote",Y=b.querySelector(`[data-action="${ce}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ze=Se(ce==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Y.innerHTML="",Y.appendChild(ze))}Fr.set(T,D),h.classList.add("persona-message-action-active");let xe=Se(le,14,"currentColor",2);xe&&(xe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(xe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=O.getMessages().find(tt=>tt.id===T);Ae&&Z.onFeedback&&Z.onFeedback({type:D,messageId:Ae.id,message:Ae})}}}),Xe.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let T=b.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-approval-action");if(!D)return;let U=D==="approve"?"approved":"denied",H=O.getMessages().find(ce=>ce.id===T);if(!(H!=null&&H.approval))return;let le=b.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),H.approval.toolType==="webmcp"?O.resolveWebMcpApproval(T,U):O.resolveApproval(H.approval,U)});let Tt=null,Vn=null,Kn={artifacts:[],selectedId:null},Rn=!1,kt={current:null};Xe.addEventListener("click",l=>{var Y,xe,Oe,Ae,tt;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Oe=(xe=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Oe.call(xe,{type:"download",artifactId:b}))===!0)return;let D=O.getArtifactById(b),U=D==null?void 0:D.markdown,_=(D==null?void 0:D.title)||"artifact";if(!U){let ze=h.closest("[data-open-artifact]"),bt=ze==null?void 0:ze.closest("[data-message-id]"),ct=bt==null?void 0:bt.getAttribute("data-message-id");if(ct){let We=O.getMessages().find(je=>je.id===ct);if(We!=null&&We.rawContent)try{let je=JSON.parse(We.rawContent);U=(Ae=je==null?void 0:je.props)==null?void 0:Ae.markdown,_=((tt=je==null?void 0:je.props)==null?void 0:tt.title)||_}catch{}}}if(!U)return;let H=new Blob([U],{type:"text/markdown"}),le=URL.createObjectURL(H),ce=document.createElement("a");ce.href=le,ce.download=`${_}.md`,ce.click(),URL.revokeObjectURL(le)}),Xe.addEventListener("click",l=>{var D,U,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(U=(D=r.features)==null?void 0:D.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:_.call(U,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Rn=!1,O.selectArtifact(b),Xn())}),Xe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let or=J.composerOverlay,sr=(l,p,h)=>{var _,H,le,ce;let b=p.trim();if(!b||!kt.current)return;let T=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",D=h.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:b,answers:h.structured,values:(H=h.values)!=null?H:h.source==="multi"?b.split(", "):[b],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),us(or,T);let U=kt.current.getMessages().find(Y=>{var xe;return((xe=Y.toolCall)==null?void 0:xe.id)===T});(le=U==null?void 0:U.agentMetadata)!=null&&le.awaitingLocalTool?kt.current.resolveAskUserQuestion(U,(ce=h.structured)!=null?ce:b):kt.current.sendMessage(b)},Gn=l=>{var T;let p=kt.current;if(!p)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",b=p.getMessages().find(D=>{var U;return((U=D.toolCall)==null?void 0:U.id)===h});b&&p.persistAskUserQuestionProgress(b,{answers:za(l,b),currentIndex:dr(l)})},no=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),_r=l=>{var T,D,U;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let p=dr(l),h=ps(l);if(p>=h-1)return;let b=(U=kt.current)==null?void 0:U.getMessages().find(_=>{var H;return((H=_.toolCall)==null?void 0:H.id)===l.getAttribute("data-tool-call-id")});b&&(Va(l,b,r,p+1),Gn(l))};or.addEventListener("click",l=>{var D,U,_,H,le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let He=(D=b.getAttribute("data-tool-call-id"))!=null?D:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),us(or,He);let We=(U=kt.current)==null?void 0:U.getMessages().find(je=>{var Qe;return((Qe=je.toolCall)==null?void 0:Qe.id)===He});(_=We==null?void 0:We.agentMetadata)!=null&&_.awaitingLocalTool&&((H=kt.current)==null||H.markAskUserQuestionResolved(We),(le=kt.current)==null||le.resolveAskUserQuestion(We,"(dismissed)"));return}if(T==="pick"){let He=h.getAttribute("data-option-label");if(!He)return;let We=b.getAttribute("data-multi-select")==="true",je=yo(b);if(je&&We){let Qe=_o(b)[dr(b)],wt=new Set(Array.isArray(Qe)?Qe:[]);wt.has(He)?wt.delete(He):wt.add(He),vo(b,Array.from(wt)),Gn(b);return}if(je){vo(b,He),Gn(b),_r(b);return}if(We){let Qe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Qe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Qe);let wt=b.querySelector('[data-ask-user-action="submit-multi"]');wt&&(wt.disabled=Ki(b).length===0);return}sr(b,He,{source:"pick",values:[He]});return}if(T==="submit-multi"){let He=Ki(b);if(He.length===0)return;sr(b,He.join(", "),{source:"multi",values:He});return}if(T==="open-free-text"){let He=b.querySelector('[data-ask-free-text-row="true"]');if(He){He.classList.remove("persona-hidden");let We=He.querySelector('[data-ask-free-text-input="true"]');We==null||We.focus()}return}if(T==="focus-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]');He==null||He.focus();return}if(T==="submit-free-text"){let He=b.querySelector('[data-ask-free-text-input="true"]'),We=(ce=He==null?void 0:He.value)!=null?ce:"";if(!We.trim())return;if(yo(b)){vo(b,We.trim()),Gn(b),_r(b);return}sr(b,We,{source:"free-text"});return}if(T==="next"||T==="back"){if(!kt.current)return;let He=(Y=b.getAttribute("data-tool-call-id"))!=null?Y:"",We=kt.current.getMessages().find(Fe=>{var De;return((De=Fe.toolCall)==null?void 0:De.id)===He});if(!We)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(Oe=(xe=je==null?void 0:je.value)==null?void 0:xe.trim())!=null?Oe:"";if(Qe){let Fe=_o(b)[dr(b)];(typeof Fe!="string"||Fe!==Qe)&&vo(b,Qe)}let wt=T==="next"?1:-1,W=dr(b)+wt;Va(b,We,r,W),Gn(b);return}if(T==="submit-all"){if(!kt.current)return;let He=(Ae=b.getAttribute("data-tool-call-id"))!=null?Ae:"",We=kt.current.getMessages().find(Fe=>{var De;return((De=Fe.toolCall)==null?void 0:De.id)===He});if(!We)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(tt=je==null?void 0:je.value)==null?void 0:tt.trim())!=null?ze:"";Qe&&vo(b,Qe);let wt=za(b,We);kt.current.persistAskUserQuestionProgress(We,{answers:wt,currentIndex:dr(b)});let W=no(wt);sr(b,W||"(submitted)",{source:"submit-all",structured:wt});return}if(T==="skip"){if(!kt.current)return;let He=(bt=b.getAttribute("data-tool-call-id"))!=null?bt:"",We=kt.current.getMessages().find(De=>{var ge;return((ge=De.toolCall)==null?void 0:ge.id)===He});if(!We)return;let je=yo(b),Qe=dr(b),wt=ps(b),W=Qe>=wt-1;if(!je){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:He},bubbles:!0,composed:!0})),us(or,He),(ct=We.agentMetadata)!=null&&ct.awaitingLocalTool&&(kt.current.markAskUserQuestionResolved(We),kt.current.resolveAskUserQuestion(We,"(dismissed)"));return}vo(b,"");let Fe=b.querySelector('[data-ask-free-text-input="true"]');if(Fe&&(Fe.value=""),W){let De=za(b,We),ge=no(De);sr(b,ge||"(skipped)",{source:"submit-all",structured:De});return}Va(b,We,r,Qe+1),Gn(b);return}}),or.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 T=h.value;if(T.trim()){if(yo(b)){vo(b,T.trim()),Gn(b),_r(b);return}sr(b,T,{source:"free-text"})}});let ro=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=or.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",ro);let Qn=null,$t=null,Bn=null,ar=null,oo=()=>{};function Or(){ar==null||ar(),ar=null}let so=()=>{var U;if(!Qn||!$t)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),h=((U=n.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||h){$t.style.removeProperty("position"),$t.style.removeProperty("left"),$t.style.removeProperty("top"),$t.style.removeProperty("bottom"),$t.style.removeProperty("width"),$t.style.removeProperty("z-index");return}let b=Qn.firstElementChild;if(!b||b===$t)return;let T=10;$t.style.position="absolute",$t.style.top="0",$t.style.bottom="0",$t.style.width=`${T}px`,$t.style.zIndex="5";let D=b.offsetWidth-T/2;$t.style.left=`${Math.max(0,D)}px`},Tr=()=>{},Xn=()=>{var h,b,T,D,U;if(!Tt||!pr(r))return;Li(n,r),Ii(n,r),Tr();let l=(D=(T=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,p=he.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),Tt.update(Kn),Rn?(Tt.setMobileOpen(!1),Tt.element.classList.add("persona-hidden"),(U=Tt.backdrop)==null||U.classList.add("persona-hidden")):Kn.artifacts.length>0&&(Tt.element.classList.remove("persona-hidden"),Tt.setMobileOpen(!0)),oo()};if(pr(r)){he.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(ue),Tt=Dm(r,{onSelect:h=>{var b;return(b=kt.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Rn=!0,Xn()}}),Tt.element.classList.add("persona-hidden"),Qn=p,p.appendChild(l),p.appendChild(Tt.element),Tt.backdrop&&he.appendChild(Tt.backdrop),he.appendChild(p),oo=()=>{var b,T,D,U;if(!Qn||!Tt)return;if(!(((D=(T=(b=r.features)==null?void 0:b.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Bn==null||Bn(),Bn=null,Or(),$t&&($t.remove(),$t=null),Tt.element.style.removeProperty("width"),Tt.element.style.removeProperty("maxWidth");return}if(!$t){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 H=n.ownerDocument,le=(U=H.defaultView)!=null?U:window,ce=Y=>{var bt,ct;if(!Tt||Y.button!==0||n.classList.contains("persona-artifact-narrow-host")||le.innerWidth<=640)return;Y.preventDefault(),Or();let xe=Y.clientX,Oe=Tt.element.getBoundingClientRect().width,Ae=(ct=(bt=r.features)==null?void 0:bt.artifacts)==null?void 0:ct.layout,tt=He=>{let We=Qn.getBoundingClientRect().width,je=n.classList.contains("persona-artifact-appearance-seamless"),Qe=je?0:Om(Qn,le),wt=je?0:_.getBoundingClientRect().width||6,W=Oe-(He.clientX-xe),Fe=$m(W,We,Qe,wt,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);Tt.element.style.width=`${Fe}px`,Tt.element.style.maxWidth="none",so()},ze=()=>{H.removeEventListener("pointermove",tt),H.removeEventListener("pointerup",ze),H.removeEventListener("pointercancel",ze),ar=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};ar=ze,H.addEventListener("pointermove",tt),H.addEventListener("pointerup",ze),H.addEventListener("pointercancel",ze);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",ce),$t=_,Qn.insertBefore(_,Tt.element),Bn=()=>{_.removeEventListener("pointerdown",ce)}}if($t){let _=Kn.artifacts.length>0&&!Rn;$t.classList.toggle("persona-hidden",!_),so()}},Tr=()=>{var le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We,je,Qe;if(!M||!Tt||((ce=(le=r.launcher)==null?void 0:le.sidebarMode)!=null?ce:!1)||An(r)&&vr(r).reveal==="emerge")return;let b=(Y=n.ownerDocument.defaultView)!=null?Y:window,T=(Oe=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?Oe:!0,D=(tt=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?tt:640;if(T&&b.innerWidth<=D||!_m(r,M))return;let U=(ct=(bt=(ze=r.launcher)==null?void 0:ze.width)!=null?bt:r.launcherWidth)!=null?ct:Xr,_=(Qe=(je=(We=(He=r.features)==null?void 0:He.artifacts)==null?void 0:We.layout)==null?void 0:je.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Kn.artifacts.length>0&&!Rn?(he.style.width=_,he.style.maxWidth=_):(he.style.width=U,he.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Vn=new ResizeObserver(()=>{Xn()}),Vn.observe(he))}else he.appendChild(ue),N()&&Ge&&(J.peekBanner&&Ge.appendChild(J.peekBanner),Ge.appendChild(_e));n.appendChild(Me),Ge&&n.appendChild(Ge);let ye=()=>{var Fe,De,ge,jt,Ut,Jt,At,Qt,Zn,sn,Je,Rt,pn,cr,er,Io,Po,ss,as,Yt,Wo,go,fo,Kr,Ro,hr,Ze,fn;if(N()){he.style.width="100%",he.style.maxWidth="100%";let Kt=(De=(Fe=r.launcher)==null?void 0:Fe.composerBar)!=null?De:{},Vt=Me.dataset.state==="expanded",yt=(ge=Kt.expandedSize)!=null?ge:"anchored";if(!(Vt&&yt!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Et=(Ut=(jt=r.theme)==null?void 0:jt.components)==null?void 0:Ut.panel,Mn=ii(r),Hn=(Nn,Bo)=>{var $s;return Nn==null||Nn===""?Bo:($s=ys(Mn,Nn))!=null?$s:Nn},Hr="1px solid var(--persona-border)",xn="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Hn(Et==null?void 0:Et.border,Hr),ue.style.borderRadius=Hn(Et==null?void 0:Et.borderRadius,Dn),ue.style.boxShadow=Hn(Et==null?void 0:Et.shadow,xn),ue.style.overflow="hidden";return}let l=An(r),p=(At=(Jt=r.launcher)==null?void 0:Jt.sidebarMode)!=null?At:!1,h=l||p||((Zn=(Qt=r.launcher)==null?void 0:Qt.fullHeight)!=null?Zn:!1),b=((sn=r.launcher)==null?void 0:sn.enabled)===!1,T=(Rt=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Rt.panel,D=ii(r),U=(Kt,Vt)=>{var yt;return Kt==null||Kt===""?Vt:(yt=ys(D,Kt))!=null?yt:Kt},_=(pn=n.ownerDocument.defaultView)!=null?pn:window,H=(er=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?er:!0,le=(Po=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Po:640,ce=_.innerWidth<=le,Y=H&&ce&&M,xe=(as=(ss=r.launcher)==null?void 0:ss.position)!=null?as:"bottom-left",Oe=xe==="bottom-left"||xe==="top-left",Ae=(Wo=(Yt=r.launcher)==null?void 0:Yt.zIndex)!=null?Wo:In,tt=p||Y?"none":"1px solid var(--persona-border)",ze=Y?"none":p?Oe?"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&&!Y&&(ze="none",tt="none");let bt=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ct=U(T==null?void 0:T.border,tt),He=U(T==null?void 0:T.shadow,ze),We=U(T==null?void 0:T.borderRadius,bt),je=Le.scrollTop;n.style.cssText="",Me.style.cssText="",he.style.cssText="",ue.style.cssText="",Le.style.cssText="",_e.style.cssText="";let Qe=()=>{var Vt;if(je<=0)return;((Vt=Le.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Le.scrollTop===je)return;let yt=Le.scrollHeight-Le.clientHeight;yt<=0||(Le.scrollTop=Math.min(je,yt))})};if(Y){Me.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"),Me.style.cssText=`
34
+ `,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 Um(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",yy=30*1e3,by={"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 vy(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=by[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 xy(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 wy(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},qm=n=>n.map(e=>({...e,streaming:!1})),zm=(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=s.streaming?Vp(a):a,v=r(u);c=o&&d?o(v):v}else c=so(a);return c}};function jm(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 Vm=(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=Ou(e),o=tl.getForInstance(r.plugins);r.components&&Do.registerAll(r.components);let s=Hm(),i=r.persistState===!1?null:(_l=r.storageAdapter)!=null?_l:Dm(),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=zm(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=pm({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=Sm({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=jm(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),gm(S,y);else if(H==="tool")ps.has(S)?ps.delete(S):ps.add(S),fm(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),vm(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=Vu(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=Em(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:Im($n,se),bt=ze?0:O.getBoundingClientRect().width||6,P=Fe-(Be.clientX-be),Ne=Wm(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||!Pm(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=`
33
35
  position: fixed !important;
34
36
  inset: 0 !important;
35
37
  width: 100% !important;
@@ -39,9 +41,9 @@ _Details: ${e.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
39
41
  padding: 0 !important;
40
42
  display: flex !important;
41
43
  flex-direction: column !important;
42
- z-index: ${Ae} !important;
44
+ z-index: ${Ce} !important;
43
45
  background-color: var(--persona-surface, #ffffff) !important;
44
- `,he.style.cssText=`
46
+ `,pe.style.cssText=`
45
47
  position: relative !important;
46
48
  display: flex !important;
47
49
  flex-direction: column !important;
@@ -54,7 +56,7 @@ _Details: ${e.message}_`:r}var ra=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
- `,ue.style.cssText=`
59
+ `,ce.style.cssText=`
58
60
  display: flex !important;
59
61
  flex-direction: column !important;
60
62
  flex: 1 1 0% !important;
@@ -65,20 +67,20 @@ _Details: ${e.message}_`:r}var ra=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
- `,Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.overflowY="auto",_e.style.flexShrink="0",L=!0,Qe();return}let wt=(fo=(go=r==null?void 0:r.launcher)==null?void 0:go.width)!=null?fo:r==null?void 0:r.launcherWidth,W=wt!=null?wt:Xr;if(!p&&!l)b&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=W,he.style.maxWidth=W);else if(l)if(vr(r).reveal==="emerge"){let Vt=vr(r).width;he.style.width=Vt,he.style.maxWidth=Vt}else he.style.width="100%",he.style.maxWidth="100%";if(Tr(),he.style.boxShadow=He,he.style.borderRadius=We,ue.style.border=ct,ue.style.borderRadius=We,l&&!Y&&(T==null?void 0:T.border)===void 0&&(ue.style.border="none",vr(r).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",b&&(n.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",b&&(Me.style.overflow="hidden"),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%",he.style.overflow="hidden",ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.overflowY="auto",_e.style.flexShrink="0"),Me.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&&((Kr=xr[xe])!=null?Kr:xr["bottom-right"]).split(" ").forEach(Vt=>Me.classList.add(Vt)),p){let Kt=(hr=(Ro=r.launcher)==null?void 0:Ro.sidebarWidth)!=null?hr:"420px";Me.style.cssText=`
70
+ `,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0",W=!0,Ke();return}let bt=(oo=(ro=r==null?void 0:r.launcher)==null?void 0:ro.width)!=null?oo:r==null?void 0:r.launcherWidth,P=bt!=null?bt:qr;if(!p&&!l)y&&h?(pe.style.width="100%",pe.style.maxWidth="100%"):(pe.style.width=P,pe.style.maxWidth=P);else if(l)if(gr(r).reveal==="emerge"){let Ot=gr(r).width;pe.style.width=Ot,pe.style.maxWidth=Ot}else pe.style.width="100%",pe.style.maxWidth="100%";if(xr(),pe.style.boxShadow=Be,pe.style.borderRadius=We,ce.style.border=st,ce.style.borderRadius=We,l&&!Z&&(S==null?void 0:S.border)===void 0&&(ce.style.border="none",gr(r).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),h&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",y&&(n.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",y&&(Ee.style.overflow="hidden"),pe.style.display="flex",pe.style.flexDirection="column",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.maxHeight="100%",pe.style.height="100%",pe.style.overflow="hidden",ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0"),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"),!p&&!y&&!l&&((_r=fr[be])!=null?_r:fr["bottom-right"]).split(" ").forEach(Ot=>Ee.classList.add(Ot)),p){let _t=(pr=(Ao=r.launcher)==null?void 0:Ao.sidebarWidth)!=null?pr:"420px";Ee.style.cssText=`
69
71
  position: fixed !important;
70
72
  top: 0 !important;
71
73
  bottom: 0 !important;
72
- width: ${Kt} !important;
74
+ width: ${_t} !important;
73
75
  height: 100vh !important;
74
76
  max-height: 100vh !important;
75
77
  margin: 0 !important;
76
78
  padding: 0 !important;
77
79
  display: flex !important;
78
80
  flex-direction: column !important;
79
- z-index: ${Ae} !important;
80
- ${Oe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
81
- `,he.style.cssText=`
81
+ z-index: ${Ce} !important;
82
+ ${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
+ `,pe.style.cssText=`
82
84
  position: relative !important;
83
85
  display: flex !important;
84
86
  flex-direction: column !important;
@@ -89,9 +91,9 @@ _Details: ${e.message}_`:r}var ra=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: ${He} !important;
94
+ box-shadow: ${Be} !important;
93
95
  border-radius: ${We} !important;
94
- `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),ue.style.cssText=`
96
+ `,pe.style.setProperty("width","100%","important"),pe.style.setProperty("max-width","100%","important"),ce.style.cssText=`
95
97
  display: flex !important;
96
98
  flex-direction: column !important;
97
99
  flex: 1 1 0% !important;
@@ -101,36 +103,36 @@ _Details: ${e.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
101
103
  max-height: 100% !important;
102
104
  overflow: hidden !important;
103
105
  border-radius: ${We} !important;
104
- border: ${ct} !important;
105
- `,_e.style.cssText=`
106
+ border: ${st} !important;
107
+ `,He.style.cssText=`
106
108
  flex-shrink: 0 !important;
107
109
  border-top: none !important;
108
110
  padding: 8px 16px 12px 16px !important;
109
- `}if(!b&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",Vt=p?"":"padding-top: 1.25em !important;",yt=p?"":`z-index: ${(fn=(Ze=r.launcher)==null?void 0:Ze.zIndex)!=null?fn:In} !important;`;Me.style.cssText+=Kt+Vt+yt}Qe()};ye(),vs(n,r),Li(n,r),Ii(n,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",ro)});let rn=null,un=null;gt.push(()=>{rn==null||rn(),rn=null,un==null||un(),un=null}),Vn&&gt.push(()=>{Vn==null||Vn.disconnect(),Vn=null}),gt.push(()=>{Bn==null||Bn(),Bn=null,Or(),$t&&($t.remove(),$t=null),Tt==null||Tt.element.style.removeProperty("width"),Tt==null||Tt.element.style.removeProperty("maxWidth")}),Ne&&gt.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),K==null||K.destroy(),K=null,fe==null||fe.destroy(),fe=null,X=null});let Er=null,Es=()=>{Er&&(Er(),Er=null),r.colorScheme==="auto"&&(Er=em(()=>{vs(n,r)}))};Es(),gt.push(()=>{Er&&(Er(),Er=null)});let $r=(Hc=r.features)==null?void 0:Hc.streamAnimation;if($r!=null&&$r.type&&$r.type!=="none"){let l=ia($r.type,$r.plugins);l&&(il(l,n),gt.push(()=>mm(n)))}let Eo=Lm(Gt),Mr=null,O,Go=l=>{var b,T;if(!O)return;let p=l!=null?l:O.getMessages(),h=((T=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:T.enabled)!==!1?yu(p):null;h?Eo.render(h,O,Pe,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(D=>D.role==="user")?Eo.render([],O,Pe,p):Eo.render(r.suggestionChips,O,Pe,p,r.suggestionChipsConfig)},kr=!1,Lr=om(),qr=new Map,Ir=new Map,mr=new Map,Qo=0,xa=ls()!==null,Jn=di(),Yn=0,gr=null,fr=!1,Mo=!1,Ur=0,Tn=null,Pr=null,Xo=!1,ko=!1,Jo=null,wa=4,Yo=24,Ca=80,Zo=new Map,vt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ms=(Nc=(Dc=r.voiceRecognition)==null?void 0:Dc.autoResume)!=null?Nc:!1,ir=l=>{s.emit("voice:state",{active:vt.active,source:l,timestamp:Date.now()})},qn=()=>{m(l=>({...l,voiceState:{active:vt.active,timestamp:Date.now(),manuallyDeactivated:vt.manuallyDeactivated}}))},Aa=()=>{var b,T;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=kl(d.voiceState),p=!!l.active,h=Number((T=l.timestamp)!=null?T:0);vt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<ub&&setTimeout(()=>{var D,U;vt.active||(vt.manuallyDeactivated=!1,((U=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:U.type)==="runtype"?O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("restore"),O.isVoiceActive()&&rs()}):Ha("restore"))},1e3)},Sa=()=>O?Ym(O.getMessages()).filter(l=>!l.__skipPersist):[];function es(l){if(!(i!=null&&i.save))return;let h={messages:l?Ym(l):O?Sa():[],metadata:d,artifacts:Kn.artifacts,selectedArtifactId:Kn.selectedId};try{let b=i.save(h);b instanceof Promise&&b.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let zr=null,ks=()=>Me.querySelector("#persona-scroll-container")||Le,ao=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),fr=!1},Ls=()=>{gr!==null&&(cancelAnimationFrame(gr),gr=null),Mo=!1,ao()},Is=()=>{Ur>0?(Wn.textContent=String(Ur),Wn.style.display="",mt.setAttribute("aria-label",`${an()||"Jump to latest"} (${Ur} new)`)):(Wn.textContent="",Wn.style.display="none",mt.setAttribute("aria-label",an()||"Jump to latest"))},Ps=()=>{Ur!==0&&(Ur=0,Is())},Ws=()=>et()==="follow"?!Jn.isFollowing():!Uo(Le,Yo),Un=()=>{if(!Ot()||ae){mt.parentNode&&mt.remove(),mt.style.display="none";return}mt.parentNode!==ue&&ue.appendChild(mt),On();let p=Jr(Le)>0&&Ws();p||Ps(),mt.style.display=p?"":"none"},ts=()=>{Jn.pause()&&(Ls(),Un())},Wr=()=>{Jn.resume(),Ps(),Un()},Rr=(l=!1)=>{et()==="follow"&&Jn.isFollowing()&&(!l&&!kr||(gr!==null&&(cancelAnimationFrame(gr),gr=null),Mo=!0,gr=requestAnimationFrame(()=>{gr=null,Mo=!1,Jn.isFollowing()&&Ta(ks(),l?220:140)})))},Rs=(l,p,h,b=()=>!0)=>{let T=l.scrollTop,D=p(),U=D-T;ao();let _=performance.now();fr=!0;let H=ce=>1-Math.pow(1-ce,3),le=ce=>{if(!b()){ao();return}let Y=p();Y!==D&&(D=Y,U=D-T);let xe=ce-_,Oe=Math.min(xe/h,1),Ae=H(Oe),tt=T+U*Ae;l.scrollTop=tt,Yn=l.scrollTop,Oe<1?zr=requestAnimationFrame(le):(l.scrollTop=D,Yn=l.scrollTop,zr=null,fr=!1)};zr=requestAnimationFrame(le)},Ta=(l,p=500)=>{let h=Jr(l)-l.scrollTop;if(Math.abs(h)<1){Yn=l.scrollTop;return}if(Math.abs(h)>=Ca){ao(),fr=!0,l.scrollTop=Jr(l),Yn=l.scrollTop,fr=!1;return}Rs(l,()=>Jr(l),p,()=>Jn.isFollowing())},Bs=()=>{let l=ks();fr=!0,l.scrollTop=Jr(l),Yn=l.scrollTop,fr=!1,Un()},Hs=l=>{ln.style.height=`${Math.max(0,Math.round(l))}px`,Tn&&(Tn.spacerHeight=Math.max(0,l))},Lo=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),ao(),Tn=null,ln.style.height="0px"},Ea=l=>{Pr!==null&&cancelAnimationFrame(Pr),Pr=requestAnimationFrame(()=>{var le;Pr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Le.querySelector(`[data-message-id="${p}"]`);if(!h)return;let b=0,T=h;for(;T&&T!==Le;)b+=T.offsetTop,T=T.offsetParent;let D=(le=Tn==null?void 0:Tn.spacerHeight)!=null?le:0,U=Le.scrollHeight-D,{targetScrollTop:_,spacerHeight:H}=cm({anchorOffsetTop:b,topOffset:_t(),viewportHeight:Le.clientHeight,contentHeight:U});Tn={initialSpacerHeight:H,contentHeightAtAnchor:U,spacerHeight:H},Hs(H),Rs(Le,()=>_,220)})},Ma=()=>{if(et()==="follow"){if(!Jn.isFollowing()||Uo(Le,1))return;Rr(!kr);return}if(Tn&&Tn.initialSpacerHeight>0){let l=Le.scrollHeight-Tn.spacerHeight,p=dm({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:l});p!==Tn.spacerHeight&&Hs(p)}Un()},ka=l=>{let p=et();p==="follow"?(Wr(),Rr(!0)):p==="anchor-top"&&Ea(l)},La=l=>{let p=new Map;l.forEach(h=>{let b=Zo.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(s.emit("assistant:message",h),!ko&&et()!=="anchor-top"&&Ws()&&(Ur+=1,Is(),Un())),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Zo.clear(),p.forEach((h,b)=>{Zo.set(b,h)})},Ia=(l,p,h)=>{var ct,He,We,je,Qe,wt;let b=document.createElement("div"),D=(()=>{var Fe;let W=o.find(De=>De.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Fe=r.loadingIndicator)!=null&&Fe.render)return r.loadingIndicator.render})(),U=(W,Fe)=>Fe==null?!1:typeof Fe=="string"?(W.textContent=Fe,!0):(W.appendChild(Fe),!0),_=new Set,H=new Set,le=o.some(W=>W.renderAskUserQuestion),ce=[],Y=[],xe=r.enableComponentStreaming!==!1,Oe=o.some(W=>W.renderApproval)&&r.approval!==!1,Ae=[];if(p.forEach(W=>{var Je,Rt,pn,cr,er,Io,Po,ss,as,Yt,Wo,go,fo,Kr,Ro,hr;_.add(W.id);let Fe=le&&Fo(W),De=Oe&&W.variant==="approval"&&!!W.approval,ge=!Fe&&W.role==="assistant"&&!W.variant&&xe&&Gm(W);if(!De&&mr.has(W.id)){let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),mr.delete(W.id)}if(!ge&&Ir.has(W.id)){let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime"),Ir.delete(W.id)}let jt=Fo(W)?`:${(Je=W.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Rt=W.agentMetadata)!=null&&Rt.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ut=rm(W,Qo)+jt,Jt=Fe||De||ge?null:sm(Lr,W.id,Ut);if(Jt){b.appendChild(Jt.cloneNode(!0)),Fo(W)&&((pn=W.toolCall)!=null&&pn.id)&&((cr=W.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((er=W.agentMetadata)!=null&&er.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}let At=null,Qt=o.find(Ze=>!!(W.variant==="reasoning"&&Ze.renderReasoning||W.variant==="tool"&&Ze.renderToolCall||!W.variant&&Ze.renderMessage)),Zn=(Io=r.layout)==null?void 0:Io.messages;if(Fo(W)&&((Po=W.agentMetadata)==null?void 0:Po.askUserQuestionAnswered)===!0){qr.delete(W.id);let Ze=l.querySelector(`#wrapper-${W.id}`);Ze==null||Ze.removeAttribute("data-preserve-runtime");return}if(Qi(W)&&((as=(ss=r.features)==null?void 0:ss.suggestReplies)==null?void 0:as.enabled)!==!1)return;if(Fo(W)&&((Wo=(Yt=r.features)==null?void 0:Yt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let Ze=o.find(fn=>typeof fn.renderAskUserQuestion=="function");if(Ze&&kt.current){let fn=qr.get(W.id),Kt=fn!==Ut,Vt=null;if(Kt){let{payload:Et,complete:Mn}=ds(W),Hn=W.id,Hr=()=>{var xn;return(xn=kt.current)==null?void 0:xn.getMessages().find(Dn=>Dn.id===Hn)};Vt=Ze.renderAskUserQuestion({message:W,payload:Et,complete:Mn,resolve:xn=>{var Nn;let Dn=Hr();Dn&&((Nn=kt.current)==null||Nn.resolveAskUserQuestion(Dn,xn))},dismiss:()=>{var Dn,Nn,Bo;let xn=Hr();(Dn=xn==null?void 0:xn.agentMetadata)!=null&&Dn.awaitingLocalTool&&((Nn=kt.current)==null||Nn.markAskUserQuestionResolved(xn),(Bo=kt.current)==null||Bo.resolveAskUserQuestion(xn,"(dismissed)"))},config:r})}let yt=fn!=null;if(Kt&&Vt===null&&!yt){((go=W.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=W.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${W.id}`,Zt.setAttribute("data-wrapper-id",W.id),Zt.setAttribute("data-ask-plugin-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),b.appendChild(Zt),ce.push({messageId:W.id,fingerprint:Ut,bubble:Vt});return}else{((Kr=W.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Ro=W.agentMetadata)!=null&&Ro.askUserQuestionAnswered)&&(H.add(W.toolCall.id),ja(W,r,J.composerOverlay));return}}else if(De){let Ze=o.find(yt=>typeof yt.renderApproval=="function"),Kt=mr.get(W.id)!==Ut,Vt=null;if(Kt&&(Ze!=null&&Ze.renderApproval)){let yt=W.id,Zt=(Et,Mn)=>{var Hr,xn,Dn;let Hn=(Hr=kt.current)==null?void 0:Hr.getMessages().find(Nn=>Nn.id===yt);Hn!=null&&Hn.approval&&(Hn.approval.toolType==="webmcp"?(xn=kt.current)==null||xn.resolveWebMcpApproval(Hn.id,Et):(Dn=kt.current)==null||Dn.resolveApproval(Hn.approval,Et,Mn))};Vt=Ze.renderApproval({message:W,defaultRenderer:()=>Mi(W,r),config:r,approve:Et=>Zt("approved",Et),deny:Et=>Zt("denied",Et)})}if(Kt&&Vt===null){let yt=l.querySelector(`#wrapper-${W.id}`);yt==null||yt.removeAttribute("data-preserve-runtime"),mr.delete(W.id),At=Mi(W,r)}else{let yt=document.createElement("div");yt.className="persona-flex",yt.id=`wrapper-${W.id}`,yt.setAttribute("data-wrapper-id",W.id),yt.setAttribute("data-approval-plugin-stub","true"),yt.setAttribute("data-preserve-runtime","true"),b.appendChild(yt),Ae.push({messageId:W.id,fingerprint:Ut,bubble:Vt});return}}else if(Qt)if(W.variant==="reasoning"&&W.reasoning&&Qt.renderReasoning){if(!Ve)return;At=Qt.renderReasoning({message:W,defaultRenderer:()=>hl(W,r),config:r})}else if(W.variant==="tool"&&W.toolCall&&Qt.renderToolCall){if(!ve)return;At=Qt.renderToolCall({message:W,defaultRenderer:()=>bl(W,r),config:r})}else Qt.renderMessage&&(At=Qt.renderMessage({message:W,defaultRenderer:()=>{let Ze=fl(W,h,Zn,r.messageActions,Z,{loadingIndicatorRenderer:D,widgetConfig:r});return W.role!=="user"&&wl(Ze,W,r,O),Ze},config:r}));if(!At&&ge){let Ze=Qm(W);if(Ze){let fn=Ir.get(W.id),Kt=fn!==Ut,Vt=r.wrapComponentDirectiveInBubble!==!1,yt=null;if(Kt){let Zt=Vm(Ze,{config:r,message:W,transform:h});if(Zt)if(Vt){let Et=document.createElement("div");if(Et.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(" "),Et.id=`bubble-${W.id}`,Et.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Mn=document.createElement("div");Mn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Mn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Et.appendChild(Mn)}Et.appendChild(Zt),yt=Et}else{let Et=document.createElement("div");if(Et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Et.id=`bubble-${W.id}`,Et.setAttribute("data-message-id",W.id),Et.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Mn=document.createElement("div");Mn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Mn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Et.appendChild(Mn)}Et.appendChild(Zt),yt=Et}}if(yt||fn!=null){let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${W.id}`,Zt.setAttribute("data-wrapper-id",W.id),Zt.setAttribute("data-component-directive-stub","true"),Zt.setAttribute("data-preserve-runtime","true"),Vt||Zt.classList.add("persona-w-full"),b.appendChild(Zt),Y.push({messageId:W.id,fingerprint:Ut,bubble:yt});return}}}if(!At)if(W.variant==="reasoning"&&W.reasoning){if(!Ve)return;At=hl(W,r)}else if(W.variant==="tool"&&W.toolCall){if(!ve)return;At=bl(W,r)}else if(W.variant==="approval"&&W.approval){if(r.approval===!1)return;At=Mi(W,r)}else{let Ze=(hr=r.layout)==null?void 0:hr.messages;Ze!=null&&Ze.renderUserMessage&&W.role==="user"?At=Ze.renderUserMessage({message:W,config:r,streaming:!!W.streaming}):Ze!=null&&Ze.renderAssistantMessage&&W.role==="assistant"?At=Ze.renderAssistantMessage({message:W,config:r,streaming:!!W.streaming}):At=fl(W,h,Ze,r.messageActions,Z,{loadingIndicatorRenderer:D,widgetConfig:r}),W.role!=="user"&&At&&wl(At,W,r,O)}let sn=document.createElement("div");sn.className="persona-flex",sn.id=`wrapper-${W.id}`,sn.setAttribute("data-wrapper-id",W.id),W.role==="user"&&sn.classList.add("persona-justify-end"),(At==null?void 0:At.getAttribute("data-persona-component-directive"))==="true"&&sn.classList.add("persona-w-full"),sn.appendChild(At),am(Lr,W.id,Ut,sn),b.appendChild(sn)}),J.composerOverlay&&J.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Fe=>{let De=Fe.getAttribute("data-persona-ask-sheet-for");De&&!H.has(De)&&us(J.composerOverlay,De)}),(He=(ct=r.features)==null?void 0:ct.toolCallDisplay)!=null&&He.grouped){let W=[],Fe=[];p.forEach(De=>{if(De.variant==="tool"&&De.toolCall&&ve){Fe.push(De);return}Fe.length>1&&W.push(Fe),Fe=[]}),Fe.length>1&&W.push(Fe),W.forEach((De,ge)=>{var Je,Rt;let jt=De.map(pn=>Array.from(b.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(jt.length<2)return;let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id=`wrapper-tool-group-${ge}-${De[0].id}`,Ut.setAttribute("data-wrapper-id",`tool-group-${ge}-${De[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let At=document.createElement("div");At.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Qt=`Called ${De.length} tools`,Zn=(Rt=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Rt.call(Je,{messages:De,toolCalls:De.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:Qt,config:r});U(At,Zn)||(At.textContent=Qt);let sn=document.createElement("div");sn.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(At,sn),Ut.appendChild(Jt),jt[0].before(Ut),jt.forEach((pn,cr)=>{let er=document.createElement("div");er.className="persona-tool-group-item persona-relative",er.setAttribute("data-persona-tool-group-item","true"),cr<jt.length-1&&er.setAttribute("data-persona-tool-group-connector","true"),er.appendChild(pn),sn.appendChild(er)})})}im(Lr,_);let tt=p.some(W=>W.role==="assistant"&&W.streaming),ze=p[p.length-1],bt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(kr&&p.some(W=>W.role==="user")&&!tt&&!bt){let W={config:r,streaming:!0,location:"standalone",defaultRenderer:ga},Fe=o.find(ge=>ge.renderLoadingIndicator),De=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(De=Fe.renderLoadingIndicator(W)),De===null&&((We=r.loadingIndicator)!=null&&We.render)&&(De=r.loadingIndicator.render(W)),De===null&&(De=ga()),De){let ge=document.createElement("div"),jt=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;ge.className=jt?["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 Ut=document.createElement("div");Ut.className="persona-flex",Ut.id="wrapper-typing-indicator",Ut.setAttribute("data-wrapper-id","typing-indicator"),Ut.appendChild(ge),b.appendChild(Ut)}}if(!kr&&p.length>0){let W=p[p.length-1],Fe={config:r,lastMessage:W,messageCount:p.length},De=o.find(jt=>jt.renderIdleIndicator),ge=null;if(De!=null&&De.renderIdleIndicator&&(ge=De.renderIdleIndicator(Fe)),ge===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Fe)),ge){let jt=document.createElement("div"),Ut=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;jt.className=Ut?["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(" "),jt.setAttribute("data-idle-indicator","true"),jt.appendChild(ge);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(jt),b.appendChild(Jt)}}if(li(l,b),ce.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of ce){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),qr.set(W,Fe))}if(qr.size>0)for(let W of qr.keys())_.has(W)||qr.delete(W);if(Y.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of Y){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),Ir.set(W,Fe))}if(Ir.size>0)for(let W of Ir.keys())_.has(W)||Ir.delete(W);if(Ae.length>0)for(let{messageId:W,fingerprint:Fe,bubble:De}of Ae){let ge=l.querySelector(`#wrapper-${W}`);ge&&De!==null&&(ge.replaceChildren(De),ge.setAttribute("data-bubble-fp",Fe),mr.set(W,Fe))}if(mr.size>0)for(let W of mr.keys())_.has(W)||mr.delete(W)},io=(l,p,h)=>{Ia(l,p,h),to()},lo=null,Pa=()=>{var h;if(lo)return;let l=b=>{let T=b.composedPath();T.includes(Me)||Ge&&T.includes(Ge)||be(!1,"user")};lo=l,((h=n.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},Ds=()=>{var p;if(!lo)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",lo,!0),lo=null};gt.push(()=>Ds());let co=null,Wa=()=>{var h;if(co)return;let l=b=>{b.key==="Escape"&&(b.isComposing||be(!1,"user"))};co=l,((h=n.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},Ns=()=>{var p;if(!co)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",co,!0),co=null};gt.push(()=>Ns());let po=!1,Fs=new Set,Ra=()=>{var p,h,b,T;let l=(b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},jr=()=>{var bt,ct,He,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=(bt=O==null?void 0:O.getMessages())!=null?bt:[],b;for(let je=h.length-1;je>=0;je--){let Qe=h[je];if(Qe.role==="assistant"&&Qe.content){b=Qe;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let T=b.content,D=!!b.streaming,U=Ra(),_=mi(U),H=_.type!=="none"?ia(_.type,U==null?void 0:U.plugins):null,le=((ct=H==null?void 0:H.isAnimating)==null?void 0:ct.call(H,b))===!0,ce=H!==null&&(D||le);ce&&H&&!Fs.has(H.name)&&(il(H,n),Fs.add(H.name));let Y=ce&&(H!=null&&H.containerClass)?H.containerClass:null,xe=(He=p.dataset.personaPeekStreamClass)!=null?He:null;xe&&xe!==Y&&(p.classList.remove(xe),delete p.dataset.personaPeekStreamClass),Y&&xe!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),ce?(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 Oe=ce?gi(T,_.buffer,H,b,D):T;if(ce&&_.placeholder==="skeleton"&&D&&(!Oe||!Oe.trim())){let je=document.createElement("div"),Qe=ca();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),li(p,je)}else{let je=Math.max(0,Oe.length-100),Qe=Oe.length>100?Oe.slice(-100):Oe,wt=ho(Qe);if(!ce||!H){let W=Oe.length>100?`\u2026${Qe}`:Qe;p.textContent!==W&&(p.textContent=W)}else{let W=wt;(H.wrap==="char"||H.wrap==="word")&&(W=la(wt,H.wrap,`peek-${b.id}`,{skipTags:H.skipTags,startIndex:je}));let Fe=document.createElement("div");if(Fe.innerHTML=W,H.useCaret&&Qe.length>0){let De=fi(),ge=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),jt=ge[ge.length-1];jt!=null&&jt.parentNode?jt.parentNode.insertBefore(De,jt.nextSibling):Fe.appendChild(De)}li(p,Fe),(We=H.onAfterRender)==null||We.call(H,{container:p,bubble:l,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let ze=kr||po;l.classList.toggle("persona-pill-peek--visible",ze)};if(N()){let l=J.peekBanner;if(l){let b=T=>{T.preventDefault(),T.stopPropagation(),be(!0,"user")};l.addEventListener("pointerdown",b),gt.push(()=>{l.removeEventListener("pointerdown",b)})}let p=()=>{po||(po=!0,jr())},h=()=>{po&&(po=!1,jr())};he.addEventListener("pointerenter",p),he.addEventListener("pointerleave",h),gt.push(()=>{he.removeEventListener("pointerenter",p),he.removeEventListener("pointerleave",h)}),Ge&&(Ge.addEventListener("pointerenter",p),Ge.addEventListener("pointerleave",h),gt.push(()=>{Ge.removeEventListener("pointerenter",p),Ge.removeEventListener("pointerleave",h)}))}let Ba=l=>{var xe,Oe,Ae,tt,ze,bt,ct,He;let p=(Oe=(xe=r.launcher)==null?void 0:xe.composerBar)!=null?Oe:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",b=(tt=p.bottomOffset)!=null?tt:"16px",T=p.collapsedMaxWidth,D=(ze=p.expandedMaxWidth)!=null?ze:"880px",U=(bt=p.expandedTopOffset)!=null?bt:"5vh",_=(ct=p.modalMaxWidth)!=null?ct:"880px",H=(He=p.modalMaxHeight)!=null?He:"min(90vh, 800px)",le="calc(100vw - 32px)",ce="var(--persona-pill-area-height, 80px)",Y=Me.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",Ge){let We=Ge.style;We.bottom=b,We.width=T!=null?T:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=le,Y.maxHeight=H,Y.height=H;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${b} + ${ce})`,Y.top=U,Y.width=D,Y.maxWidth=le}},Br=()=>{var H,le,ce,Y,xe,Oe,Ae,tt;if(!F())return;if(N()){let bt=(ce=((le=(H=r.launcher)==null?void 0:H.composerBar)!=null?le:{}).expandedSize)!=null?ce:"anchored",ct=k?"expanded":"collapsed";Me.dataset.state=ct,Me.dataset.expandedSize=bt,Ge&&(Ge.dataset.state=ct,Ge.dataset.expandedSize=bt),Me.style.removeProperty("display"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ba(k),ue.style.display=k?"flex":"none",ye(),k?(Pa(),Wa()):(Ds(),Ns()),jr();return}let l=An(r),p=(Y=n.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(xe=r.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Oe:640,b=(tt=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?tt:!0,T=p.innerWidth<=h,D=b&&T&&M,U=vr(r).reveal;k?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),on?on.element.style.display="none":gn&&(gn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!D?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),on?on.element.style.display=l?"none":"":gn&&(gn.style.display=l?"none":""))},be=(l,p="user")=>{var D,U;if(!F()||k===l)return;let h=k;k=l,Br();let b=(()=>{var Ae,tt,ze,bt,ct,He,We,je,Qe,wt;let _=(tt=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?tt:!1,H=(ze=n.ownerDocument.defaultView)!=null?ze:window,le=(ct=(bt=r.launcher)==null?void 0:bt.mobileFullscreen)!=null?ct:!0,ce=(We=(He=r.launcher)==null?void 0:He.mobileBreakpoint)!=null?We:640,Y=H.innerWidth<=ce,xe=An(r)&&le&&Y,Oe=N()&&((wt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return _||le&&Y&&M||xe||Oe})();if(k&&b){if(!rn){let _=n.getRootNode(),H=_ instanceof ShadowRoot?_.host:n.closest(".persona-host");H&&(rn=ll(H,(U=(D=r.launcher)==null?void 0:D.zIndex)!=null?U:In))}un||(un=cl(n.ownerDocument))}else k||(rn==null||rn(),rn=null,un==null||un(),un=null);k&&(_s(),et()==="follow"?Rr(!0):Bs());let T={open:k,source:p,timestamp:Date.now()};k&&!h?s.emit("widget:opened",T):!k&&h&&s.emit("widget:closed",T),s.emit("widget:state",{open:k,launcherEnabled:M,voiceActive:vt.active,streaming:O.isStreaming()})},w=l=>{Mt(l?"stop":"send"),V&&(V.disabled=l),Eo.buttons.forEach(p=>{p.disabled=l}),_e.dataset.personaComposerStreaming=l?"true":"false",_e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},$=()=>{vt.active||Pe&&Pe.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>$(),200)});let P=()=>{var h,b,T,D,U,_,H,le,ce,Y,xe;wr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",Sn.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",Pe.placeholder=(_=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?_:"How can I help...";let l=Le.querySelector("[data-persona-intro-card]");if(l){let Oe=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(Le.classList.remove("persona-gap-3"),Le.classList.add("persona-gap-6")):(Le.classList.remove("persona-gap-6"),Le.classList.add("persona-gap-3"))}!((ce=(le=r.sendButton)==null?void 0:le.useIcon)!=null&&ce)&&!(O!=null&&O.isStreaming())&&(Ue.textContent=(xe=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?xe:"Send"),Pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Pe.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=>{m(p=>({...p,sessionId:l}))}});let G=null,ie=()=>{G==null&&(G=setInterval(()=>{let l=Xe.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(G),G=null;return}let p=Date.now();l.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Ka(p-b))})},100))};O=new si(r,{onMessagesChanged(l){var b;io(Xe,l,Ie),ie(),Go(l),Rr(!kr),La(l);let p=[...l].reverse().find(T=>T.role==="user");l.length===0&&Lo(),!Xo||ko?(Xo=!0,Jo=(b=p==null?void 0:p.id)!=null?b:null):p&&p.id!==Jo&&(Jo=p.id,ka(p.id));let h=vt.lastUserMessageId;p&&p.id!==h&&(vt.lastUserMessageId=p.id,s.emit("user:message",p)),vt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),es(l),jr()},onStatusChanged(l){var b;let p=(b=r.statusIndicator)!=null?b:{};at(yn,(T=>{var D,U,_,H;return T==="idle"?(D=p.idleText)!=null?D:Ln.idle:T==="connecting"?(U=p.connectingText)!=null?U:Ln.connecting:T==="connected"?(_=p.connectedText)!=null?_:Ln.connected:T==="error"?(H=p.errorText)!=null?H:Ln.error:Ln[T]})(l),p,l)},onStreamingChanged(l){kr=l,w(l),O&&io(Xe,O.getMessages(),Ie),l||Rr(!0),jr()},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":Vr(),rs();break;case"processing":Vr(),gg();break;case"speaking":Vr(),fg();break;default:l==="idle"&&O.isBargeInActive()?(Vr(),rs(),V==null||V.setAttribute("aria-label","End voice session")):(vt.active=!1,Vr(),ir("system"),qn());break}},onArtifactsState(l){Kn=l,Xn(),es()}}),kt.current=O;let Q=null;if(O.onReadAloudChange((l,p)=>{var T;Zr=l,eo=p,to();let h=l!=null?l:Q;l&&(Q=l);let b=h&&(T=O.getMessages().find(D=>D.id===h))!=null?T:null;s.emit("message:read-aloud",{messageId:h,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(Q=null)}),Xo=!0,((_c=(Fc=r.voiceRecognition)==null?void 0:Fc.provider)==null?void 0:_c.type)==="runtype")try{O.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&O.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(fe||r.onSSEEvent)&&O.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),pe==null||pe.processEvent(l,p),fe==null||fe.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,b;if(l){if(l.metadata&&(d=kl(l.metadata),E.syncFromMetadata()),(p=l.messages)!=null&&p.length){ko=!0;try{O.hydrateMessages(l.messages)}finally{ko=!1}}(h=l.artifacts)!=null&&h.length&&O.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Re=()=>{var p,h,b;!N()||k||!((b=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||be(!0,"auto")},$e=l=>{var T;if(l.preventDefault(),O.isStreaming()){O.cancel(),pe==null||pe.reset(),K==null||K.update();return}let p=Pe.value.trim(),h=(T=Ct==null?void 0:Ct.hasAttachments())!=null?T:!1;if(!p&&!h)return;Re();let b;h&&(b=[],b.push(...Ct.getContentParts()),p&&b.push(Zi(p))),Pe.value="",Pe.style.height="auto",qt(),O.sendMessage(p,{contentParts:b}),h&&Ct.clearAttachments()},lt=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Ye={...ci},Pt=!1,qt=()=>{Ye={...ci}},vn=()=>O.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Wt=l=>{if(!Pe)return;Pt=!0,Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),Pt=!1;let p=Pe.value.length;Pe.setSelectionRange(p,p)},Ht=()=>{Pt||qt()},mn=l=>{if(Pe){if(lt()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=Pe.selectionStart===0&&Pe.selectionEnd===0,h=nm({direction:l.key==="ArrowUp"?"up":"down",history:vn(),currentValue:Pe.value,atStart:p,state:Ye});if(Ye=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Wt(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(O.isStreaming()){l.preventDefault();return}qt(),l.preventDefault(),Ue.click()}}},En=l=>{l.key!=="Escape"||l.isComposing||O.isStreaming()&&l.composedPath().includes(ue)&&(O.cancel(),pe==null||pe.reset(),K==null||K.update(),qt(),l.preventDefault(),l.stopImmediatePropagation())},Cn=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Ct)return;let p=gb(l.clipboardData);p.length!==0&&(l.preventDefault(),await Ct.handleFiles(p))},Dt=null,cn=!1,ns=null,ht=null,Hl=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ha=(l="user")=>{var D,U,_,H,le,ce,Y;if(cn||O.isStreaming())return;let p=Hl();if(!p)return;Dt=new p;let b=(U=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?U:2e3;Dt.continuous=!0,Dt.interimResults=!0,Dt.lang="en-US";let T=Pe.value;Dt.onresult=xe=>{let Oe="",Ae="";for(let ze=0;ze<xe.results.length;ze++){let bt=xe.results[ze],ct=bt[0].transcript;bt.isFinal?Oe+=ct+" ":Ae=ct}let tt=T+Oe+Ae;Pe.value=tt,ns&&clearTimeout(ns),(Oe||Ae)&&(ns=window.setTimeout(()=>{let ze=Pe.value.trim();ze&&Dt&&cn&&(uo(),Pe.value="",Pe.style.height="auto",O.sendMessage(ze,{viaVoice:!0}))},b))},Dt.onerror=xe=>{xe.error!=="no-speech"&&uo()},Dt.onend=()=>{if(cn){let xe=Pe.value.trim();xe&&xe!==T.trim()&&(Pe.value="",Pe.style.height="auto",O.sendMessage(xe,{viaVoice:!0})),uo()}};try{if(Dt.start(),cn=!0,vt.active=!0,l!=="system"&&(vt.manuallyDeactivated=!1),ir(l),qn(),V){let xe=(_=r.voiceRecognition)!=null?_:{};ht={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(H=xe.iconName)!=null?H:"mic",iconSize:parseFloat((Y=(ce=xe.iconSize)!=null?ce:(le=r.sendButton)==null?void 0:le.size)!=null?Y:"40")||24};let Oe=xe.recordingBackgroundColor,Ae=xe.recordingIconColor,tt=xe.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let ze=V.querySelector("svg");ze&&ze.setAttribute("stroke",Ae)}tt&&(V.style.borderColor=tt),V.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(cn){if(cn=!1,ns&&(clearTimeout(ns),ns=null),Dt){try{Dt.stop()}catch{}Dt=null}if(vt.active=!1,ir(l),qn(),V){if(V.classList.remove("persona-voice-recording"),ht){V.style.backgroundColor=ht.backgroundColor,V.style.color=ht.color,V.style.borderColor=ht.borderColor;let p=V.querySelector("svg");p&&p.setAttribute("stroke",ht.color||"currentColor"),ht=null}V.setAttribute("aria-label","Start voice recognition")}}},mg=(l,p)=>{var ct,He,We,je,Qe,wt,W,Fe,De;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((ct=l==null?void 0:l.provider)==null?void 0:ct.type)==="runtype",T=((He=l==null?void 0:l.provider)==null?void 0:He.type)==="custom";if(!(h||b||T))return null;let U=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 H=(We=l==null?void 0:l.iconName)!=null?We:"mic",le=(je=p==null?void 0:p.size)!=null?je:"40px",ce=(Qe=l==null?void 0:l.iconSize)!=null?Qe:le,Y=parseFloat(ce)||24,xe=(wt=l==null?void 0:l.backgroundColor)!=null?wt:p==null?void 0:p.backgroundColor,Oe=(W=l==null?void 0:l.iconColor)!=null?W:p==null?void 0:p.textColor;_.style.width=ce,_.style.height=ce,_.style.minWidth=ce,_.style.minHeight=ce,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let tt=Se(H,Y,Oe||"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F3A4}",xe?_.style.backgroundColor=xe:_.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),U.appendChild(_);let ze=(Fe=l==null?void 0:l.tooltipText)!=null?Fe:"Start voice recognition";if(((De=l==null?void 0:l.showTooltip)!=null?De:!1)&&ze){let ge=y("div","persona-send-button-tooltip");ge.textContent=ze,U.appendChild(ge)}return{micButton:_,micButtonWrapper:U}},Ri=()=>{var p,h,b,T,D;if(!V||ht)return;let l=(p=r.voiceRecognition)!=null?p:{};ht={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((D=(T=l.iconSize)!=null?T:(b=r.sendButton)==null?void 0:b.size)!=null?D:"40")||24}},Bi=(l,p)=>{var D,U,_,H,le;if(!V)return;let h=V.querySelector("svg");h&&h.remove();let b=(le=ht==null?void 0:ht.iconSize)!=null?le:parseFloat((H=(_=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?_:(U=r.sendButton)==null?void 0:U.size)!=null?H:"40")||24,T=Se(l,b,p,1.5);T&&V.appendChild(T)},Da=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rs=()=>{var T;if(!V)return;Ri();let l=(T=r.voiceRecognition)!=null?T:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,b=l.recordingBorderColor;if(Da(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",V.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=V.querySelector("svg");D&&D.setAttribute("stroke",h)}b&&(V.style.borderColor=b),V.setAttribute("aria-label","Stop voice recognition")},gg=()=>{var _,H,le,ce,Y,xe,Oe,Ae;if(!V)return;Ri();let l=(_=r.voiceRecognition)!=null?_:{},p=O.getVoiceInterruptionMode(),h=(H=l.processingIconName)!=null?H:"loader",b=(ce=(le=l.processingIconColor)!=null?le:ht==null?void 0:ht.color)!=null?ce:"",T=(xe=(Y=l.processingBackgroundColor)!=null?Y:ht==null?void 0:ht.backgroundColor)!=null?xe:"",D=(Ae=(Oe=l.processingBorderColor)!=null?Oe:ht==null?void 0:ht.borderColor)!=null?Ae:"";Da(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=T,V.style.borderColor=D;let U=b||"currentColor";V.style.color=U,Bi(h,U),V.setAttribute("aria-label","Processing voice input"),p==="none"&&(V.style.cursor="default")},fg=()=>{var le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We;if(!V)return;Ri();let l=(le=r.voiceRecognition)!=null?le:{},p=O.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(ce=l.speakingIconName)!=null?ce:h,T=(Ae=l.speakingIconColor)!=null?Ae:p==="barge-in"?(xe=(Y=l.recordingIconColor)!=null?Y:ht==null?void 0:ht.color)!=null?xe:"":(Oe=ht==null?void 0:ht.color)!=null?Oe:"",D=(bt=l.speakingBackgroundColor)!=null?bt:p==="barge-in"?(tt=l.recordingBackgroundColor)!=null?tt:"var(--persona-voice-recording-bg, #ef4444)":(ze=ht==null?void 0:ht.backgroundColor)!=null?ze:"",U=(We=l.speakingBorderColor)!=null?We:p==="barge-in"?(ct=l.recordingBorderColor)!=null?ct:"":(He=ht==null?void 0:ht.borderColor)!=null?He:"";Da(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=D,V.style.borderColor=U;let _=T||"currentColor";V.style.color=_,Bi(b,_);let H=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",H),p==="none"&&(V.style.cursor="default"),p==="barge-in"&&V.classList.add("persona-voice-recording")},Vr=()=>{var l,p,h;V&&(Da(),ht&&(V.style.backgroundColor=(l=ht.backgroundColor)!=null?l:"",V.style.color=(p=ht.color)!=null?p:"",V.style.borderColor=(h=ht.borderColor)!=null?h:"",Bi(ht.iconName,ht.color||"currentColor"),ht=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},Na=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=O.getVoiceStatus(),b=O.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,qn(),ir("user"),Vr()});return}O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),vt.manuallyDeactivated=!O.isVoiceActive(),qn(),ir("user"),O.isVoiceActive()?rs():Vr()});return}if(cn){let h=Pe.value.trim();vt.manuallyDeactivated=!0,qn(),uo("user"),h&&(Pe.value="",Pe.style.height="auto",O.sendMessage(h))}else vt.manuallyDeactivated=!1,qn(),Ha("user")};jn=Na,V&&(V.addEventListener("click",Na),gt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Vr()):uo("system"),V&&V.removeEventListener("click",Na)}));let hg=s.on("assistant:complete",()=>{Ms&&(vt.active||vt.manuallyDeactivated||Ms==="assistant"&&!vt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!vt.active&&!vt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("auto"),O.isVoiceActive()&&rs()}):Ha("auto"))},600))});gt.push(hg);let bg=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});gt.push(bg);let Dl=()=>{be(!k,"user")},on=null,gn=null;if(M&&!N()){let{instance:l,element:p}=ul({config:r,plugins:o,onToggle:Dl});on=l,l||(gn=p)}on?n.appendChild(on.element):gn&&n.appendChild(gn),Br(),Go(),P(),w(O.isStreaming()),et()==="follow"?Rr(!0):Bs(),Aa(),B&&(!M||N()?setTimeout(()=>$(),0):k&&setTimeout(()=>$(),200));let _s=()=>{var H,le,ce,Y,xe,Oe,Ae,tt,ze,bt,ct,He,We,je,Qe,wt,W,Fe,De,ge,jt,Ut;if(N()){On(),Br();return}let l=An(r),p=(le=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?le:!1,h=l||p||((Y=(ce=r.launcher)==null?void 0:ce.fullHeight)!=null?Y:!1),b=(xe=n.ownerDocument.defaultView)!=null?xe:window,T=(Ae=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ae:!0,D=(ze=(tt=r.launcher)==null?void 0:tt.mobileBreakpoint)!=null?ze:640,U=b.innerWidth<=D,_=T&&U&&M;try{if(_){ye(),vs(n,r);return}if(L&&(L=!1,ye(),vs(n,r)),!M&&!l){he.style.height="",he.style.width="";return}if(!p&&!l){let Jt=(ct=(bt=r==null?void 0:r.launcher)==null?void 0:bt.width)!=null?ct:r==null?void 0:r.launcherWidth,At=Jt!=null?Jt:Xr;he.style.width=At,he.style.maxWidth=At}if(Tr(),!h){let Jt=b.innerHeight,At=64,Qt=(We=(He=r.launcher)==null?void 0:He.heightOffset)!=null?We:0,Zn=Math.max(200,Jt-At),sn=Math.min(640,Zn),Je=Math.max(200,sn-Qt);he.style.height=`${Je}px`}}finally{if(On(),Br(),k&&M){let At=((je=n.ownerDocument.defaultView)!=null?je:window).innerWidth<=((wt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?wt:640),Qt=(Fe=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?Fe:!1,Zn=(ge=(De=r.launcher)==null?void 0:De.mobileFullscreen)!=null?ge:!0,sn=An(r)&&Zn&&At,Je=Qt||Zn&&At&&M||sn;if(Je&&!un){let Rt=n.getRootNode(),pn=Rt instanceof ShadowRoot?Rt.host:n.closest(".persona-host");pn&&!rn&&(rn=ll(pn,(Ut=(jt=r.launcher)==null?void 0:jt.zIndex)!=null?Ut:In)),un=cl(n.ownerDocument)}else Je||(rn==null||rn(),rn=null,un==null||un(),un=null)}}};_s();let Nl=(Oc=n.ownerDocument.defaultView)!=null?Oc:window;if(Nl.addEventListener("resize",_s),gt.push(()=>Nl.removeEventListener("resize",_s)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{On()});l.observe(_e),gt.push(()=>l.disconnect())}Yn=Le.scrollTop;let Fl=Jr(Le),yg=()=>{let l=Le.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Le.ownerDocument.getSelection()},Hi=()=>lm(yg(),Le),_l=()=>{let l=Le.scrollTop,p=Jr(Le),h=p<Fl;if(Fl=p,et()!=="follow"){Yn=l,Un();return}let{action:b,nextLastScrollTop:T}=pi({following:Jn.isFollowing(),currentScrollTop:l,lastScrollTop:Yn,nearBottom:Uo(Le,Yo),userScrollThreshold:wa,isAutoScrolling:fr||Mo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Yn=T,b==="resume"){Hi()||Wr();return}b==="pause"&&ts()};if(Le.addEventListener("scroll",_l,{passive:!0}),gt.push(()=>Le.removeEventListener("scroll",_l)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ma()});l.observe(Xe),l.observe(Le),gt.push(()=>l.disconnect())}let Ol=()=>{et()==="follow"&&Jn.isFollowing()&&Hi()&&ts()},$l=Le.ownerDocument;$l.addEventListener("selectionchange",Ol),gt.push(()=>{$l.removeEventListener("selectionchange",Ol)});let ql=l=>{if(et()!=="follow")return;let p=ui({following:Jn.isFollowing(),deltaY:l.deltaY,nearBottom:Uo(Le,Yo),resumeWhenNearBottom:!0});p==="pause"?ts():p==="resume"&&!Hi()&&Wr()};Le.addEventListener("wheel",ql,{passive:!0}),gt.push(()=>Le.removeEventListener("wheel",ql)),mt.addEventListener("click",()=>{Lo(),Le.scrollTop=Le.scrollHeight,Yn=Le.scrollTop,Wr(),Rr(!0),Un()}),gt.push(()=>mt.remove()),gt.push(()=>{Ls(),Lo()});let Ul=()=>{Ke&&(Mr&&(Ke.removeEventListener("click",Mr),Mr=null),F()?(Ke.style.display="",Mr=()=>{be(!1,"user")},Ke.addEventListener("click",Mr)):Ke.style.display="none")};Ul(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{O.clearMessages(),Lr.clear(),Wr(),us(J.composerOverlay);try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}d={},E.syncFromMetadata(),fe==null||fe.clear(),pe==null||pe.reset(),K==null||K.update()})})(),Nt&&Nt.addEventListener("submit",$e),Pe==null||Pe.addEventListener("keydown",mn),Pe==null||Pe.addEventListener("input",Ht),Pe==null||Pe.addEventListener("paste",Cn);let zl=($c=n.ownerDocument)!=null?$c:document;zl.addEventListener("keydown",En,!0);let jl="persona-attachment-drop-active",Os=0,Di=()=>{Os=0,ue.classList.remove(jl)},os=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&Ct!==null},Vl=l=>{!Pi(l.dataTransfer)||!os()||(Os++,Os===1&&ue.classList.add(jl))},Kl=l=>{!Pi(l.dataTransfer)||!os()||(Os--,Os<=0&&Di())},Gl=l=>{!Pi(l.dataTransfer)||!os()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Ql=l=>{var h;if(!Pi(l.dataTransfer)||!os())return;l.preventDefault(),l.stopPropagation(),Di();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&Ct.handleFiles(p)},mo=!0;ue.addEventListener("dragenter",Vl,mo),ue.addEventListener("dragleave",Kl,mo),n.addEventListener("dragover",Gl,mo),n.addEventListener("drop",Ql,mo);let Fa=n.ownerDocument,Xl=l=>{os()&&l.preventDefault()},Jl=l=>{os()&&l.preventDefault()};Fa.addEventListener("dragover",Xl),Fa.addEventListener("drop",Jl),gt.push(()=>{Nt&&Nt.removeEventListener("submit",$e),Pe==null||Pe.removeEventListener("keydown",mn),Pe==null||Pe.removeEventListener("input",Ht),Pe==null||Pe.removeEventListener("paste",Cn),zl.removeEventListener("keydown",En,!0)}),gt.push(()=>{ue.removeEventListener("dragenter",Vl,mo),ue.removeEventListener("dragleave",Kl,mo),n.removeEventListener("dragover",Gl,mo),n.removeEventListener("drop",Ql,mo),Fa.removeEventListener("dragover",Xl),Fa.removeEventListener("drop",Jl),Di()}),gt.push(()=>{O.cancel()}),on?gt.push(()=>{on==null||on.destroy()}):gn&&gt.push(()=>{gn==null||gn.remove()});let dn={update(l){var Mn,Hn,Hr,xn,Dn,Nn,Bo,$s,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,vd,xd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Id,Pd,Wd,Rd,Bd,Hd,Dd,Nd,Fd,_d,Od,$d,qd,Ud,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,bp,yp,vp,xp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Ip,Pp,Wp,Rp,Bp,Hp,Dp,Np,Fp,_p,Op,$p,qp,Up,zp,jp,Vp;let p=r.toolCall,h=r.messageActions,b=(Mn=r.layout)==null?void 0:Mn.messages,T=r.colorScheme,D=r.loadingIndicator,U=r.iterationDisplay,_=(Hn=r.features)==null?void 0:Hn.showReasoning,H=(Hr=r.features)==null?void 0:Hr.showToolCalls,le=(xn=r.features)==null?void 0:xn.toolCallDisplay,ce=(Dn=r.features)==null?void 0:Dn.reasoningDisplay;r={...r,...l},ye(),vs(n,r),Li(n,r),Ii(n,r),Xn(),r.colorScheme!==T&&Es();let Y=Al.getForInstance(r.plugins);o.length=0,o.push(...Y),M=(Bo=(Nn=r.launcher)==null?void 0:Nn.enabled)!=null?Bo:!0,S=(Gc=($s=r.launcher)==null?void 0:$s.autoExpand)!=null?Gc:!1,Ve=(Xc=(Qc=r.features)==null?void 0:Qc.showReasoning)!=null?Xc:!0,ve=(Yc=(Jc=r.features)==null?void 0:Jc.showToolCalls)!=null?Yc:!0,qe=(ed=(Zc=r.features)==null?void 0:Zc.scrollToBottom)!=null?ed:{};let xe=et();Te=(nd=(td=r.features)==null?void 0:td.scrollBehavior)!=null?nd:{},xe!==et()&&(Lo(),Wr()),Cr(),Un();let Oe=Ne;if(Ne=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,Ne&&!Oe){if(fe||(X=new ha(oe),fe=new fa(se,X),pe=pe!=null?pe:new ba,X.open().then(()=>fe==null?void 0:fe.restore()).catch(()=>{}),O.setSSEEventCallback((te,Lt)=>{var Xt;(Xt=r.onSSEEvent)==null||Xt.call(r,te,Lt),pe==null||pe.processEvent(te,Lt),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Lt)})})),!xt&&Ce){let te=(ad=(sd=r.features)==null?void 0:sd.eventStream)==null?void 0:ad.classNames,Lt="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");xt=y("button",Lt),xt.style.width="28px",xt.style.height="28px",xt.style.color=_n.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Xt=Se("activity","18px","currentColor",1.5);Xt&&xt.appendChild(Xt);let dt=J.clearChatButtonWrapper,Bt=J.closeButtonWrapper,hn=dt||Bt;hn&&hn.parentNode===Ce?Ce.insertBefore(xt,hn):Ce.appendChild(xt),xt.addEventListener("click",()=>{ae?ur():Nr()})}}else!Ne&&Oe&&(ur(),xt&&(xt.remove(),xt=null),fe==null||fe.clear(),X==null||X.destroy(),fe=null,X=null,pe==null||pe.reset(),pe=null);if(((id=r.launcher)==null?void 0:id.enabled)===!1&&on&&(on.destroy(),on=null),((ld=r.launcher)==null?void 0:ld.enabled)===!1&&gn&&(gn.remove(),gn=null),((cd=r.launcher)==null?void 0:cd.enabled)!==!1&&!on&&!gn){let{instance:te,element:Lt}=ul({config:r,plugins:o,onToggle:Dl});on=te,te||(gn=Lt),n.appendChild(Lt)}on&&on.update(r),q&&((dd=r.launcher)==null?void 0:dd.title)!==void 0&&(q.textContent=r.launcher.title),ke&&((pd=r.launcher)==null?void 0:pd.subtitle)!==void 0&&(ke.textContent=r.launcher.subtitle);let Ae=(ud=r.layout)==null?void 0:ud.header;if((Ae==null?void 0:Ae.layout)!==A&&Ce){let te=Ae?yi(r,Ae,{showClose:F(),onClose:()=>be(!1,"user")}):zo({config:r,showClose:F(),onClose:()=>be(!1,"user")});nt.replaceHeader(te),Ce=nt.header.element,Ft=nt.header.iconHolder,q=nt.header.headerTitle,ke=nt.header.headerSubtitle,Ke=nt.header.closeButton,A=Ae==null?void 0:Ae.layout}else if(Ae&&(Ft&&(Ft.style.display=Ae.showIcon===!1?"none":""),q&&(q.style.display=Ae.showTitle===!1?"none":""),ke&&(ke.style.display=Ae.showSubtitle===!1?"none":""),Ke&&(Ke.style.display=Ae.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let te=Ae.showClearChat;if(te!==void 0){J.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Lt}=J;Lt&&!Lt.classList.contains("persona-absolute")&&(te?Lt.classList.remove("persona-ml-auto"):Lt.classList.add("persona-ml-auto"))}}let ze=((md=r.layout)==null?void 0:md.showHeader)!==!1;Ce&&(Ce.style.display=ze?"":"none");let bt=((gd=r.layout)==null?void 0:gd.showFooter)!==!1;_e&&(_e.style.display=bt?"":"none"),On(),Un(),M!==R?M?be(S,"auto"):(k=!0,Br()):S!==I&&be(S,"auto"),I=S,R=M,_s(),Ul();let We=JSON.stringify(l.toolCall)!==JSON.stringify(p),je=JSON.stringify(r.messageActions)!==JSON.stringify(h),Qe=JSON.stringify((fd=r.layout)==null?void 0:fd.messages)!==JSON.stringify(b),wt=((hd=r.loadingIndicator)==null?void 0:hd.render)!==(D==null?void 0:D.render)||((bd=r.loadingIndicator)==null?void 0:bd.renderIdle)!==(D==null?void 0:D.renderIdle)||((yd=r.loadingIndicator)==null?void 0:yd.showBubble)!==(D==null?void 0:D.showBubble),W=r.iterationDisplay!==U,Fe=((xd=(vd=r.features)==null?void 0:vd.showReasoning)!=null?xd:!0)!==(_!=null?_:!0)||((Cd=(wd=r.features)==null?void 0:wd.showToolCalls)!=null?Cd:!0)!==(H!=null?H:!0)||JSON.stringify((Ad=r.features)==null?void 0:Ad.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify((Sd=r.features)==null?void 0:Sd.reasoningDisplay)!==JSON.stringify(ce);(We||je||Qe||wt||W||Fe)&&O&&(Qo++,io(Xe,O.getMessages(),Ie));let ge=(Td=r.launcher)!=null?Td:{},jt=(Ed=ge.headerIconHidden)!=null?Ed:!1,Ut=(kd=(Md=r.layout)==null?void 0:Md.header)==null?void 0:kd.showIcon,Jt=jt||Ut===!1,At=ge.headerIconName,Qt=(Ld=ge.headerIconSize)!=null?Ld:"48px";if(Ft){let te=ue.querySelector(".persona-border-b-persona-divider"),Lt=te==null?void 0:te.querySelector(".persona-flex-col");if(Jt)Ft.style.display="none",te&&Lt&&!te.contains(Lt)&&te.insertBefore(Lt,te.firstChild);else{if(Ft.style.display="",Ft.style.height=Qt,Ft.style.width=Qt,te&&Lt&&(te.contains(Ft)?Ft.nextSibling!==Lt&&(Ft.remove(),te.insertBefore(Ft,Lt)):te.insertBefore(Ft,Lt)),At){let dt=parseFloat(Qt)||24,Bt=Se(At,dt*.6,"currentColor",1);Bt?Ft.replaceChildren(Bt):Ft.textContent=(Id=ge.agentIconText)!=null?Id:"\u{1F4AC}"}else if(ge.iconUrl){let dt=Ft.querySelector("img");if(dt)dt.src=ge.iconUrl,dt.style.height=Qt,dt.style.width=Qt;else{let Bt=document.createElement("img");Bt.src=ge.iconUrl,Bt.alt="",Bt.className="persona-rounded-xl persona-object-cover",Bt.style.height=Qt,Bt.style.width=Qt,Ft.replaceChildren(Bt)}}else{let dt=Ft.querySelector("svg"),Bt=Ft.querySelector("img");(dt||Bt)&&Ft.replaceChildren(),Ft.textContent=(Pd=ge.agentIconText)!=null?Pd:"\u{1F4AC}"}let Xt=Ft.querySelector("img");Xt&&(Xt.style.height=Qt,Xt.style.width=Qt)}}let Zn=(Rd=(Wd=r.layout)==null?void 0:Wd.header)==null?void 0:Rd.showTitle,sn=(Hd=(Bd=r.layout)==null?void 0:Bd.header)==null?void 0:Hd.showSubtitle;if(q&&(q.style.display=Zn===!1?"none":""),ke&&(ke.style.display=sn===!1?"none":""),Ke){((Nd=(Dd=r.layout)==null?void 0:Dd.header)==null?void 0:Nd.showCloseButton)===!1?Ke.style.display="none":Ke.style.display="";let Lt=(Fd=ge.closeButtonSize)!=null?Fd:"32px",Xt=(_d=ge.closeButtonPlacement)!=null?_d:"inline";Ke.style.height=Lt,Ke.style.width=Lt;let{closeButtonWrapper:dt}=J,Bt=Xt==="top-right",hn=dt==null?void 0:dt.classList.contains("persona-absolute");if(dt&&Bt!==hn)if(dt.remove(),Bt)dt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(dt);else{let ft=($d=(Od=ge.clearChat)==null?void 0:Od.placement)!=null?$d:"inline",bn=(Ud=(qd=ge.clearChat)==null?void 0:qd.enabled)!=null?Ud:!0;dt.className=bn&&ft==="inline"?"":"persona-ml-auto";let zn=ue.querySelector(".persona-border-b-persona-divider");zn&&zn.appendChild(dt)}if(Ke.style.color=ge.closeButtonColor||_n.actionIconColor,ge.closeButtonBackgroundColor?(Ke.style.backgroundColor=ge.closeButtonBackgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let ft=ge.closeButtonBorderWidth||"0px",bn=ge.closeButtonBorderColor||"transparent";Ke.style.border=`${ft} solid ${bn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ge.closeButtonBorderRadius?(Ke.style.borderRadius=ge.closeButtonBorderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(Ke.style.paddingLeft=ge.closeButtonPaddingX,Ke.style.paddingRight=ge.closeButtonPaddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ge.closeButtonPaddingY?(Ke.style.paddingTop=ge.closeButtonPaddingY,Ke.style.paddingBottom=ge.closeButtonPaddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let kn=(zd=ge.closeButtonIconName)!=null?zd:"x",br=(jd=ge.closeButtonIconText)!=null?jd:"\xD7";Ke.innerHTML="";let Fn=Se(kn,"28px","currentColor",1);Fn?Ke.appendChild(Fn):Ke.textContent=br;let nn=(Vd=ge.closeButtonTooltipText)!=null?Vd:"Close chat",tr=(Kd=ge.closeButtonShowTooltip)!=null?Kd:!0;if(Ke.setAttribute("aria-label",nn),dt&&(dt._cleanupTooltip&&(dt._cleanupTooltip(),delete dt._cleanupTooltip),tr&&nn)){let ft=null,bn=()=>{if(ft||!Ke)return;let Ho=Ke.ownerDocument,qs=Ho.body;if(!qs)return;ft=Dr(Ho,"div","persona-clear-chat-tooltip"),ft.textContent=nn;let Us=Dr(Ho,"div");Us.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Us);let Do=Ke.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(xo),ft.style.left=`${Do.left+Do.width/2}px`,ft.style.top=`${Do.top-8}px`,ft.style.transform="translate(-50%, -100%)",qs.appendChild(ft)},zn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};dt.addEventListener("mouseenter",bn),dt.addEventListener("mouseleave",zn),Ke.addEventListener("focus",bn),Ke.addEventListener("blur",zn),dt._cleanupTooltip=()=>{zn(),dt&&(dt.removeEventListener("mouseenter",bn),dt.removeEventListener("mouseleave",zn)),Ke&&(Ke.removeEventListener("focus",bn),Ke.removeEventListener("blur",zn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Rt}=J;if(Je){let te=(Gd=ge.clearChat)!=null?Gd:{},Lt=(Qd=te.enabled)!=null?Qd:!0,Xt=(Jd=(Xd=r.layout)==null?void 0:Xd.header)==null?void 0:Jd.showClearChat,dt=Xt!==void 0?Xt:Lt,Bt=(Yd=te.placement)!=null?Yd:"inline";if(Rt){Rt.style.display=dt?"":"none";let{closeButtonWrapper:hn}=J;!N()&&hn&&!hn.classList.contains("persona-absolute")&&(dt?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let kn=Bt==="top-right",br=Rt.classList.contains("persona-absolute");if(!N()&&kn!==br&&dt){if(Rt.remove(),kn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",ue.style.position="relative",ue.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let nn=ue.querySelector(".persona-border-b-persona-divider"),tr=J.closeButtonWrapper;nn&&tr&&tr.parentElement===nn?nn.insertBefore(Rt,tr):nn&&nn.appendChild(Rt)}let Fn=J.closeButtonWrapper;Fn&&!Fn.classList.contains("persona-absolute")&&(kn?Fn.classList.add("persona-ml-auto"):Fn.classList.remove("persona-ml-auto"))}}if(dt){if(!N()){let ft=(Zd=te.size)!=null?Zd:"32px";Je.style.height=ft,Je.style.width=ft}let hn=(ep=te.iconName)!=null?ep:"refresh-cw",kn=(tp=te.iconColor)!=null?tp:"";Je.style.color=kn||_n.actionIconColor,Je.innerHTML="";let br=N()?"14px":"20px",Fn=Se(hn,br,"currentColor",2);if(Fn&&Je.appendChild(Fn),te.backgroundColor?(Je.style.backgroundColor=te.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ft=te.borderWidth||"0px",bn=te.borderColor||"transparent";Je.style.border=`${ft} solid ${bn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");te.borderRadius?(Je.style.borderRadius=te.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),te.paddingX?(Je.style.paddingLeft=te.paddingX,Je.style.paddingRight=te.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),te.paddingY?(Je.style.paddingTop=te.paddingY,Je.style.paddingBottom=te.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let nn=(np=te.tooltipText)!=null?np:"Clear chat",tr=(rp=te.showTooltip)!=null?rp:!0;if(Je.setAttribute("aria-label",nn),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),tr&&nn)){let ft=null,bn=()=>{if(ft||!Je)return;let Ho=Je.ownerDocument,qs=Ho.body;if(!qs)return;ft=Dr(Ho,"div","persona-clear-chat-tooltip"),ft.textContent=nn;let Us=Dr(Ho,"div");Us.className="persona-clear-chat-tooltip-arrow",ft.appendChild(Us);let Do=Je.getBoundingClientRect();ft.style.position="fixed",ft.style.zIndex=String(xo),ft.style.left=`${Do.left+Do.width/2}px`,ft.style.top=`${Do.top-8}px`,ft.style.transform="translate(-50%, -100%)",qs.appendChild(ft)},zn=()=>{ft&&ft.parentNode&&(ft.parentNode.removeChild(ft),ft=null)};Rt.addEventListener("mouseenter",bn),Rt.addEventListener("mouseleave",zn),Je.addEventListener("focus",bn),Je.addEventListener("blur",zn),Rt._cleanupTooltip=()=>{zn(),Rt&&(Rt.removeEventListener("mouseenter",bn),Rt.removeEventListener("mouseleave",zn)),Je&&(Je.removeEventListener("focus",bn),Je.removeEventListener("blur",zn))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Tl],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick];E=El({parsers:pn,handlers:cr,getSessionMetadata:u,updateSessionMetadata:m,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),Ie=Zm(r,E,re),O.updateConfig(r),io(Xe,O.getMessages(),Ie),Go(),P(),w(O.isStreaming());let er=((op=r.voiceRecognition)==null?void 0:op.enabled)===!0,Io=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Po=((ap=(sp=r.voiceRecognition)==null?void 0:sp.provider)==null?void 0:ap.type)==="runtype";if(er&&(Io||Po))if(!V||!St){let te=mg(r.voiceRecognition,r.sendButton);te&&(V=te.micButton,St=te.micButtonWrapper,ot.insertBefore(St,rt),V.addEventListener("click",Na),V.disabled=O.isStreaming())}else{let te=(ip=r.voiceRecognition)!=null?ip:{},Lt=(lp=r.sendButton)!=null?lp:{},Xt=(cp=te.iconName)!=null?cp:"mic",dt=(dp=Lt.size)!=null?dp:"40px",Bt=(pp=te.iconSize)!=null?pp:dt,hn=parseFloat(Bt)||24;V.style.width=Bt,V.style.height=Bt,V.style.minWidth=Bt,V.style.minHeight=Bt;let kn=(mp=(up=te.iconColor)!=null?up:Lt.textColor)!=null?mp:"currentColor";V.innerHTML="";let br=Se(Xt,hn,kn,2);br?V.appendChild(br):V.textContent="\u{1F3A4}";let Fn=(gp=te.backgroundColor)!=null?gp:Lt.backgroundColor;Fn?V.style.backgroundColor=Fn:V.style.backgroundColor="",kn?V.style.color=kn:V.style.color="var(--persona-text, #111827)",te.borderWidth?(V.style.borderWidth=te.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),te.borderColor?V.style.borderColor=te.borderColor:V.style.borderColor="",te.paddingX?(V.style.paddingLeft=te.paddingX,V.style.paddingRight=te.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),te.paddingY?(V.style.paddingTop=te.paddingY,V.style.paddingBottom=te.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let nn=St==null?void 0:St.querySelector(".persona-send-button-tooltip"),tr=(fp=te.tooltipText)!=null?fp:"Start voice recognition";if(((hp=te.showTooltip)!=null?hp:!1)&&tr)if(nn)nn.textContent=tr,nn.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=tr,St==null||St.insertBefore(bn,V)}else nn&&(nn.style.display="none");St.style.display="",V.disabled=O.isStreaming()}else V&&St&&(St.style.display="none",((yp=(bp=r.voiceRecognition)==null?void 0:bp.provider)==null?void 0:yp.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():cn&&uo());if(((vp=r.attachments)==null?void 0:vp.enabled)===!0)if(!me||!de){let te=(xp=r.attachments)!=null?xp:{},Xt=(Cp=((wp=r.sendButton)!=null?wp:{}).size)!=null?Cp:"40px";ut||(ut=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ut.style.display="none",Nt.insertBefore(ut,Pe)),Ee||(Ee=document.createElement("input"),Ee.type="file",Ee.accept=((Ap=te.allowedTypes)!=null?Ap:Qr).join(","),Ee.multiple=((Sp=te.maxFiles)!=null?Sp:4)>1,Ee.style.display="none",Ee.setAttribute("aria-label","Attach files"),Nt.insertBefore(Ee,Pe)),me=y("div","persona-send-button-wrapper"),de=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),de.type="button",de.setAttribute("aria-label",(Tp=te.buttonTooltipText)!=null?Tp:"Attach file");let dt=(Ep=te.buttonIconName)!=null?Ep:"paperclip",Bt=Xt,hn=parseFloat(Bt)||40,kn=Math.round(hn*.6);de.style.width=Bt,de.style.height=Bt,de.style.minWidth=Bt,de.style.minHeight=Bt,de.style.fontSize="18px",de.style.lineHeight="1",de.style.backgroundColor="transparent",de.style.color="var(--persona-primary, #111827)",de.style.border="none",de.style.borderRadius="6px",de.style.transition="background-color 0.15s ease",de.addEventListener("mouseenter",()=>{de.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),de.addEventListener("mouseleave",()=>{de.style.backgroundColor="transparent"});let br=Se(dt,kn,"currentColor",1.5);br?de.appendChild(br):de.textContent="\u{1F4CE}",de.addEventListener("click",tr=>{tr.preventDefault(),Ee==null||Ee.click()}),me.appendChild(de);let Fn=(Mp=te.buttonTooltipText)!=null?Mp:"Attach file",nn=y("div","persona-send-button-tooltip");nn.textContent=Fn,me.appendChild(nn),pt.append(me),!Ct&&Ee&&ut&&(Ct=oa.fromConfig(te),Ct.setPreviewsContainer(ut),Ee.addEventListener("change",async()=>{Ct&&(Ee!=null&&Ee.files)&&(await Ct.handleFileSelect(Ee.files),Ee.value="")})),ue.querySelector(".persona-attachment-drop-overlay")||ue.appendChild(eg(te.dropOverlay))}else{me.style.display="";let te=(kp=r.attachments)!=null?kp:{};Ee&&(Ee.accept=((Lp=te.allowedTypes)!=null?Lp:Qr).join(","),Ee.multiple=((Ip=te.maxFiles)!=null?Ip:4)>1),Ct&&Ct.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else me&&(me.style.display="none"),Ct&&Ct.clearAttachments(),(Pp=ue.querySelector(".persona-attachment-drop-overlay"))==null||Pp.remove();let Yt=(Wp=r.sendButton)!=null?Wp:{},Wo=(Rp=Yt.useIcon)!=null?Rp:!1,go=(Bp=Yt.iconText)!=null?Bp:"\u2191",fo=Yt.iconName,Kr=(Hp=Yt.tooltipText)!=null?Hp:"Send message",Ro=(Dp=Yt.showTooltip)!=null?Dp:!1,hr=(Np=Yt.size)!=null?Np:"40px",Ze=Yt.backgroundColor,fn=Yt.textColor;if(Wo){if(Ue.style.width=hr,Ue.style.height=hr,Ue.style.minWidth=hr,Ue.style.minHeight=hr,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",fn?Ue.style.color=fn:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let te=parseFloat(hr)||24,Lt=(fn==null?void 0:fn.trim())||"currentColor",Xt=Se(fo,te,Lt,2);Xt?Ue.appendChild(Xt):Ue.textContent=go}else Ue.textContent=go;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ze?(Ue.style.backgroundColor=Ze,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(_p=(Fp=r.copy)==null?void 0:Fp.sendButtonLabel)!=null?_p:"Send",Ue.style.width="",Ue.style.height="",Ue.style.minWidth="",Ue.style.minHeight="",Ue.style.fontSize="",Ue.style.lineHeight="",Ue.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",Ze?(Ue.style.backgroundColor=Ze,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),fn?Ue.style.color=fn:Ue.classList.add("persona-text-white");Yt.borderWidth?(Ue.style.borderWidth=Yt.borderWidth,Ue.style.borderStyle="solid"):(Ue.style.borderWidth="",Ue.style.borderStyle=""),Yt.borderColor?Ue.style.borderColor=Yt.borderColor:Ue.style.borderColor="",Yt.paddingX?(Ue.style.paddingLeft=Yt.paddingX,Ue.style.paddingRight=Yt.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Yt.paddingY?(Ue.style.paddingTop=Yt.paddingY,Ue.style.paddingBottom=Yt.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Kt=rt==null?void 0:rt.querySelector(".persona-send-button-tooltip");if(Ro&&Kr)if(Kt)Kt.textContent=Kr,Kt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Kr,rt==null||rt.insertBefore(te,Ue)}else Kt&&(Kt.style.display="none");let Vt=(zp=(Op=r.layout)==null?void 0:Op.contentMaxWidth)!=null?zp:N()?(Up=(qp=($p=r.launcher)==null?void 0:$p.composerBar)==null?void 0:qp.contentMaxWidth)!=null?Up:"720px":void 0;Vt?(Xe.style.maxWidth=Vt,Xe.style.marginLeft="auto",Xe.style.marginRight="auto",Xe.style.width="100%",Nt&&(Nt.style.maxWidth=Vt,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),Gt&&(Gt.style.maxWidth=Vt,Gt.style.marginLeft="auto",Gt.style.marginRight="auto")):(Xe.style.maxWidth="",Xe.style.marginLeft="",Xe.style.marginRight="",Xe.style.width="",Nt&&(Nt.style.maxWidth="",Nt.style.marginLeft="",Nt.style.marginRight=""),Gt&&(Gt.style.maxWidth="",Gt.style.marginLeft="",Gt.style.marginRight=""));let yt=(jp=r.statusIndicator)!=null?jp:{},Zt=(Vp=yt.visible)!=null?Vp:!0;if(yn.style.display=Zt?"":"none",O){let te=O.getStatus();at(yn,(Xt=>{var dt,Bt,hn,kn;return Xt==="idle"?(dt=yt.idleText)!=null?dt:Ln.idle:Xt==="connecting"?(Bt=yt.connectingText)!=null?Bt:Ln.connecting:Xt==="connected"?(hn=yt.connectedText)!=null?hn:Ln.connected:Xt==="error"?(kn=yt.errorText)!=null?kn:Ln.error:Ln[Xt]})(te),yt,te)}yn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=yt.align==="left"?"persona-text-left":yt.align==="center"?"persona-text-center":"persona-text-right";yn.classList.add(Et)},open(){F()&&be(!0,"api")},close(){F()&&be(!1,"api")},toggle(){F()&&be(!k,"api")},clearChat(){Rn=!1,O.clearMessages(),Lr.clear(),Wr();try{localStorage.removeItem(Ss),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ss}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ss)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={},E.syncFromMetadata(),fe==null||fe.clear(),pe==null||pe.reset(),K==null||K.update()},setMessage(l){return!Pe||O.isStreaming()?!1:(!k&&F()&&be(!0,"system"),Pe.value=l,Pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let p=(l==null?void 0:l.trim())||Pe.value.trim();return p?(!k&&F()&&be(!0,"system"),Pe.value="",Pe.style.height="auto",O.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return O.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(O.isVoiceActive()||(!k&&F()&&be(!0,"system"),vt.manuallyDeactivated=!1,qn(),O.toggleVoice().then(()=>{vt.active=O.isVoiceActive(),ir("user"),O.isVoiceActive()&&rs()})),!0):cn?!0:Hl()?(!k&&F()&&be(!0,"system"),vt.manuallyDeactivated=!1,qn(),Ha("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{vt.active=!1,vt.manuallyDeactivated=!0,qn(),ir("user"),Vr()}),!0):!1:cn?(vt.manuallyDeactivated=!0,qn(),uo("user"),!0):!1},injectMessage(l){return!k&&F()&&be(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!k&&F()&&be(!0,"system");let p=O.injectAssistantMessage(l);return z&&(z=!1,j&&(clearTimeout(j),j=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),p},injectUserMessage(l){return!k&&F()&&be(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!k&&F()&&be(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!k&&F()&&be(!0,"system"),O.injectMessageBatch(l)},injectComponentDirective(l){return!k&&F()&&be(!0,"system"),O.injectComponentDirective(l)},injectTestMessage(l){!k&&F()&&be(!0,"system"),O.injectTestEvent(l)},async connectStream(l,p){return O.connectStream(l,p)},__pushEventStreamEvent(l){fe&&(pe==null||pe.processEvent(l.type,l.payload),fe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Ne||!fe||Nr()},hideEventStream(){ae&&ur()},isEventStreamVisible(){return ae},showArtifacts(){pr(r)&&(Rn=!1,Xn(),Tt==null||Tt.setMobileOpen(!0))},hideArtifacts(){pr(r)&&(Rn=!0,Xn())},upsertArtifact(l){return pr(r)?(Rn=!1,O.upsertArtifact(l)):null},selectArtifact(l){pr(r)&&O.selectArtifact(l)},clearArtifacts(){pr(r)&&O.clearArtifacts()},getArtifacts(){var l;return(l=O==null?void 0:O.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=O==null?void 0:O.getSelectedArtifactId())!=null?l:null},focusInput(){return M&&!k&&!N()||!Pe?!1:(Pe.focus(),!0)},async resolveApproval(l,p,h){let T=O.getMessages().find(D=>{var U;return D.variant==="approval"&&((U=D.approval)==null?void 0:U.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){O.resolveWebMcpApproval(T.id,p);return}return O.resolveApproval(T.approval,p,h)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(l){m(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return F()&&k},isVoiceActive(){return vt.active},toggleReadAloud(l){O.toggleReadAloud(l)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(l){return O.getReadAloudState(l)},onReadAloudChange(l){return O.onReadAloudChange(l)},getState(){return{open:F()&&k,launcherEnabled:M,voiceActive:vt.active,streaming:O.isStreaming()}},showCSATFeedback(l){!k&&F()&&be(!0,"system");let p=Xe.querySelector(".persona-feedback-container");p&&p.remove();let h=Xm({onSubmit:async(b,T)=>{var D;O.isClientTokenMode()&&await O.submitCSATFeedback(b,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&F()&&be(!0,"system");let p=Xe.querySelector(".persona-feedback-container");p&&p.remove();let h=Jm({onSubmit:async(b,T)=>{var D;O.isClientTokenMode()&&await O.submitNPSFeedback(b,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,b,T)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return O.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return O.submitNPSFeedback(l,p)},destroy(){G!=null&&(clearInterval(G),G=null),gt.forEach(l=>l()),Me.remove(),Ge==null||Ge.remove(),on==null||on.destroy(),gn==null||gn.remove(),Mr&&Ke.removeEventListener("click",Mr)}};if((((qc=e==null?void 0:e.debugTools)!=null?qc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:h=>h?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=p,gt.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=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",p),gt.push(()=>{window.removeEventListener("persona:focusInput",p)}),Ne){let _=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===l)&&dn.showEventStream()},H=le=>{let ce=le.detail;(!(ce!=null&&ce.instanceId)||ce.instanceId===l)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",H),gt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",H)})}let h=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.showArtifacts()},b=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.hideArtifacts()},T=_=>{let H=_.detail;H!=null&&H.instanceId&&H.instanceId!==l||H!=null&&H.artifact&&dn.upsertArtifact(H.artifact)},D=_=>{let H=_.detail;H!=null&&H.instanceId&&H.instanceId!==l||typeof(H==null?void 0:H.id)=="string"&&dn.selectArtifact(H.id)},U=_=>{let H=_.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",U),gt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",U)})}let lr=fb(r.persistState);if(lr&&F()){let l=hb(lr.storage),p=`${lr.keyPrefix}widget-open`,h=`${lr.keyPrefix}widget-voice`,b=`${lr.keyPrefix}widget-voice-mode`;if(l){let T=((Uc=lr.persist)==null?void 0:Uc.openState)&&l.getItem(p)==="true",D=((zc=lr.persist)==null?void 0:zc.voiceState)&&l.getItem(h)==="true",U=((jc=lr.persist)==null?void 0:jc.voiceState)&&l.getItem(b)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var _;if(D||U)dn.startVoiceRecognition();else if((_=lr.persist)!=null&&_.focusInput){let H=n.querySelector("textarea");H&&H.focus()}},100)},0),(Vc=lr.persist)!=null&&Vc.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Kc=lr.persist)!=null&&Kc.voiceState&&(s.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),s.on("user:message",_=>{l.setItem(b,_.viaVoice?"true":"false")})),lr.clearOnChatClear){let _=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(b)},H=()=>_();window.addEventListener("persona:clear-chat",H),gt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return g&&F()&&setTimeout(()=>{dn.open()},0),jr(),xa||eu().then(()=>{O&&(Qo++,Lr.clear(),io(Xe,O.getMessages(),Ie))}).catch(()=>{}),dn};var bb=(n,t)=>{let e=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(e);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(e);return o?Math.max(0,t*parseFloat(o[1])/100):420},yb=(n,t)=>{if(t===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=t},vb=(n,t)=>{t===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},xb=(n,t)=>{let e=n.parentElement;if(!e)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",e.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."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ng=(n,t)=>{var r,o;let e=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=e?"":"100%",n.style.display=e?"":"flex",n.style.flexDirection=e?"":"column",n.style.flex=e?"":"1 1 auto",n.style.minHeight=e?"":"0"},Wl=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=""},rg=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Wl(n)},Ll=n=>{n.style.transition=""},Il=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=""},Pl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},Wi=(n,t)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",t.style.alignItems=""},wb=(n,t,e,r,o)=>{o?e.parentElement!==t&&(n.replaceChildren(),t.replaceChildren(e,r),n.appendChild(t)):e.parentElement===t&&(t.replaceChildren(),n.appendChild(e),n.appendChild(r))},Cb=(n,t,e,r,o,s)=>{let a=s?t:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,e):a.lastElementChild!==r&&a.replaceChildren(e,r)},og=(n,t,e,r,o,s,a)=>{var v,x,E,M,S,B;let i=vr(s),d=i.reveal==="push";wb(n,t,e,r,d),Cb(n,t,e,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",e.style.display="flex",e.style.flexDirection="column",e.style.minHeight="0",e.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,g=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,f=(M=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?M:640,u=c!=null?c.innerWidth<=f:!1;if(g&&u&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),Il(t),Ll(r),rg(r),Pl(e),Wi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",e.style.flex="1 1 auto",e.style.width="100%",e.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((B=(S=s==null?void 0:s.launcher)==null?void 0:S.zIndex)!=null?B:In),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",e.style.flex="1 1 auto",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),rg(r),yb(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",Il(t),Ll(r),Pl(e),Wi(o,r);let I=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=I,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",Ll(r),Wl(r),Wi(o,r);let I=bb(i.width,n.clientWidth),R=Math.max(0,n.clientWidth),A=i.animate?"margin-left 180ms ease":"none",L=i.side==="right"?a?-I:0:a?0:-I;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+I}px`,t.style.transition=A,t.style.marginLeft=`${L}px`,t.style.transform="",e.style.flex="0 0 auto",e.style.flexGrow="0",e.style.flexShrink="0",e.style.width=`${R}px`,e.style.maxWidth=`${R}px`,e.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="",Il(t),Wl(r),Pl(e),Wi(o,r);let I=i.reveal==="emerge";I?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",L=!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",vb(r,i.maxHeight),r.style.overflow=I||L?"hidden":"visible",r.style.transition=A,I&&(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")}},Ab=(n,t)=>{let e=n.ownerDocument.createElement("div");return ng(e,t),n.appendChild(e),{mode:"direct",host:e,shell:null,syncWidgetState:()=>{},updateConfig(r){ng(e,r)},destroy(){e.remove()}}},Sb=(n,t)=>{var B,I,R,A;let{ownerDocument:e}=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=e.createElement("div"),i=e.createElement("div"),d=e.createElement("div"),c=e.createElement("aside"),g=e.createElement("div"),f=(I=(B=t==null?void 0:t.launcher)==null?void 0:B.enabled)==null||I?(A=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",g.dataset.personaDockRole="host",c.appendChild(g),r.insertBefore(a,n),d.appendChild(n);let u=null,m=()=>{u==null||u.disconnect(),u=null},v=()=>{m(),vr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(u=new ResizeObserver(()=>{og(a,i,d,c,g,t,f)}),u.observe(a))},x=!1,E=()=>{og(a,i,d,c,g,t,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,xb(a,vr(t)))},M=a.ownerDocument.defaultView,S=()=>{E()};return M==null||M.addEventListener("resize",S),vr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:g,shell:a,syncWidgetState(L){let N=L.launcherEnabled?L.open:!0;f!==N&&(f=N,E())},updateConfig(L){var N,F;t=L,((F=(N=t==null?void 0:t.launcher)==null?void 0:N.enabled)!=null?F:!0)===!1&&(f=!0),E()},destroy(){M==null||M.removeEventListener("resize",S),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},sg=(n,t)=>An(t)?Sb(n,t):Ab(n,t);var va={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ag=.15,ig=1.5,Rl="persona-preview-shell-theme",Tb={load:()=>null,save:()=>{},clear:()=>{}},Eb=["How do I get started?","Pricing & plans","Talk to support"];function Bl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Mb(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 lg(n){let t=Mb(n);return`* { box-sizing: border-box; }
111
+ `}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=zu(()=>{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(()=>om(n)))}let ho=xm(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?du(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=Qu(),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<yy&&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=()=>_?qm(_.getMessages()).filter(l=>!l.__skipPersist):[];function Zr(l){if(!(i!=null&&i.save))return;let h={messages:l?qm(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}=em({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=tm({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});p!==yn.spacerHeight&&Fr(p)}Je()},og=l=>{let p=et();p==="follow"?(Nr(),Hn(!0)):p==="anchor-top"&&Bn(l)},sg=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)})},ag=(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&&Om(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=Gu(P,Oo)+Ft,zt=Ne||De||ge?null:Xu(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=_m(P);if(Ye){let an=Tr.get(P.id),_t=an!==Dt,Ot=r.wrapComponentDirectiveInBubble!==!1,ft=null;if(_t){let Vt=Nm(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),Ju(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)})})}Yu(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)=>{ag(l,p,h),Gr()},bs=null,ig=()=>{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,lg=()=>{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,cg=()=>{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=cg(),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 dg=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"),dg(k),ce.style.display=k?"flex":"none",ye(),k?(ig(),lg()):(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,pg=()=>{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),pg(),Fo(l),Hn(!Ar),sg(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,og(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(),hg();break;case"speaking":Or(),yg();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()},ug=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},li={...Ba},ci=!1,la=()=>{li={...Ba}},mg=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),gg=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(ug()&&(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=Ku({direction:l.key==="ArrowUp"?"up":"down",history:mg(),currentValue:Te.value,atStart:p,state:li});if(li=h.state,h.handled){l.preventDefault(),h.value!==void 0&&gg(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=vy(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")}}},fg=(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")},hg=()=>{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")},yg=()=>{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 bg=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(bg);let vg=s.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});dt.push(vg);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),xg=()=>{let l=we.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:we.ownerDocument.getSelection()},ui=()=>Zu(xg(),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=zm(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=fg(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(jm(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=$m({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=Um({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=xy(r.persistState);if(rr&&D()){let l=wy(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 Cy=(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},Ay=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},Sy=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},Ty=(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.")},Km=(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=""},Gm=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=""},My=(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))},Ey=(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)},Qm=(n,e,t,r,o,s,a)=>{var v,x,I,M,E,F;let i=gr(s),d=i.reveal==="push";My(n,e,t,r,d),Ey(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),Gm(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"),Gm(r),Ay(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=Cy(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",Sy(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")}},ky=(n,e)=>{let t=n.ownerDocument.createElement("div");return Km(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Km(t,r)},destroy(){t.remove()}}},Ly=(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(()=>{Qm(a,i,d,c,m,e,f)}),g.observe(a))},x=!1,I=()=>{Qm(a,i,d,c,m,e,f),v(),f&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,Ty(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()}}},Xm=(n,e)=>gn(e)?Ly(n,e):ky(n,e);var na={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Jm=.15,Ym=1.5,pl="persona-preview-shell-theme",Py={load:()=>null,save:()=>{},clear:()=>{}},Iy=["How do I get started?","Pricing & plans","Talk to support"];function ul(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Wy(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 Zm(n){let e=Wy(n);return`* { box-sizing: border-box; }
110
112
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
111
113
  html { color-scheme: ${n}; }
112
- body { font-family: system-ui, sans-serif; background: ${t.pageBg}; }
114
+ body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
113
115
  .preview-iframe-mock { min-height: 100%; }
114
- .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
115
- .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${t.dot}; }
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; }
117
+ .preview-iframe-dot { width: 10px; height: 10px; border-radius: 50%; background: ${e.dot}; }
116
118
  .preview-iframe-copy { padding: 32px; }
117
- .preview-iframe-line { border-radius: 999px; background: ${t.skeleton}; margin-bottom: 12px; }
119
+ .preview-iframe-line { border-radius: 999px; background: ${e.skeleton}; margin-bottom: 12px; }
118
120
  .preview-iframe-line.hero { width: 48%; height: 16px; }
119
121
  .preview-iframe-line.body { width: 72%; height: 10px; }
120
122
  .preview-iframe-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin: 24px 0; }
121
- .preview-iframe-card { height: 84px; border-radius: 14px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
123
+ .preview-iframe-card { height: 84px; border-radius: 14px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
122
124
  .preview-workspace-shell { height: 100%; min-height: 100%; display: flex; flex-direction: column; }
123
- .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${t.chromeBorder}; background: ${t.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
125
+ .preview-workspace-topbar { height: 52px; flex-shrink: 0; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; justify-content: space-between; padding: 0 18px; }
124
126
  .preview-workspace-topbar-left { display: flex; align-items: center; gap: 12px; }
125
- .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
126
- .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${t.skeleton}; }
127
- .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
127
+ .preview-workspace-topbar-badge { width: 18px; height: 18px; border-radius: 6px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
128
+ .preview-workspace-topbar-line { width: 180px; height: 10px; border-radius: 999px; background: ${e.skeleton}; }
129
+ .preview-workspace-topbar-pill { width: 64px; height: 28px; border-radius: 999px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
128
130
  .preview-workspace-body { flex: 1; min-height: 0; display: flex; padding: 20px; }
129
- .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
131
+ .preview-workspace-content { position: relative; display: flex; flex-direction: column; flex: 1; width: 100%; height: 100%; min-width: 0; min-height: 0; overflow: hidden; border-radius: 24px; background: rgba(255,255,255,0.72); box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
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
- .preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${t.cardBg}; box-shadow: inset 0 0 0 1px ${t.cardBorder}; }
133
- .preview-workspace-card.short { height: 96px; }`}function cg(n,t){let e=n.contentDocument;if(!(e!=null&&e.documentElement))return;let r=e.getElementById(Rl);r||(r=e.createElement("style"),r.id=Rl,e.head.appendChild(r)),r.textContent=lg(t)}var kb=`
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}; }
135
+ .preview-workspace-card.short { height: 96px; }`}function eg(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(pl);r||(r=t.createElement("style"),r.id=pl,t.head.appendChild(r)),r.textContent=Zm(e)}var Ry=`
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: ${e.message}_`:r}var ra=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>`,Lb=`
154
+ </div>`,Hy=`
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,8 +164,8 @@ _Details: ${e.message}_`:r}var ra=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 dg(n,t,e,r){let o=`
166
- ${kb}
167
+ </div>`;function tg(n,e,t,r){let o=`
168
+ ${Ry}
167
169
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
168
170
  <div class="preview-workspace-shell">
169
171
  <div class="preview-workspace-topbar">
@@ -175,7 +177,7 @@ _Details: ${e.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
175
177
  </div>
176
178
  <div class="preview-workspace-body">
177
179
  <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
178
- ${Lb}
180
+ ${Hy}
179
181
  </div>
180
182
  </div>
181
183
  </div>`;return`<!DOCTYPE html>
@@ -183,16 +185,16 @@ _Details: ${e.message}_`:r}var ra=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="${Bl(r)}">
187
- <style id="${Rl}">${lg(t)}</style>
188
+ <link rel="stylesheet" href="${ul(r)}">
189
+ <style id="${pl}">${Zm(e)}</style>
188
190
  </head>
189
191
  <body>
190
- ${e?s:o}
192
+ ${t?s:o}
191
193
  </body>
192
- </html>`}var Ib=()=>[{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()}],Pb=n=>{var t,e,r,o,s,a,i,d;return!!((e=(t=n==null?void 0:n.features)==null?void 0:t.toolCallDisplay)!=null&&e.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Wb(n,t,e=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="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()}]:n==="conversation"&&Pb(t)?[...Ib(),...e]:[{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()},...e]}function Rb(n,t,e=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:t!=="minimized"},o={...n,launcher:r,suggestionChips:t==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Eb:n.suggestionChips,initialMessages:Wb(t,n,e),storageAdapter:Tb};return t==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Bb(n,t){var r,o;let e=n.theme?qo(n.theme,{validate:!1}):qo();return{...zt,...n.config,theme:e,darkTheme:n.darkTheme,colorScheme:(o=t!=null?t:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ts(n,t){var r,o;let e=(r=n.scene)!=null?r:"conversation";return Rb(Bb(n,t),e,(o=n.appendedMessages)!=null?o:[])}function pg(n){var r,o,s,a,i;let t=(r=n.compareMode)!=null?r:"off",e=(o=n.shellMode)!=null?o:"light";if(t==="themes")return[{mountId:"preview-light",label:"Light",config:Ts(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ts(n,"dark"),shellMode:"dark"}];if(t==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ts(d,e),shellMode:e},{mountId:"preview-current",label:"Current",config:Ts(n,e),shellMode:e}]}return[{mountId:"preview-current",label:"Current",config:Ts(n,e),shellMode:e}]}function ug(n,t){let e={...t},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function g(){var S;return(S=e.device)!=null?S:"desktop"}function f(){var S;return(S=e.zoom)!=null?S:i}function u(){var k,z;let S=getComputedStyle(n),B=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),I=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),R=40,A=((k=e.compareMode)!=null?k:"off")!=="off",L=(n.clientWidth-B-R)/(A?2:1),N=n.clientHeight-I-R;if(L<=0||N<=0)return 1;let F=(z=va[g()])!=null?z:va.desktop;return Math.min(L/F.w,N/F.h,1)}function m(){var I,R,A;i=u();let S=Math.max(ag,Math.min(ig,f()));d=S;let B=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let L of B){let N=(I=L.dataset.device)!=null?I:"desktop",F=(R=va[N])!=null?R:va.desktop;L.style.width=`${F.w*S}px`,L.style.height=`${F.h*S}px`,N==="mobile"&&(L.style.borderRadius=`${32*S}px`);let k=L.querySelector("iframe");k&&(k.style.width=`${F.w}px`,k.style.height=`${F.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${S})`)}(A=e.onScaleChange)==null||A.call(e,S)}function v(){var S;(S=e.onBeforeDestroy)==null||S.call(e);for(let B of r)B.destroy();for(let B of o)B();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function E(){var ve,Ne,qe,Te;if(a)return;v();let S=++c,B=pg(e),I=g(),R=((ve=e.compareMode)!=null?ve:"off")!=="off",A=((Ne=e.scene)!=null?Ne:"conversation")==="minimized",L=(qe=e.widgetCssPath)!=null?qe:"/widget-dist/widget.css",N=(Te=e.buildSrcdoc)!=null?Te:dg,F=I==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=we=>`<div class="${F}" data-mount-id="${we.mountId}" data-device="${I}" data-shell-mode="${we.shellMode}">
193
- ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${Bl(we.label)}</span></div>`:""}
194
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${we.mountId}"></iframe>
195
- </div>`,z=R?`<div class="preview-compare-grid">${B.map(we=>`<div class="preview-compare-cell">${k(we)}</div>`).join("")}</div>`:`<div class="preview-single">${k(B[0])}</div>`;e.morphContainer?e.morphContainer(n,z):n.innerHTML=z,m();let j=x(),re=0,Ie=j.length,Ve=()=>{var oe,X,se,fe,pe;if(a||S!==c)return;for(let K of j){let ae=K.dataset.mountId;if(!ae||!K.contentDocument)continue;let Be=B.find(at=>at.mountId===ae);if(!Be)continue;let ee=()=>{},Z=An(Be.config),ne=Z?(()=>{var J;let at=(J=K.contentDocument)==null?void 0:J.getElementById(`preview-content-${ae}`);if(!at)return null;let nt=sg(at,Be.config),Me=K.contentDocument.createElement("div");Me.id=ae,Me.style.height="100%",Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1",Me.style.minHeight="0",nt.host.appendChild(Me);let he=()=>nt.syncWidgetState(st.getState()),Ge=ee;return ee=()=>{nt.destroy(),Ge()},Me.__syncDock=he,Me.__hostLayout=nt,Me})():K.contentDocument.getElementById(ae);if(!ne)continue;let st=tg(ne,Be.config);if(r.push(st),Z&&ne.__syncDock){let at=ne.__syncDock,nt=st.on("widget:opened",at),Me=st.on("widget:closed",at),he=ee;ee=()=>{nt(),Me(),he()},at()}o.push(ee),A&&st.close()}if(((oe=e.scene)!=null?oe:"conversation")==="artifact"||(fe=(se=(X=e.config)==null?void 0:X.features)==null?void 0:se.artifacts)!=null&&fe.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
194
+ </html>`}var By=()=>[{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()}],Dy=n=>{var e,t,r,o,s,a,i,d;return!!((t=(e=n==null?void 0:n.features)==null?void 0:e.toolCallDisplay)!=null&&t.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Ny(n,e,t=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="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()}]:n==="conversation"&&Dy(e)?[...By(),...t]:[{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()},...t]}function Fy(n,e,t=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...n,launcher:r,suggestionChips:e==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:Iy:n.suggestionChips,initialMessages:Ny(e,n,t),storageAdapter:Py};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Oy(n,e){var r,o;let t=n.theme?Wo(n.theme,{validate:!1}):Wo();return{...Nt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function gs(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Fy(Oy(n,e),t,(o=n.appendedMessages)!=null?o:[])}function ng(n){var r,o,s,a,i;let e=(r=n.compareMode)!=null?r:"off",t=(o=n.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:gs(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:gs(n,"dark"),shellMode:"dark"}];if(e==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:gs(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:gs(n,t),shellMode:t}]}function rg(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function m(){var E;return(E=t.device)!=null?E:"desktop"}function f(){var E;return(E=t.zoom)!=null?E:i}function g(){var k,j;let E=getComputedStyle(n),F=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),L=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),R=40,A=((k=t.compareMode)!=null?k:"off")!=="off",W=(n.clientWidth-F-R)/(A?2:1),N=n.clientHeight-L-R;if(W<=0||N<=0)return 1;let D=(j=na[m()])!=null?j:na.desktop;return Math.min(W/D.w,N/D.h,1)}function u(){var L,R,A;i=g();let E=Math.max(Jm,Math.min(Ym,f()));d=E;let F=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let W of F){let N=(L=W.dataset.device)!=null?L:"desktop",D=(R=na[N])!=null?R:na.desktop;W.style.width=`${D.w*E}px`,W.style.height=`${D.h*E}px`,N==="mobile"&&(W.style.borderRadius=`${32*E}px`);let k=W.querySelector("iframe");k&&(k.style.width=`${D.w}px`,k.style.height=`${D.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${E})`)}(A=t.onScaleChange)==null||A.call(t,E)}function v(){var E;(E=t.onBeforeDestroy)==null||E.call(t);for(let F of r)F.destroy();for(let F of o)F();r=[],o=[]}function x(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function I(){var xe,Ie,_e,Se;if(a)return;v();let E=++c,F=ng(t),L=m(),R=((xe=t.compareMode)!=null?xe:"off")!=="off",A=((Ie=t.scene)!=null?Ie:"conversation")==="minimized",W=(_e=t.widgetCssPath)!=null?_e:"/widget-dist/widget.css",N=(Se=t.buildSrcdoc)!=null?Se:tg,D=L==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=ve=>`<div class="${D}" data-mount-id="${ve.mountId}" data-device="${L}" data-shell-mode="${ve.shellMode}">
195
+ ${R?`<div class="preview-frame-meta"><span class="preview-frame-label">${ul(ve.label)}</span></div>`:""}
196
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ve.mountId}"></iframe>
197
+ </div>`,j=R?`<div class="preview-compare-grid">${F.map(ve=>`<div class="preview-compare-cell">${k(ve)}</div>`).join("")}</div>`:`<div class="preview-single">${k(F[0])}</div>`;t.morphContainer?t.morphContainer(n,j):n.innerHTML=j,u();let V=x(),ne=0,Re=V.length,Ue=()=>{var re,X,ie,he,oe;if(a||E!==c)return;for(let K of V){let te=K.dataset.mountId;if(!te||!K.contentDocument)continue;let qe=F.find(lt=>lt.mountId===te);if(!qe)continue;let Y=()=>{},le=gn(qe.config),Pe=le?(()=>{var J;let lt=(J=K.contentDocument)==null?void 0:J.getElementById(`preview-content-${te}`);if(!lt)return null;let rt=Xm(lt,qe.config),Ee=K.contentDocument.createElement("div");Ee.id=te,Ee.style.height="100%",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1",Ee.style.minHeight="0",rt.host.appendChild(Ee);let pe=()=>rt.syncWidgetState(it.getState()),Xe=Y;return Y=()=>{rt.destroy(),Xe()},Ee.__syncDock=pe,Ee.__hostLayout=rt,Ee})():K.contentDocument.getElementById(te);if(!Pe)continue;let it=Vm(Pe,qe.config);if(r.push(it),le&&Pe.__syncDock){let lt=Pe.__syncDock,rt=it.on("widget:opened",lt),Ee=it.on("widget:closed",lt),pe=Y;Y=()=>{rt(),Ee(),pe()},lt()}o.push(Y),A&&it.close()}if(((re=t.scene)!=null?re:"conversation")==="artifact"||(he=(ie=(X=t.config)==null?void 0:X.features)==null?void 0:ie.artifacts)!=null&&he.enabled)for(let K of r)K.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`});(pe=e.onAfterMount)==null||pe.call(e,{iframes:j,controllers:[...r]})};for(let we of j){let oe=we.dataset.mountId;if(!oe)continue;let X=B.find(se=>se.mountId===oe);X&&(we.addEventListener("load",()=>{re++,re>=Ie&&Ve()},{once:!0}),we.srcdoc=N(oe,X.shellMode,An(X.config),L))}Ie===0&&Ve()}function M(){var I;if(a)return;let S=pg(e);if(r.length!==S.length){E();return}if(S.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){E();return}r.forEach((R,A)=>{var L;R.update(S[A].config),((L=e.scene)!=null?L:"conversation")==="minimized"&&R.close()});for(let R of S){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&cg(A,R.shellMode)}(I=e.onAfterUpdate)==null||I.call(e,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),E(),{update(S){if(a)return;let B=S.device!==void 0&&S.device!==e.device||S.scene!==void 0&&S.scene!==e.scene||S.compareMode!==void 0&&S.compareMode!==e.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==e.widgetCssPath;e={...e,...S},B?E():M()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(e={...e,zoom:void 0},m())},getIframes(){return x()},getScale(){return d},setZoom(S){a||(e={...e,zoom:S},m())}}}0&&(module.exports={createThemePreview});
205
+ - Resizable panes`});(oe=t.onAfterMount)==null||oe.call(t,{iframes:V,controllers:[...r]})};for(let ve of V){let re=ve.dataset.mountId;if(!re)continue;let X=F.find(ie=>ie.mountId===re);X&&(ve.addEventListener("load",()=>{ne++,ne>=Re&&Ue()},{once:!0}),ve.srcdoc=N(re,X.shellMode,gn(X.config),W))}Re===0&&Ue()}function M(){var L;if(a)return;let E=ng(t);if(r.length!==E.length){I();return}if(E.some(R=>{let A=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${R.mountId}"]`);return!A||A.dataset.shellMode!==R.shellMode})){I();return}r.forEach((R,A)=>{var W;R.update(E[A].config),((W=t.scene)!=null?W:"conversation")==="minimized"&&R.close()});for(let R of E){let A=n.querySelector(`iframe[data-mount-id="${R.mountId}"]`);A&&eg(A,R.shellMode)}(L=t.onAfterUpdate)==null||L.call(t,{iframes:x(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||u()}),s.observe(n)),I(),{update(E){if(a)return;let F=E.device!==void 0&&E.device!==t.device||E.scene!==void 0&&E.scene!==t.scene||E.compareMode!==void 0&&E.compareMode!==t.compareMode||E.widgetCssPath!==void 0&&E.widgetCssPath!==t.widgetCssPath;t={...t,...E},F?I():M()},destroy(){a||(a=!0,v(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},u())},getIframes(){return x()},getScale(){return d},setZoom(E){a||(t={...t,zoom:E},u())}}}0&&(module.exports={createThemePreview});