@runtypelabs/persona 4.7.0 → 4.8.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 (117) hide show
  1. package/dist/animations/glyph-cycle.cjs +2 -2
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/glyph-cycle.js +2 -2
  5. package/dist/animations/{types-CSmiKRVa.d.cts → types-BsZtXPKK.d.cts} +43 -3
  6. package/dist/animations/{types-CSmiKRVa.d.ts → types-BsZtXPKK.d.ts} +43 -3
  7. package/dist/animations/wipe.cjs +2 -2
  8. package/dist/animations/wipe.d.cts +1 -1
  9. package/dist/animations/wipe.d.ts +1 -1
  10. package/dist/chunk-5EIIHQLQ.js +1 -0
  11. package/dist/codegen.cjs +12 -12
  12. package/dist/codegen.js +14 -14
  13. package/dist/index.cjs +91 -68
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +877 -172
  16. package/dist/index.d.ts +877 -172
  17. package/dist/index.global.js +81 -57
  18. package/dist/index.global.js.map +1 -1
  19. package/dist/index.js +91 -68
  20. package/dist/index.js.map +1 -1
  21. package/dist/install.global.js +1 -1
  22. package/dist/install.global.js.map +1 -1
  23. package/dist/launcher.global.js +3 -2
  24. package/dist/launcher.global.js.map +1 -1
  25. package/dist/markdown-parsers.js +24 -24
  26. package/dist/plugin-kit.cjs +1 -1
  27. package/dist/plugin-kit.js +1 -1
  28. package/dist/runtype-tts-entry-UJAEF7NZ.js +1 -0
  29. package/dist/runtype-tts.js +1 -1
  30. package/dist/session-reconnect-JKIJBHS5.js +1 -0
  31. package/dist/smart-dom-reader.cjs +17 -17
  32. package/dist/smart-dom-reader.d.cts +753 -15
  33. package/dist/smart-dom-reader.d.ts +753 -15
  34. package/dist/smart-dom-reader.js +17 -17
  35. package/dist/testing.cjs +3 -3
  36. package/dist/testing.js +3 -3
  37. package/dist/theme-editor-preview.cjs +81 -58
  38. package/dist/theme-editor-preview.d.cts +761 -15
  39. package/dist/theme-editor-preview.d.ts +761 -15
  40. package/dist/theme-editor-preview.js +81 -58
  41. package/dist/theme-editor.cjs +6 -6
  42. package/dist/theme-editor.d.cts +753 -15
  43. package/dist/theme-editor.d.ts +753 -15
  44. package/dist/theme-editor.js +10 -10
  45. package/dist/theme-reference.cjs +1 -1
  46. package/dist/theme-reference.d.cts +74 -0
  47. package/dist/theme-reference.d.ts +74 -0
  48. package/dist/theme-reference.js +1 -1
  49. package/dist/voice-worklet-player.cjs +2 -2
  50. package/dist/voice-worklet-player.js +2 -2
  51. package/dist/webmcp-polyfill.js +2 -2
  52. package/dist/widget.css +1 -1
  53. package/package.json +2 -3
  54. package/src/artifacts-session.test.ts +178 -0
  55. package/src/client.test.ts +186 -1
  56. package/src/client.ts +92 -9
  57. package/src/components/artifact-card.test.ts +333 -0
  58. package/src/components/artifact-card.ts +75 -28
  59. package/src/components/artifact-inline.test.ts +1328 -0
  60. package/src/components/artifact-inline.ts +920 -0
  61. package/src/components/artifact-pane.test.ts +1042 -0
  62. package/src/components/artifact-pane.ts +440 -131
  63. package/src/components/artifact-preview.test.ts +1155 -0
  64. package/src/components/artifact-preview.ts +994 -0
  65. package/src/components/pill-composer-builder.test.ts +6 -2
  66. package/src/components/pill-composer-builder.ts +6 -6
  67. package/src/components/reasoning-bubble.ts +1 -13
  68. package/src/components/registry.ts +38 -3
  69. package/src/components/tool-bubble.ts +1 -13
  70. package/src/defaults.ts +1 -0
  71. package/src/generated/runtype-openapi-contract.ts +55 -3
  72. package/src/index-core.ts +20 -1
  73. package/src/index.ts +8 -0
  74. package/src/markdown-parsers-loader.test.ts +158 -0
  75. package/src/markdown-parsers-loader.ts +74 -9
  76. package/src/runtime/host-layout.test.ts +163 -0
  77. package/src/runtime/host-layout.ts +110 -7
  78. package/src/runtime/init.ts +18 -61
  79. package/src/session.ts +76 -22
  80. package/src/styles/widget.css +773 -26
  81. package/src/theme-editor/preview.ts +2 -0
  82. package/src/theme-editor/sections.test.ts +26 -1
  83. package/src/theme-editor/sections.ts +10 -2
  84. package/src/theme-reference.ts +2 -2
  85. package/src/tool-call-display-defaults.test.ts +1 -0
  86. package/src/types/theme.ts +77 -0
  87. package/src/types.ts +516 -17
  88. package/src/ui.artifact-pane-gating.test.ts +636 -0
  89. package/src/ui.component-directive.test.ts +104 -0
  90. package/src/ui.composer-bar.test.ts +60 -2
  91. package/src/ui.detached-panel.test.ts +1049 -0
  92. package/src/ui.tool-display.test.ts +51 -0
  93. package/src/ui.ts +698 -109
  94. package/src/utils/artifact-custom-actions.ts +128 -0
  95. package/src/utils/artifact-display.test.ts +42 -0
  96. package/src/utils/artifact-display.ts +84 -0
  97. package/src/utils/artifact-file.test.ts +116 -0
  98. package/src/utils/artifact-file.ts +117 -0
  99. package/src/utils/artifact-gate.test.ts +112 -5
  100. package/src/utils/artifact-gate.ts +39 -14
  101. package/src/utils/artifact-loading-status.ts +55 -0
  102. package/src/utils/artifact-status-label.ts +190 -0
  103. package/src/utils/buttons.ts +7 -1
  104. package/src/utils/code-highlight.test.ts +186 -0
  105. package/src/utils/code-highlight.ts +400 -0
  106. package/src/utils/icons.ts +2 -0
  107. package/src/utils/roving-tablist.test.ts +152 -0
  108. package/src/utils/roving-tablist.ts +111 -0
  109. package/src/utils/spinner.ts +45 -0
  110. package/src/utils/theme.test.ts +48 -0
  111. package/src/utils/theme.ts +7 -0
  112. package/src/utils/tokens.ts +91 -0
  113. package/src/utils/tool-loading-animation.test.ts +32 -0
  114. package/src/utils/tool-loading-animation.ts +24 -0
  115. package/dist/chunk-DFBSCFYN.js +0 -1
  116. package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
  117. package/dist/session-reconnect-U77QFUR7.js +0 -1
@@ -1,22 +1,28 @@
1
- "use strict";var Sf=Object.create;var Ea=Object.defineProperty;var Tf=Object.getOwnPropertyDescriptor;var Ef=Object.getOwnPropertyNames;var Mf=Object.getPrototypeOf,kf=Object.prototype.hasOwnProperty;var ds=(n,e)=>()=>(n&&(e=n(n=0)),e);var Ma=(n,e)=>{for(var t in e)Ea(n,t,{get:e[t],enumerable:!0})},Au=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ef(e))!kf.call(n,o)&&o!==t&&Ea(n,o,{get:()=>e[o],enumerable:!(r=Tf(e,o))||r.enumerable});return n};var Su=(n,e,t)=>(t=n!=null?Sf(Mf(n)):{},Au(e||!n||!n.__esModule?Ea(t,"default",{value:n,enumerable:!0}):t,n)),Lf=n=>Au(Ea({},"__esModule",{value:!0}),n);var Mu={};Ma(Mu,{DOMPurify:()=>Eu.default,Marked:()=>Tu.Marked});var Tu,Eu,ku=ds(()=>{"use strict";Tu=require("marked"),Eu=Su(require("dompurify"),1)});var vs,Xi=ds(()=>{"use strict";vs=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 l of a)l()}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 Dh(n){return n.replace(/\/+$/,"")}async function Nh(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 za,bm=ds(()=>{"use strict";Xi();za=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 vs(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,l;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var h;e===this.generation&&((h=r.onStart)==null||h.call(r))}),d.onFinished(()=>{var h;e===this.generation&&((h=r.onEnd)==null||h.call(r))});let c=`${Dh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,u=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!u.ok||!u.body)throw new Error(await Nh(u));let g=u.body.getReader();for(;;){let{done:h,value:m}=await g.read();if(e!==this.generation){await g.cancel().catch(()=>{});return}if(h)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(l=r.onError)==null||l.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 ja,vm=ds(()=>{"use strict";ja=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,l;if(r){(s=t.onError)==null||s.call(t,o);return}(l=(a=this.options).onFallback)==null||l.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 wm={};Ma(wm,{FallbackSpeechEngine:()=>ja,RuntypeSpeechEngine:()=>za});var xm=ds(()=>{"use strict";bm();vm()});var Am={};Ma(Am,{createReconnectController:()=>Oh});function Oh(n){let e=0,t=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),t){let y=t;t=null,y()}},a=()=>{let y=n.getStatus();y!=="resuming"&&y!=="paused"||s()},l=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",l),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},u=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",l),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},g=y=>new Promise(w=>{t=w,r=setTimeout(()=>{r=null,t=null,w()},y)}),h=()=>{var W;let y=n.getResumable();n.clearResumable(),n.setReconnecting(!1),e=0,u(),n.setAbortController(null);let w=!1;for(let E of n.getMessages())E.streaming&&(E.streaming=!1,w=!0);let T=n.buildErrorContent("Connection lost and the response could not be resumed.");T?n.appendMessage({id:`reconnect-failed-${(W=y==null?void 0:y.executionId)!=null?W:n.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:n.nextSequence()}):w&&n.notifyMessagesChanged(),n.setStreaming(!1),n.setStatus("idle"),n.onError(new Error("Durable session reconnect failed."))},m=async()=>{var W,E,H,B,I,S;let y=(E=(W=n.config.reconnect)==null?void 0:W.backoffMs)!=null?E:Fh,w=(B=(H=n.config.reconnect)==null?void 0:H.maxAttempts)!=null?B:y.length,T=n.config.reconnectStream;if(!T){n.setReconnecting(!1);return}for(;n.getResumable()&&e<w;){e+=1,n.setStatus("resuming");let P=n.getResumable(),z=P.lastEventId,U=new AbortController;n.setAbortController(U),n.emitReconnect({phase:"resuming",handle:P,attempt:e});let k=null;try{let _=await T({executionId:P.executionId,after:P.lastEventId,signal:U.signal});_&&_.ok&&_.body&&(k=_.body)}catch{k=null}if(U.signal.aborted)return;if(k){let _=(I=n.getMessages().find(Z=>Z.id===P.assistantMessageId))==null?void 0:I.content,O=typeof _=="string"?_:"";try{await n.resumeConnect(k,P.assistantMessageId,O)}catch{}if(U.signal.aborted)return;if(!n.getResumable()){n.setReconnecting(!1),e=0,u(),n.emitReconnect({phase:"resumed",handle:P});return}n.getResumable().lastEventId!==z&&(e=0)}if(n.getResumable()&&e<w&&(n.setStatus("paused"),await g((S=y[Math.min(e-1,y.length-1)])!=null?S:1e3),U.signal.aborted))return}n.getResumable()&&h()};return{begin(){e=0,c(),m()},teardown(){r&&(clearTimeout(r),r=null),t=null,e=0,u()},wake:s}}var Fh,Sm=ds(()=>{"use strict";Fh=[1e3,2e3,4e3,8e3,8e3]});var Yb={};Ma(Yb,{createThemePreview:()=>Jg});module.exports=Lf(Yb);var Lu=null,js=null,ps=null;var Pu=()=>js?Promise.resolve(js):ps||(Lu?(ps=Lu().then(n=>(js=n,n)),ps):(ps=Promise.resolve().then(()=>(ku(),Mu)).then(n=>(js=n,n)),ps)),$o=()=>js;var Pf=n=>{if(n)return n},Di=n=>{let e=null;return t=>{var o,s;let r=$o();if(!r)return ho(t);if(!e){let{Marked:a}=r,l=n==null?void 0:n.markedOptions;e=new a({gfm:(o=l==null?void 0:l.gfm)!=null?o:!0,breaks:(s=l==null?void 0:l.breaks)!=null?s:!0,pedantic:l==null?void 0:l.pedantic,silent:l==null?void 0:l.silent});let d=Pf(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},ka=n=>n?Di({markedOptions:n.options,renderer:n.renderer}):Di(),ov=Di();var ho=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var If={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"]},Rf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wf=()=>{let n=null;return e=>{let t=$o();if(!t)return ho(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:")&&!Rf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,If)}},La=n=>n===!1?null:typeof n=="function"?n:Wf();var Iu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ru=n=>n.includes("|"),Wu=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())},Hf=n=>`| ${n.join(" | ")} |`,Bf=n=>`| ${Array.from({length:n},()=>"---").join(" | ")} |`,Df=(n,e)=>n.length>=e?n.slice(0,e):n.concat(Array.from({length:e-n.length},()=>"")),Hu=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(!Ru(o)||Iu.test(o)||!Iu.test(s))continue;let a=Wu(o).length;if(a<1)continue;let l=Bf(a);e[r+1]!==l&&(e[r+1]=l,t=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!Ru(c))break;let u=Hf(Df(Wu(c),a));e[d]!==u&&(e[d]=u,t=!0)}r=d-1}return t?e.join(`
3
- `):n};var Vr="webmcp:",Ni=new Map,Bu=n=>{var e;Ni.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&Ni.set(t.name,r)}},Vs=n=>Ni.get(Ou(n)),Pa={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Du=null;function Fu(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}:${Nf(e.join(""))}`}function Nu(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 Nf(n){let e=Nu(n,0).toString(36),t=Nu(n,2654435761).toString(36);return`${e}.${t}`}var Ia=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 Pa.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Bu(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=Of(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,r){if(await this.ensureReady(),this.config.enabled!==!0)return ur("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let y=typeof document!="undefined"&&!!document.modelContext;return ur(y?"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=Ou(e),a;try{a=await o.getTools()}catch(y){let w=y instanceof Error?y.message:String(y);return ur(`Failed to read WebMCP registry: ${w}`)}Bu(a);let l=a.find(y=>y.name===s);if(!l)return ur(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return ur(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return ur("Aborted by cancel()");let d=Vs(s),c={toolName:s,args:t,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return ur("User declined the tool call.");if(r!=null&&r.aborted)return ur("Aborted by cancel()");let u=new AbortController,g=!1,h=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();r&&(r.aborted?u.abort():r.addEventListener("abort",m,{once:!0}));try{let y=await o.executeTool(l,qf(t),{signal:u.signal});return _f(y)}catch(y){if(g)return ur(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return ur("Aborted by cancel()");let w=y instanceof Error?y.message:String(y);return ur(w)}finally{clearTimeout(h),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}(Du?await Du():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Pa.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,Pa.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:$f;try{return await t(e)}catch(o){return Pa.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=>Ff(e,r))}},Ou=n=>n.startsWith(Vr)?n.slice(Vr.length):n,us=n=>n.startsWith(Vr),Ff=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Of=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},_f=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:zf(e)}]}},ur=n=>({isError:!0,content:[{type:"text",text:n}]}),$f=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Uf(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
1
+ "use strict";var Ef=Object.create;var Js=Object.defineProperty;var kf=Object.getOwnPropertyDescriptor;var Lf=Object.getOwnPropertyNames;var Pf=Object.getPrototypeOf,If=Object.prototype.hasOwnProperty;var Zo=(t,e)=>()=>(t&&(e=t(t=0)),e);var Ys=(t,e)=>{for(var n in e)Js(t,n,{get:e[n],enumerable:!0})},Gc=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lf(e))!If.call(t,r)&&r!==n&&Js(t,r,{get:()=>e[r],enumerable:!(o=kf(e,r))||o.enumerable});return t};var Xc=(t,e,n)=>(n=t!=null?Ef(Pf(t)):{},Gc(e||!t||!t.__esModule?Js(n,"default",{value:t,enumerable:!0}):n,t)),Rf=t=>Gc(Js({},"__esModule",{value:!0}),t);var Yc={};Ys(Yc,{DOMPurify:()=>Jc.default,Marked:()=>Qc.Marked});var Qc,Jc,Zc=Zo(()=>{"use strict";Qc=require("marked"),Jc=Xc(require("dompurify"),1)});var ir,Gi=Zo(()=>{"use strict";ir=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function _g(t){return t.replace(/\/+$/,"")}async function $g(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var ba,qd=Zo(()=>{"use strict";Gi();ba=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new ir(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${_g(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await $g(a));let l=a.body.getReader();for(;;){let{done:p,value:d}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var va,Vd=Zo(()=>{"use strict";va=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Kd={};Ys(Kd,{FallbackSpeechEngine:()=>va,RuntypeSpeechEngine:()=>ba});var Gd=Zo(()=>{"use strict";qd();Vd()});var Qd={};Ys(Qd,{createReconnectController:()=>zg});function zg(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=t.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=b=>new Promise(x=>{n=x,o=setTimeout(()=>{o=null,n=null,x()},b)}),w=()=>{let b=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,c(),t.setAbortController(null);let x=!1;for(let W of t.getMessages())W.streaming&&(W.streaming=!1,x=!0);let P=t.buildErrorContent("Connection lost and the response could not be resumed.");P?t.appendMessage({id:`reconnect-failed-${b?.executionId??t.nextSequence()}`,role:"assistant",content:P,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):x&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},f=async()=>{let b=t.config.reconnect?.backoffMs??Ug,x=t.config.reconnect?.maxAttempts??b.length,P=t.config.reconnectStream;if(!P){t.setReconnecting(!1);return}for(;t.getResumable()&&e<x;){e+=1,t.setStatus("resuming");let W=t.getResumable(),M=W.lastEventId,R=new AbortController;t.setAbortController(R),t.emitReconnect({phase:"resuming",handle:W,attempt:e});let D=null;try{let $=await P({executionId:W.executionId,after:W.lastEventId,signal:R.signal});$&&$.ok&&$.body&&(D=$.body)}catch{D=null}if(R.signal.aborted)return;if(D){let $=t.getMessages().find(z=>z.id===W.assistantMessageId)?.content,j=typeof $=="string"?$:"";try{await t.resumeConnect(D,W.assistantMessageId,j)}catch{}if(R.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,c(),t.emitReconnect({phase:"resumed",handle:W});return}t.getResumable().lastEventId!==M&&(e=0)}if(t.getResumable()&&e<x&&(t.setStatus("paused"),await u(b[Math.min(e-1,b.length-1)]??1e3),R.signal.aborted))return}t.getResumable()&&w()};return{begin(){e=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,c()},wake:s}}var Ug,Jd=Zo(()=>{"use strict";Ug=[1e3,2e3,4e3,8e3,8e3]});var Fy={};Ys(Fy,{createThemePreview:()=>$u});module.exports=Rf(Fy);var ed=null,qr=null,ko=null,Zs=new Set,td=t=>{qr=t;let e=[...Zs];Zs.clear();for(let n of e)try{n()}catch{}return t};var ea=t=>qr?()=>{}:(Zs.add(t),Wf().catch(()=>{}),()=>{Zs.delete(t)});var nd=t=>{throw ko=null,t},Wf=()=>qr?Promise.resolve(qr):ko||(ed?(ko=ed().then(td,nd),ko):(ko=Promise.resolve().then(()=>(Zc(),Yc)).then(td,nd),ko)),Bn=()=>qr;var Bf=t=>{if(t)return t},Bi=t=>{let e=null;return n=>{let o=Bn();if(!o)return Yn(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Bf(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},ta=t=>t?Bi({markedOptions:t.options,renderer:t.renderer}):Bi(),jy=Bi();var Yn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Hf={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"]},Df=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ff=()=>{let t=null;return e=>{let n=Bn();if(!n)return Yn(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Df.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Hf)}},na=t=>t===!1?null:typeof t=="function"?t:Ff();var od=/^\s*\|?[\s:|-]*-[\s:|-]*$/,rd=t=>t.includes("|"),sd=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Nf=t=>`| ${t.join(" | ")} |`,Of=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,_f=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),ad=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
2
+ `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!rd(r)||od.test(r)||!od.test(s))continue;let a=sd(r).length;if(a<1)continue;let l=Of(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let d=e[p];if(d.trim()===""||!rd(d))break;let c=Nf(_f(sd(d),a));e[p]!==c&&(e[p]=c,n=!0)}o=p-1}return n?e.join(`
3
+ `):t};var Hn="webmcp:",Hi=new Map,id=t=>{Hi.clear();for(let e of t){let n=e.title?.trim();n&&Hi.set(e.name,n)}},Vr=t=>Hi.get(pd(t)),oa={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},ld=null;function dd(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${$f(e.join(""))}`}function cd(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function $f(t){let e=cd(t,0).toString(36),n=cd(t,2654435761).toString(36);return`${e}.${n}`}var ra=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let n;try{n=await e.getTools()}catch(r){return oa.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}id(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=zf(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return wn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return wn(b?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=pd(e),a;try{a=await r.getTools()}catch(b){let x=b instanceof Error?b.message:String(b);return wn(`Failed to read WebMCP registry: ${x}`)}id(a);let l=a.find(b=>b.name===s);if(!l)return wn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return wn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return wn("Aborted by cancel()");let p=Vr(s),d={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return wn("User declined the tool call.");if(o?.aborted)return wn("Aborted by cancel()");let c=new AbortController,u=!1,w=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let b=await r.executeTool(l,Kf(n),{signal:c.signal});return jf(b)}catch(b){if(u)return wn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return wn("Aborted by cancel()");let x=b instanceof Error?b.message:String(b);return wn(x)}finally{clearTimeout(w),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(ld?await ld():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){oa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,oa.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){let n=this.confirmHandler??qf;try{return await n(e)}catch(o){return oa.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Uf(e,o))}},pd=t=>t.startsWith(Hn)?t.slice(Hn.length):t,er=t=>t.startsWith(Hn),Uf=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},zf=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},jf=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Gf(e)}]}},wn=t=>({isError:!0,content:[{type:"text",text:t}]}),qf=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Vf(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
4
4
 
5
5
  Arguments:
6
- ${e}`:"")+(n.description?`
6
+ ${e}`:"")+(t.description?`
7
7
 
8
- ${n.description}`:"");return window.confirm(t)},Uf=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)}},qf=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},zf=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var jf="agent_",Vf="flow_";function _u(n){return n.startsWith(jf)?{kind:"agentId",agentId:n}:n.startsWith(Vf)?{kind:"flowId",flowId:n}:null}function $u(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),l=t.slice(r+1);if(a==="runtype"){let c=_u(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let o=_u(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var yo=require("partial-json");var v=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Ir=(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 l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ks=(...n)=>n.filter(Boolean).join(" ");var Fi="ask_user_question",Gs=8,ms="data-persona-ask-sheet-for",Kf="Other",Gf="Other\u2026",qu="Type your own answer here",zu="Send",Qf="Next",Xf="Back",Jf="Submit all",Yf="Skip",Zf=3,Oi="data-ask-current-index",_i="data-ask-question-count",ju="data-ask-answers",$i="data-ask-grouped",Vu="data-ask-layout",eh=n=>n.layout==="pills"?"pills":"rows",th=n=>n.getAttribute(Vu)==="pills"?"pills":"rows",Uu=!1,Ku=n=>n.replace(/["\\]/g,"\\$&"),Uo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Fi,Ui=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},gs=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,yo.parse)(o,yo.STR|yo.OBJ|yo.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Qs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>Gs&&!Uu&&(Uu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Gs}.`)),e.slice(0,Gs)},nh=n=>{var e;return(e=Qs(n)[0])!=null?e:null},rh=(n,e)=>{var t;return(t=Qs(n)[e])!=null?t:null},oh=(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))},Gu=(n,e,t)=>{if(n!=="rows")return null;let r=v("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");r.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},sh=(n,e,t,r)=>{let s=v("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=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=n.label,a.appendChild(l),n.description){let c=v("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=Gu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},ah=n=>{let t=v("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},ih=(n,e,t,r)=>{var u,g,h;let s=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");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&&!t){for(let m=0;m<Zf;m++)s.appendChild(ah(r));return s}if(d.forEach((m,y)=>{s.appendChild(sh(m,y,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Kf:Gf;if(r==="rows"){let y=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let w=v("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=e.freeTextPlaceholder)!=null?u:qu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(T),y.appendChild(w);let W=Gu(r,a,d.length);W&&y.appendChild(W),s.appendChild(y)}else{let y=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(h=e.freeTextLabel)!=null?h:m,s.appendChild(y)}}return s},Qu=(n,e)=>{var s,a;let r=v("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:qu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let l=v("button","persona-ask-free-text-submit persona-pointer-events-auto");l.type="button",l.textContent=(a=n.submitLabel)!=null?a:zu,l.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(l)}return r},lh=n=>{var r;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=v("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:zu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},ch=(n,e,t)=>{var c,u,g,h;let r=v("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=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Xf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:Yf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=n===e-1;return l.textContent=d?(g=t.submitAllLabel)!=null?g:Jf:(h=t.nextLabel)!=null?h:Qf,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),r.appendChild(s),r},qo=n=>{let e=n.getAttribute(ju);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Xu=(n,e)=>{n.setAttribute(ju,JSON.stringify(e))},tr=n=>{var t;let e=Number((t=n.getAttribute(Oi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},dh=(n,e)=>{n.setAttribute(Oi,String(Math.max(0,Math.floor(e))))},fs=n=>{var t;let e=Number((t=n.getAttribute(_i))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},bo=n=>n.getAttribute($i)==="true",ph=(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 l=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(l&&Object.prototype.hasOwnProperty.call(t,l)){let d=t[l];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},uh=(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)))},Ra=(n,e)=>{let{payload:t}=gs(e),r=Qs(t),o=qo(n),s={},a=new Set;return r.forEach((l,d)=>{let c=typeof(l==null?void 0:l.question)=="string"?l.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},Ju=n=>{let e=qo(n),t=tr(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 g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),l=n.querySelector('[data-ask-free-text-input="true"]');if(l)if(typeof r=="string"&&r.length>0&&!a.has(r)){l.value=r;let d=l.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else l.value=""},Yu=n=>{if(!bo(n))return;let e=qo(n),t=tr(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 l=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},qi=(n,e,t)=>{let r=Ui(t),o=th(n),{payload:s,complete:a}=gs(e),l=bo(n),d=tr(n),c=fs(n),u=l?rh(s,d):nh(s),g=!!(u!=null&&u.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=l?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=n.querySelector('[data-ask-question="true"]');if(y){let E=typeof(u==null?void 0:u.question)=="string"?u.question:"";y.textContent=E,y.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let E=ih(u,r,a,o);w.replaceWith(E)}if(o!=="rows"){let E=n.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(Qu(r,o))}let T=n.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!T?n.appendChild(lh(r)):(!g||l)&&T&&T.remove(),n.setAttribute("data-multi-select",g?"true":"false");let W=n.querySelector('[data-ask-nav-row="true"]');if(l){let E=ch(d,c,r);W?W.replaceWith(E):n.appendChild(E)}else W&&W.remove();Ju(n),Yu(n)},mh=(n,e,t)=>{let r=Ui(e),o=eh(r),s=n.toolCall.id,a=Qs(t),l=Math.max(1,a.length),d=l>1,c=ph(n,a),u=d?uh(n,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ms,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(_i,String(l)),g.setAttribute(Oi,String(u)),g.setAttribute($i,d?"true":"false"),g.setAttribute(Vu,o),Xu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),oh(g,r);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",h.appendChild(y),g.appendChild(h);let T=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),o!=="rows"&&g.appendChild(Qu(r,o)),qi(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},gh=(n,e,t)=>{let{payload:r}=gs(e),o=Math.max(1,Qs(r).length);o>fs(n)&&(n.setAttribute(_i,String(o)),o>1&&!bo(n)&&n.setAttribute($i,"true")),qi(n,e,t)};var Wa=(n,e,t)=>{if(!t||!Uo(n)||Ui(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ms}]`).forEach(c=>{c.getAttribute(ms)!==o&&c.remove()});let a=t.querySelector(`[${ms}="${Ku(o)}"]`);if(a){gh(a,n,e);return}let{payload:l}=gs(n),d=mh(n,e,l);t.appendChild(d)},hs=(n,e)=>{if(!n)return;let t=e?`[${ms}="${Ku(e)}"]`:`[${ms}]`;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)})},zi=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),vo=(n,e)=>{let t=qo(n),r=tr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,Xu(n,t),Ju(n),Yu(n)},Ha=(n,e,t,r)=>{let o=fs(n),s=Math.max(0,Math.min(o-1,r));dh(n,s),qi(n,e,t)};var Kr="suggest_replies";var fh={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},Zu={name:Kr,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:fh,origin:"sdk",annotations:{readOnlyHint:!0}},ji=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Vi=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===Kr},hh=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},em=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Vi(r))continue;let o=hh((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},tm=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 yh={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},bh={name:Fi,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:yh,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=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(bh),tm(n)&&e.push(Zu),e};var ys=require("partial-json"),nm=n=>n.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=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)}},vh=n=>{var a,l;let e=(a=n.completedAt)!=null?a:Date.now(),t=(l=n.startedAt)!=null?l: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`},rm=n=>n.status==="complete"?vh(n):n.status==="pending"?"Waiting":"",wh=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 om=n=>n.status==="complete"?wh(n):"Using tool...",Da=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Js=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 Da(e)},Na=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 Da(e)},Ki=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Js(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Xs(r,t.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<t.length&&Xs(r,t.slice(s),[]),r},Xs=(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})},xh=()=>{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,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=r.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>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()=>{}}},Ys=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},sm=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},am=()=>{var e;let n=xh();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)}},im=()=>{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,ys.parse)(t,ys.STR|ys.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?nm(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=nm(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var lm=()=>{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 cm="4.7.0";var Zs=cm;var Ah="https://api.runtype.com/v1/dispatch",Oa="https://api.runtype.com";function Sh(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 l=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(l&&l!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(l))return`attachment.${l}`}return"attachment"}var Gi=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 Th(n){switch(n){case"json":return im;case"regex-json":return am;case"xml":return lm;default:return sm}}var dm=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Eh(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=dm(t);if(!dm(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Ys(n);return Ys(e)!==null&&a===null?e:n}var ea=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:Ah,this.headers={"Content-Type":"application/json","X-Persona-Version":Zs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Th(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 Ia(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}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=$u(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Oa}/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 l,d,c;let e=((d=(l=this.config).getStoredSessionId)==null?void 0:d.call(l))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zs},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Oa}/v1/client/feedback`}async sendFeedback(e){var a,l;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":Zs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(l=(a=this.config).onSessionExpired)==null||l.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){var r;return(r=e.signal)==null||r.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var r,o,s,a;t({type:"status",status:"connecting"});try{let l=await this.initSession();if(new Date>=new Date(l.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(r=this.config).onSessionExpired)==null||o.call(r);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let d=await this.buildPayload(e.messages),c=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:l.sessionId,messages:e.messages.filter(Gi).map(m=>{var y,w,T;return{id:m.id,role:m.role,content:(T=(w=(y=m.contentParts)!=null?y:m.llmContent)!=null?w:m.rawContent)!=null?T:m.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},{response:g,commit:h}=await this.sendWithClientToolsDiff(l.sessionId,d.clientTools,m=>{let y={...u,...m};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",y),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zs},body:JSON.stringify(y),signal:e.signal})});if(!g.ok){let m=await g.json().catch(()=>({error:"Chat request failed"}));if(g.status===401){this.clearClientSession(),(a=(s=this.config).onSessionExpired)==null||a.call(s);let w=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:w}),w}if(g.status===429){let w=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:w}),w}let y=new Error(m.error||"Failed to send message");throw t({type:"error",error:y}),y}if(!g.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}h(),t({type:"status",status:"connected"});try{await this.streamResponse(g.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(l){let d=l instanceof Error?l:new Error(String(l));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&t({type:"error",error:d}),d}}async dispatchProxy(e,t){t({type:"status",status:"connecting"});let r=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw t({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:a}),a}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){t({type:"status",status:"connecting"});let r=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal},r)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw t({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw t({type:"error",error:a}),a}t({type:"status",status:"connected"});try{await this.streamResponse(s.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}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$/,""))||Oa}/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 sendWithClientToolsDiff(e,t,r,o){let s=!!(t&&t.length>0),a=s?Fu(t):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,c=!s&&(o==null?void 0:o.emptyMeansReplace)===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,g;for(let h=0;;h++){if(g=await r({...s&&(u||!d)&&t?{clientTools:t}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&h===0&&s){let y=await g.clone().json().catch(()=>null);if((y==null?void 0:y.error)==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a!=null?a:null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,t,r){var c,u,g,h;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Oa}/resume`,a;o&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!0};if(a&&(d.sessionId=a),o&&a){let m=[...Ba(this.config),...(h=await((g=this.webMcpBridge)==null?void 0:g.snapshotForDispatch()))!=null?h:[]],{response:y,commit:w}=await this.sendWithClientToolsDiff(a,m,T=>{let W={...d,...T};return this.debug&&console.debug("[AgentWidgetClient] client token resume",W),fetch(s,{method:"POST",headers:l,body:JSON.stringify(W),signal:r==null?void 0:r.signal})},{emptyMeansReplace:!0});return y.ok&&w(),y}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,l,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Gi).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let g=new Date(c.createdAt).getTime(),h=new Date(u.createdAt).getTime();return g-h}).map(c=>{var u,g,h;return{role:c.role,content:(h=(g=(u=c.contentParts)!=null?u:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((l=this.webMcpBridge)==null?void 0:l.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async u=>{try{let g=await u({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,l;let t=e.slice().filter(Gi).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return u-g}).map(d=>{var c,u,g;return{role:d.role,content:(g=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Ba(this.config),...(l=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?l:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=g,o(g),g},c=u=>r.current?r.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=c(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,o(u)}return l.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),l.error&&(a.current=null,t({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,t,r,o){var yn,fr,hr,qe;let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),c=0,u=()=>d+c++,g=M=>{let ge=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Me=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,Le=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ge,toolCall:Me,tools:Le}},h=M=>{if(M.role!=="assistant"||M.variant)return!0;let ge=Array.isArray(M.contentParts)&&M.contentParts.length>0,Me=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ge||Me||!!M.stopReason},m=M=>{h(M)&&t({type:"message",message:g(M)})},y=null,w=null,T={current:null},W={current:null},E=null,H="",B=new Map,I=new Map,S=new Map,P=new Map,z=new Map,U={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},_=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ge,Me,Le,He,nt;return _((nt=(He=(Le=(Me=(ge=M.stepId)!=null?ge:M.step_id)!=null?Me:M.step)!=null?Le:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ge,Me,Le,He,nt,Xe,yt;return _((yt=(Xe=(nt=(He=(Le=(Me=(ge=M.callId)!=null?ge:M.call_id)!=null?Me:M.requestId)!=null?Le:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Xe:M.stepId)!=null?yt:M.step_id)},ke=r,pe=!1,ee=()=>{if(y)return y;let M,ge="",Me=E;return!pe&&ke?(M=ke,pe=!0,ge=o!=null?o:""):ke&&Me?M=`${ke}_${Me}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:M,role:"assistant",content:ge,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(y),y},Pe=(M,ge)=>{U.lastId=ge,M&&U.byStep.set(M,ge)},Ie=(M,ge)=>{var nt;let Me=(nt=M.reasoningId)!=null?nt:M.id,Le=O(M);if(Me){let Xe=String(Me);return Pe(Le,Xe),Xe}if(Le){let Xe=U.byStep.get(Le);if(Xe)return U.lastId=Xe,Xe}if(U.lastId&&!ge)return U.lastId;if(!ge)return null;let He=`reason-${u()}`;return Pe(Le,He),He},ie=M=>{let ge=P.get(M);if(ge)return ge;let Me={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:M,status:"streaming",chunks:[]}};return P.set(M,Me),m(Me),Me},he=(M,ge)=>{k.lastId=ge,M&&k.byCall.set(M,ge)},re=new Set,oe=new Map,de=new Set,Ae=new Map,$e=M=>{if(!M)return!1;let ge=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ge==="emit_artifact_markdown"||ge==="emit_artifact_component"},K=(M,ge)=>{var nt;let Me=(nt=M.toolId)!=null?nt:M.id,Le=Z(M);if(Me){let Xe=String(Me);return he(Le,Xe),Xe}if(Le){let Xe=k.byCall.get(Le);if(Xe)return k.lastId=Xe,Xe}if(k.lastId&&!ge)return k.lastId;if(!ge)return null;let He=`tool-${u()}`;return he(Le,He),He},J=M=>{let ge=z.get(M);if(ge)return ge;let Me={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:M,status:"pending"}};return z.set(M,Me),m(Me),Me},Se=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ge=Number(M);if(!Number.isNaN(ge)&&Number.isFinite(ge))return ge;let Me=Date.parse(M);if(!Number.isNaN(Me))return Me}return Date.now()},Y=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Te=new Map,Ye=new Map,tt=(M,ge,Me)=>{var yt;let Le=Ye.get(M);Le||(Le=[],Ye.set(M,Le));let He=0,nt=Le.length;for(;He<nt;){let fe=He+nt>>>1;Le[fe].seq<ge?He=fe+1:nt=fe}((yt=Le[He])==null?void 0:yt.seq)===ge?Le[He]={seq:ge,text:Me}:Le.splice(He,0,{seq:ge,text:Me});let Xe="";for(let fe=0;fe<Le.length;fe++)Xe+=Le[fe].text;return Xe},Wt=(M,ge)=>{let Me=Y(ge),Le=Te.get(M.id),He=Eh(Le,Me);M.rawContent=He;let nt=le.get(M.id),Xe=ce=>{var Ge;let ft=(Ge=M.content)!=null?Ge:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},yt=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Te.delete(M.id),M.streaming=!1,m(M)};if(!nt){Xe(Me),yt();return}let fe=Ys(He);if(fe!==null&&fe.trim()!==""){Xe(fe),yt();return}let D=ce=>{var Pt;let ft=typeof ce=="string"?ce:(Pt=ce==null?void 0:ce.text)!=null?Pt:null;if(ft!==null&&ft.trim()!=="")return ft;let Ge=nt.getExtractedText();return Ge!==null&&Ge.trim()!==""?Ge:Me},ve;try{ve=nt.processChunk(He)}catch{Xe(Me),yt();return}if(ve instanceof Promise){ve.then(ce=>{Xe(D(ce)),yt()}).catch(()=>{Xe(Me),yt()});return}Xe(D(ve)),yt()},ht=null,ot=(M,ge,Me,Le)=>{var fe;M.rawContent=ge,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ge.trim().startsWith("{")||ge.trim().startsWith("[");if(nt&&Te.set(M.id,ge),He.__isPlainTextParser===!0){M.content=Le!==void 0?ge:M.content+Me,Te.delete(M.id),le.delete(M.id),M.rawContent=void 0,m(M);return}let yt=He.processChunk(ge);if(yt instanceof Promise)yt.then(D=>{var ce;let ve=typeof D=="string"?D:(ce=D==null?void 0:D.text)!=null?ce:null;ve!==null&&ve.trim()!==""?(M.content=ve,m(M)):!nt&&!ge.trim().startsWith("<")&&(M.content=Le!==void 0?ge:M.content+Me,Te.delete(M.id),le.delete(M.id),M.rawContent=void 0,m(M))}).catch(()=>{M.content=Le!==void 0?ge:M.content+Me,Te.delete(M.id),le.delete(M.id),M.rawContent=void 0,m(M)});else{let D=typeof yt=="string"?yt:(fe=yt==null?void 0:yt.text)!=null?fe:null;D!==null&&D.trim()!==""?(M.content=D,m(M)):!nt&&!ge.trim().startsWith("<")&&(M.content=Le!==void 0?ge:M.content+Me,Te.delete(M.id),le.delete(M.id),M.rawContent=void 0,m(M))}},me=(M,ge)=>{var fe,D;let Me=ge!=null?ge:M.content;if(Me==null||Me===""){M.streaming=!1,m(M);return}let Le=Te.get(M.id),He=Le!=null?Le:Y(Me);M.rawContent=He;let nt=le.get(M.id),Xe=null,yt=!1;if(nt&&(Xe=nt.getExtractedText(),Xe===null&&(Xe=Ys(He)),Xe===null)){let ve=nt.processChunk(He);ve instanceof Promise?(yt=!0,ve.then(ce=>{var Ge;let ft=typeof ce=="string"?ce:(Ge=ce==null?void 0:ce.text)!=null?Ge:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Te.delete(M.id),m(M))}).catch(()=>{})):Xe=typeof ve=="string"?ve:(fe=ve==null?void 0:ve.text)!=null?fe:null}if(!yt){Xe!==null&&Xe.trim()!==""?M.content=Xe:Te.has(M.id)||(M.content=Y(Me));let ve=le.get(M.id);if(ve){let ce=(D=ve.close)==null?void 0:D.call(ve);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Te.delete(M.id),M.streaming=!1,m(M)}},X=(M,ge,Me)=>{let Le=I.get(M);if(Le)return Le;let He={id:`nested-${ge}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ge}};return I.set(M,He),m(He),He},lt=[],Ve,Ee=new Map,xe=0,Ze="agent",jt=!1,be=null,ue=null,An=new Map,At=(yn=this.config.iterationDisplay)!=null?yn:"separate";for(Ve=()=>{var M,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,Zt,yr,Wr,rr,or,Xr,Vt,sr,Hr,Bn,In,Dn,ar,br,Jr,Vn,Yr,St,vr,wr,Br,ir,bt,So,xr,To,Rn,Jo,Zr,Dr,eo,to,Eo,Mo,no,xt,Nn,Fn,Sn,Tt,Kn,Gn,On,ro,Ce,Nr,Qn,_t,Xn,Fr,Is,Yo,Rs,ko,Cr,oo,ct,nn,rn,Ar,Ws,Or,Lo,Sr,$,Zo,Jn,Tr,_r,Er,lr,es,va,bn,Tn,cr,En,Po,dr,vn,Mr,ts,Io,ns,so;for(let ao=0;ao<lt.length;ao++){let st=lt[ao].payloadType,x=lt[ao].payload;if(!jt&&Ze!=="flow"&&typeof x.stepType=="string"&&(Ze="flow"),st==="reasoning_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){B.set(V,j),X(V,j,"reasoning");continue}let Q=(M=Ie(x,!0))!=null?M:`reason-${u()}`,G=ie(Q);G.reasoning=(ge=G.reasoning)!=null?ge:{id:Q,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:Se((Me=x.startedAt)!=null?Me:x.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),G.streaming=!0,G.reasoning.status="streaming",m(G)}else if(st==="reasoning_delta"){let V=typeof x.id=="string"?x.id:null;if(V&&B.has(V)&&I.has(V)){let Ne=I.get(V),rt=(Xe=(nt=(He=x.reasoningText)!=null?He:x.text)!=null?nt:x.delta)!=null?Xe:"";rt&&x.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),m(Ne));continue}let j=(fe=(yt=Ie(x,!1))!=null?yt:Ie(x,!0))!=null?fe:`reason-${u()}`,Q=ie(j);Q.reasoning=(D=Q.reasoning)!=null?D:{id:j,status:"streaming",chunks:[]},Q.reasoning.startedAt=(ce=Q.reasoning.startedAt)!=null?ce:Se((ve=x.startedAt)!=null?ve:x.timestamp);let G=(Pt=(Ge=(ft=x.reasoningText)!=null?ft:x.text)!=null?Ge:x.delta)!=null?Pt:"";if(G&&x.hidden!==!0){let Ne=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Ne!==void 0){let rt=tt(j,Ne,String(G));Q.reasoning.chunks=[rt]}else Q.reasoning.chunks.push(String(G))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=Se((kt=x.completedAt)!=null?kt:x.timestamp);let Ne=(wt=Q.reasoning.startedAt)!=null?wt:Date.now();Q.reasoning.durationMs=Math.max(0,((Ht=Q.reasoning.completedAt)!=null?Ht:Date.now())-Ne)}Q.streaming=Q.reasoning.status!=="complete",m(Q)}else if(st==="reasoning_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&B.has(V)&&I.has(V)){let rt=I.get(V);if(rt.reasoning){let dt=typeof x.text=="string"?x.text:"";dt&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(dt),rt.reasoning.status="complete",rt.streaming=!1,m(rt)}B.delete(V),I.delete(V);continue}let j=(Ot=(Xt=Ie(x,!1))!=null?Xt:Ie(x,!0))!=null?Ot:`reason-${u()}`,Q=typeof x.text=="string"?x.text:"";!P.get(j)&&(Q||x.scope==="loop")&&ie(j);let G=P.get(j);if(G!=null&&G.reasoning){(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),Q&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(Q),G.reasoning.status="complete",G.reasoning.completedAt=Se((Zt=x.completedAt)!=null?Zt:x.timestamp);let rt=(yr=G.reasoning.startedAt)!=null?yr:Date.now();G.reasoning.durationMs=Math.max(0,((Wr=G.reasoning.completedAt)!=null?Wr:Date.now())-rt),G.streaming=!1,m(G)}let Ne=O(x);Ne&&U.byStep.delete(Ne)}else if(st==="tool_start"){y&&(y.streaming=!1,m(y),y=null),typeof x.iteration=="number"&&(xe=x.iteration);let V=(or=(rr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?rr:K(x,!0))!=null?or:`tool-${u()}`,j=(Xr=x.toolName)!=null?Xr:x.name;if($e(j)){re.add(V);continue}he(Z(x),V);let Q=J(V),G=(Vt=Q.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=j!=null?j:G.name,G.status="running",x.parameters!==void 0?G.args=x.parameters:x.args!==void 0&&(G.args=x.args),G.startedAt=(Hr=G.startedAt)!=null?Hr:Se((sr=x.startedAt)!=null?sr:x.timestamp),G.completedAt=void 0,G.durationMs=void 0,Q.toolCall=G,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(Q)}else if(st==="tool_output_delta"){let V=(In=(Bn=K(x,!1))!=null?Bn:K(x,!0))!=null?In:`tool-${u()}`;if(re.has(V))continue;let j=J(V),Q=(Dn=j.toolCall)!=null?Dn:{id:V,status:"running"};Q.startedAt=(br=Q.startedAt)!=null?br:Se((ar=x.startedAt)!=null?ar:x.timestamp);let G=(Yr=(Vn=(Jr=x.text)!=null?Jr:x.delta)!=null?Vn:x.message)!=null?Yr:"";G&&(Q.chunks=(St=Q.chunks)!=null?St:[],Q.chunks.push(String(G))),Q.status="running",j.toolCall=Q,j.streaming=!0;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Br=j.agentMetadata)!=null?Br:{executionId:(vr=Ne==null?void 0:Ne.executionId)!=null?vr:x.executionId,iteration:(wr=Ne==null?void 0:Ne.iteration)!=null?wr:x.iteration}),m(j)}else if(st==="tool_complete"){let V=(bt=(ir=K(x,!1))!=null?ir:K(x,!0))!=null?bt:`tool-${u()}`;if(re.has(V)){re.delete(V);continue}let j=J(V),Q=(So=j.toolCall)!=null?So:{id:V,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=Se((xr=x.completedAt)!=null?xr:x.timestamp);let G=(To=x.duration)!=null?To:x.executionTime;if(typeof G=="number")Q.durationMs=G;else{let dt=(Rn=Q.startedAt)!=null?Rn:Date.now();Q.durationMs=Math.max(0,((Jo=Q.completedAt)!=null?Jo:Date.now())-dt)}j.toolCall=Q,j.streaming=!1;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(eo=j.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:x.executionId,iteration:(Dr=Ne==null?void 0:Ne.iteration)!=null?Dr:x.iteration}),m(j);let rt=Z(x);rt&&k.byCall.delete(rt)}else if(st==="await"&&x.toolName){let V=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,j=(to=V!=null?V:x.toolId)!=null?to:`local-${u()}`,Q=J(j),G=x.toolName,Ne=x.origin==="webmcp"&&!us(G)?`webmcp:${G}`:G,rt=us(Ne),dt=(Eo=Q.toolCall)!=null?Eo:{id:j,status:"pending"};dt.name=Ne,dt.args=x.parameters,dt.status=rt?"running":"complete",dt.chunks=(Mo=dt.chunks)!=null?Mo:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:Se((xt=(no=x.startedAt)!=null?no:x.timestamp)!=null?xt:x.awaitedAt),rt?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(Fn=dt.completedAt)!=null?Fn:dt.startedAt,Q.toolCall=dt,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tt=x.executionId)!=null?Tt:(Sn=Q.agentMetadata)==null?void 0:Sn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},m(Q)}else if(st==="text_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){B.set(V,j);continue}let Q=y;Q&&(Ze==="flow"?(me(Q),ht=Q):(Q.streaming=!1,m(Q)),y=null),E=typeof x.id=="string"?x.id:E,H=""}else if(st==="text_delta"){let V=typeof x.id=="string"?x.id:null,j=V?B.get(V):void 0;if(V&&j){let G=typeof x.delta=="string"?x.delta:"",Ne=((Kn=S.get(V))!=null?Kn:"")+G;if(S.set(V,Ne),Ne.trim()==="")continue;let rt=X(V,j);rt.agentMetadata={...rt.agentMetadata,executionId:x.executionId,parentToolId:j},ot(rt,Ne,G,void 0);continue}if(E=typeof x.id=="string"?x.id:E,Ze==="flow"){let G=typeof x.delta=="string"?x.delta:"";if(H+=G,H.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:x.executionId,iteration:x.iteration},ot(Ne,H,G,void 0),w=Ne;continue}let Q=ee();Q.content+=(Gn=x.delta)!=null?Gn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:be!=null?be:void 0,agentName:ue==null?void 0:ue.agentName},w=Q,m(Q)}else if(st==="text_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&B.has(V)){let Q=I.get(V);Q&&me(Q),B.delete(V),S.delete(V),I.delete(V);continue}let j=y;j&&(Ze==="flow"?(me(j),ht=j):(((On=j.content)!=null?On:"")===""&&typeof x.text=="string"&&(j.content=x.text),j.streaming=!1,m(j)),y=null),E=null,H=""}else if(st==="step_complete"){let V=x.stepType,j=x.executionType;if(V==="tool"||j==="context")continue;if(x.success===!1){let Q=x.error,G=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&Reflect.has(Q,"message")?String((ro=Q.message)!=null?ro:"Step failed"):"Step failed";t({type:"error",error:new Error(G)});let Ne=y;Ne&&Ne.streaming&&(Ne.streaming=!1,m(Ne)),t({type:"status",status:"idle"});continue}{let Q=ht;ht=null;let G=x.stopReason,Ne=(Ce=x.result)==null?void 0:Ce.response;if(Q)G&&(Q.stopReason=G),Ne!=null?Wt(Q,Ne):Q.streaming!==!1&&(le.delete(Q.id),Te.delete(Q.id),Q.streaming=!1,m(Q));else{let rt=Ne!=null&&Ne!=="";if(rt||G){let dt=ee();G&&(dt.stopReason=G),rt?me(dt,Ne):(dt.streaming=!1,m(dt))}}continue}}else if(st==="execution_start")Ze=x.kind==="flow"?"flow":"agent",jt=!0,Ze==="agent"&&(ue={executionId:x.executionId,agentId:(Nr=x.agentId)!=null?Nr:"virtual",agentName:(Qn=x.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=x.maxTurns)!=null?_t:1,startedAt:Se(x.startedAt)});else if(st==="turn_start"){let V=typeof x.iteration=="number"?x.iteration:xe;if(V!==xe){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let j=y;j&&(j.streaming=!1,m(j),An.set(V-1,j),y=null)}xe=V}be=typeof x.id=="string"?x.id:null,w=null}else if(st==="tool_input_delta"){let V=(Xn=x.toolCallId)!=null?Xn:k.lastId;if(V){let j=z.get(V);j!=null&&j.toolCall&&(j.toolCall.chunks=(Fr=j.toolCall.chunks)!=null?Fr:[],j.toolCall.chunks.push((Is=x.delta)!=null?Is:""),m(j))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=x.stopReason,j=y!=null?y:w;if(V&&j!==null){let Q=x.id;(!Q||((Yo=j.agentMetadata)==null?void 0:Yo.turnId)===Q)&&(j.stopReason=V,m(j))}be===x.id&&(be=null)}else if(st==="media_start"){let V=String(x.id);Ee.set(V,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Ee.get(String(x.id));V&&typeof x.delta=="string"&&V.parts.push(x.delta)}else if(st==="media_complete"){let V=String(x.id),j=Ee.get(V);Ee.delete(V);let Q=(ko=(Rs=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Rs:j==null?void 0:j.mediaType)!=null?ko:"application/octet-stream",G=typeof x.data=="string"?x.data:void 0,Ne=typeof x.url=="string"?x.url:j&&j.parts.length>0?j.parts.join(""):void 0,rt=null;if(G)rt={type:"media",data:G,mediaType:Q};else if(Ne){let Mn=Q.toLowerCase();rt={type:Mn==="image"||Mn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:Q}}let dt=(Cr=x.toolCallId)!=null?Cr:j==null?void 0:j.toolCallId,xi=rt?[rt]:[],io=[];for(let Mn of xi){if(!Mn||typeof Mn!="object")continue;let dn=Mn,$r=typeof dn.type=="string"?dn.type:void 0,kr=typeof dn.mediaType=="string"?dn.mediaType.toLowerCase():"",on=null,kn="";if($r==="media"){let mn=typeof dn.data=="string"?dn.data:void 0;if(!mn)continue;kn=kr.length>0?kr:"application/octet-stream",on=`data:${kn};base64,${mn}`}else if($r==="image-url"){let mn=typeof dn.url=="string"?dn.url:void 0;if(!mn)continue;kn=kr,on=mn}else if($r==="file-url"){let mn=typeof dn.url=="string"?dn.url:void 0;if(!mn)continue;kn=kr,on=mn}else continue;if(on)if($r==="image-url"||kn.startsWith("image/"))io.push({type:"image",image:on,...kn.includes("/")?{mimeType:kn}:{}});else if(kn.startsWith("audio/"))io.push({type:"audio",audio:on,mimeType:kn});else if(kn.startsWith("video/"))io.push({type:"video",video:on,mimeType:kn});else{let mn=kn||"application/octet-stream";io.push({type:"file",data:on,mimeType:mn,filename:Sh(mn)})}}if(io.length>0){let Mn=u(),dn=dt,kr={id:`agent-media-${typeof dn=="string"&&dn.length>0?`${dn}-${Mn}`:String(Mn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Mn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:xe}};m(kr);let on=y;on&&(on.streaming=!1,m(on)),y=null,T.current=null}}else if(st==="execution_complete"){let V=(oo=x.kind)!=null?oo:Ze;V==="agent"&&ue&&(ue.status=x.success?"complete":"error",ue.completedAt=Se(x.completedAt),ue.stopReason=x.stopReason);let j=y;j&&(V==="flow"&&j.streaming!==!1?me(j):(j.streaming=!1,m(j)),y=null),E=null,H="",ht=null,t({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof x.error=="string"?x.error:(nn=(ct=x.error)==null?void 0:ct.message)!=null?nn:"Execution error";t({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(rn=x.approvalId)!=null?rn:`approval-${u()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:V,status:"pending",agentId:(Ar=ue==null?void 0:ue.agentId)!=null?Ar:"virtual",executionId:(Or=(Ws=x.executionId)!=null?Ws:ue==null?void 0:ue.executionId)!=null?Or:"",toolName:(Lo=x.toolName)!=null?Lo:"",toolType:x.toolType,description:($=x.description)!=null?$:`Execute ${(Sr=x.toolName)!=null?Sr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="step_await"&&x.awaitReason==="approval_required"){let V=(Zo=x.approvalId)!=null?Zo:`approval-${u()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:V,status:"pending",agentId:(Jn=ue==null?void 0:ue.agentId)!=null?Jn:"virtual",executionId:(_r=(Tr=x.executionId)!=null?Tr:ue==null?void 0:ue.executionId)!=null?_r:"",toolName:(Er=x.toolName)!=null?Er:"",toolType:x.toolType,description:(es=x.description)!=null?es:`Execute ${(lr=x.toolName)!=null?lr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="approval_complete"){let V=x.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:V,status:(va=x.decision)!=null?va:"approved",agentId:(bn=ue==null?void 0:ue.agentId)!=null?bn:"virtual",executionId:(cr=(Tn=x.executionId)!=null?Tn:ue==null?void 0:ue.executionId)!=null?cr:"",toolName:(En=x.toolName)!=null?En:"",description:(Po=x.description)!=null?Po:"",resolvedAt:Date.now()}};m(Q)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=x.artifactType,j=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:j,artifactType:V,title:Q,component:typeof x.component=="string"?x.component:void 0}),Ae.set(j,{markdown:"",title:Q}),!de.has(j)){de.add(j);let G={id:`artifact-ref-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:j,title:Q,artifactType:V,status:"streaming"}})};oe.set(j,G),m(G)}}else if(st==="artifact_delta"){let V=String(x.id),j=typeof x.delta=="string"?x.delta:String((dr=x.delta)!=null?dr:"");t({type:"artifact_delta",id:V,artDelta:j});let Q=Ae.get(V);Q&&(Q.markdown+=j)}else if(st==="artifact_update"){let V=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:V,component:typeof x.component=="string"?x.component:void 0})}else if(st==="artifact_complete"){let V=String(x.id);t({type:"artifact_complete",id:V});let j=oe.get(V);if(j){j.streaming=!1;try{let Q=JSON.parse((vn=j.rawContent)!=null?vn:"{}");if(Q.props){Q.props.status="complete";let G=Ae.get(V);G!=null&&G.markdown&&(Q.props.markdown=G.markdown)}j.rawContent=JSON.stringify(Q)}catch{}Ae.delete(V),m(j),oe.delete(V)}}}else if(st==="transcript_insert"){let V=x.message;if(!V||typeof V!="object")continue;let j=String((Mr=V.id)!=null?Mr:`msg-${u()}`),Q=V.role,Ne={id:j,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:u()};if(m(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),dt=(ts=rt==null?void 0:rt.props)==null?void 0:ts.artifactId;typeof dt=="string"&&de.add(dt)}catch{}y=null,T.current=null,le.delete(j),Te.delete(j)}else if(st==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let V=typeof x.error=="string"?x.error:((Io=x.error)==null?void 0:Io.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(V)});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(x.error instanceof Error)V=x.error;else if(st==="dispatch_error"){let j=(ns=x.message)!=null?ns:x.error;j!=null&&j!==""&&(V=new Error(String(j)))}else{let j=x.error;typeof j=="string"&&j!==""?V=new Error(j):j!=null&&typeof j=="object"&&Reflect.has(j,"message")&&(V=new Error(String((so=j.message)!=null?so:j)))}if(V){t({type:"error",error:V});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:M,value:ge}=await s.read();if(M)break;l+=a.decode(ge,{stream:!0});let Me=l.split(`
8
+ ${t.description}`:"");return window.confirm(n)},Vf=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Kf=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Gf=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Lo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function sa(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Xf="agent_",Qf="flow_";function ud(t){return t.startsWith(Xf)?{kind:"agentId",agentId:t}:t.startsWith(Qf)?{kind:"flowId",flowId:t}:null}function fd(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let d=ud(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=ud(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Zn=require("partial-json");var m=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Tn=(t,e,n)=>{let o=t.createElement(e);return n&&(o.className=n),o},gd=()=>document.createDocumentFragment(),ot=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let p=a[l];p!=null&&(s[l]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Po=(...t)=>t.filter(Boolean).join(" ");var Di="ask_user_question",Kr=8,tr="data-persona-ask-sheet-for",Jf="Other",Yf="Other\u2026",hd="Type your own answer here",yd="Send",Zf="Next",eg="Back",tg="Submit all",ng="Skip",og=3,Fi="data-ask-current-index",Ni="data-ask-question-count",bd="data-ask-answers",Oi="data-ask-grouped",vd="data-ask-layout",rg=t=>t.layout==="pills"?"pills":"rows",sg=t=>t.getAttribute(vd)==="pills"?"pills":"rows",md=!1,wd=t=>t.replace(/["\\]/g,"\\$&"),Io=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Di,_i=t=>t?.features?.askUserQuestion??{},nr=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,Zn.parse)(r,Zn.STR|Zn.OBJ|Zn.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Kr&&!md&&(md=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Kr}.`)),e.slice(0,Kr)},ag=t=>Gr(t)[0]??null,ig=(t,e)=>Gr(t)[e]??null,lg=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},xd=(t,e,n)=>{if(t!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},cg=(t,e,n,o)=>{let s=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=m("span","persona-ask-row-content"),l=m("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let d=m("span","persona-ask-row-description");d.textContent=t.description,a.appendChild(d)}s.appendChild(a);let p=xd(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},dg=t=>{let n=m("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},pg=(t,e,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<og;c++)s.appendChild(dg(o));return s}if(p.forEach((c,u)=>{s.appendChild(cg(c,u,o,a))}),t?.allowFreeText!==!1){let c=o==="rows"?Jf:Yf;if(o==="rows"){let u=m("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let w=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??hd,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??c),w.appendChild(f),u.appendChild(w);let b=xd(o,a,p.length);b&&u.appendChild(b),s.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??c,s.appendChild(u)}}return s},Cd=(t,e)=>{let o=m("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");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??hd,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??yd,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},ug=t=>{let e=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??yd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},fg=(t,e,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??eg,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??ng,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=m("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??tg:n.nextLabel??Zf,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Ro=t=>{let e=t.getAttribute(bd);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Ad=(t,e)=>{t.setAttribute(bd,JSON.stringify(e))},un=t=>{let e=Number(t.getAttribute(Fi)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},gg=(t,e)=>{t.setAttribute(Fi,String(Math.max(0,Math.floor(e))))},or=t=>{let e=Number(t.getAttribute(Ni)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},eo=t=>t.getAttribute(Oi)==="true",mg=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},hg=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},aa=(t,e)=>{let{payload:n}=nr(e),o=Gr(n),r=Ro(t),s={},a=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Sd=t=>{let e=Ro(t),n=un(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Td=t=>{if(!eo(t))return;let e=Ro(t),n=un(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},$i=(t,e,n)=>{let o=_i(n),r=sg(t),{payload:s,complete:a}=nr(e),l=eo(t),p=un(t),d=or(t),c=l?ig(s,p):ag(s),u=!!c?.multiSelect,w=t.querySelector('[data-ask-step-inline="true"]');w&&(w.textContent=l?`${p+1}/${d}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let b=t.querySelector('[data-ask-question="true"]');if(b){let M=typeof c?.question=="string"?c.question:"";b.textContent=M,b.classList.toggle("persona-ask-question-skeleton",!M&&!a)}let x=t.querySelector('[data-ask-pill-list="true"]');if(x){let M=pg(c,o,a,r);x.replaceWith(M)}if(r!=="rows"){let M=t.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(Cd(o,r))}let P=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!P?t.appendChild(ug(o)):(!u||l)&&P&&P.remove(),t.setAttribute("data-multi-select",u?"true":"false");let W=t.querySelector('[data-ask-nav-row="true"]');if(l){let M=fg(p,d,o);W?W.replaceWith(M):t.appendChild(M)}else W&&W.remove();Sd(t),Td(t)},yg=(t,e,n)=>{let o=_i(e),r=rg(o),s=t.toolCall.id,a=Gr(n),l=Math.max(1,a.length),p=l>1,d=mg(t,a),c=p?hg(t,l):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(tr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(Ni,String(l)),u.setAttribute(Fi,String(c)),u.setAttribute(Oi,p?"true":"false"),u.setAttribute(vd,r),Ad(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),lg(u,o);let w=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=m("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",w.appendChild(f);let b=m("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",w.appendChild(b),u.appendChild(w);let P=m("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return P.setAttribute("data-ask-pill-list","true"),P.setAttribute("role","group"),u.appendChild(P),r!=="rows"&&u.appendChild(Cd(o,r)),$i(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},bg=(t,e,n)=>{let{payload:o}=nr(e),r=Math.max(1,Gr(o).length);r>or(t)&&(t.setAttribute(Ni,String(r)),r>1&&!eo(t)&&t.setAttribute(Oi,"true")),$i(t,e,n)};var ia=(t,e,n)=>{if(!n||!Io(t)||_i(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${tr}]`).forEach(d=>{d.getAttribute(tr)!==r&&d.remove()});let a=n.querySelector(`[${tr}="${wd(r)}"]`);if(a){bg(a,t,e);return}let{payload:l}=nr(t),p=yg(t,e,l);n.appendChild(p)},rr=(t,e)=>{if(!t)return;let n=e?`[${tr}="${wd(e)}"]`:`[${tr}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},Ui=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),to=(t,e)=>{let n=Ro(t),o=un(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Ad(t,n),Sd(t),Td(t)},la=(t,e,n,o)=>{let r=or(t),s=Math.max(0,Math.min(r-1,o));gg(t,s),$i(t,e,n)};var Dn="suggest_replies";var vg={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},Md={name:Dn,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:vg,origin:"sdk",annotations:{readOnlyHint:!0}},zi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ji=t=>t.variant==="tool"&&t.toolCall?.name===Dn,wg=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ed=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ji(n))continue;let o=wg(n.toolCall?.args);return o.length>0?o:null}return null},kd=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var xg={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Kr,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},Cg={name:Di,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:xg,origin:"sdk",annotations:{readOnlyHint:!0}},ca=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(Cg),kd(t)&&e.push(Md),e};var sr=require("partial-json"),Ld=t=>t.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),no=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Ag=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Pd=t=>t.status==="complete"?Ag(t):t.status==="pending"?"Waiting":"",Sg=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Id=t=>t.status==="complete"?Sg(t):"Using tool...",da=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Qr=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return da(e)},pa=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return da(e)},qi=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Qr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ua=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&Xr(o,n.slice(s,a.index),[]),a[1]!==void 0?Xr(o,a[1],["bold"]):a[2]!==void 0?Xr(o,a[2],["italic"]):a[3]!==void 0&&Xr(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Xr(o,n.slice(s),[]),o},Xr=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Tg=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Jr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Rd=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Wd=()=>{let t=Tg();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Bd=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,sr.parse)(n,sr.STR|sr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Ld(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Ld(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Hd=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Dd="4.8.0";var Yr=Dd;var Eg="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com";function kg(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Vi=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Lg(t){switch(t){case"json":return Bd;case"regex-json":return Wd;case"xml":return Hd;default:return Rd}}var Fd=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Pg(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=Fd(n);if(!Fd(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=Jr(t);return Jr(e)!==null&&a===null?e:t}var Zr=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??Eg,this.headers={"Content-Type":"application/json","X-Persona-Version":Yr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??Lg(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new ra(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=fd(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||fa}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||fa}/v1/client/feedback`}async sendFeedback(e){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 r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:e.messages.filter(Vi).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Yr},body:JSON.stringify(c),signal:e.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||fa}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?dd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,c=!1,u;for(let w=0;;w++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&w===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||fa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,w=>{let f={...p,...w};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(Vi).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,l)=>{let p=new Date(a.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(a=>({role:a.role,content:a.contentParts??a.llmContent??a.rawContent??a.content,createdAt:a.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(a,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(a).length&&(r.context=a)}return r}async buildPayload(e){let n=e.slice().filter(Vi).sort((a,l)=>{let p=new Date(a.createdAt).getTime(),d=new Date(l.createdAt).getTime();return p-d}).map(a=>({role:a.role,content:a.contentParts??a.llmContent??a.rawContent??a.content,createdAt:a.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[a,l]of Object.entries(o.targetPayload))a!=="messages"&&(r[a]=l);let s=[...ca(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(a,p)}catch(p){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(a).length&&(r.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...r},config:this.config});if(a&&typeof a=="object"){let l=a;return r.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=r.clientTools),l}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",a)}return r}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=c=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(a.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,u=E=>{let Q=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,y=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,S=E.tools?E.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...E,reasoning:Q,toolCall:y,tools:S}},w=E=>{if(E.role!=="assistant"||E.variant)return!0;let Q=Array.isArray(E.contentParts)&&E.contentParts.length>0,y=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||Q||y||!!E.stopReason},f=E=>{w(E)&&n({type:"message",message:u(E)})},b=null,x=null,P={current:null},W={current:null},M=null,R="",D=new Map,$=new Map,j=new Map,z=new Map,C=new Map,V={lastId:null,byStep:new Map},Y={lastId:null,byCall:new Map},F=E=>{if(E==null)return null;try{return String(E)}catch{return null}},U=E=>F(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),de=E=>F(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),ye=o,Ee=!1,Ae=()=>{if(b)return b;let E,Q="",y=M;return!Ee&&ye?(E=ye,Ee=!0,Q=r??""):ye&&y?E=`${ye}_${y}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:E,role:"assistant",content:Q,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(b),b},ne=(E,Q)=>{V.lastId=Q,E&&V.byStep.set(E,Q)},me=(E,Q)=>{let y=E.reasoningId??E.id,S=U(E);if(y){let B=String(y);return ne(S,B),B}if(S){let B=V.byStep.get(S);if(B)return V.lastId=B,B}if(V.lastId&&!Q)return V.lastId;if(!Q)return null;let k=`reason-${c()}`;return ne(S,k),k},Z=E=>{let Q=z.get(E);if(Q)return Q;let y={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return z.set(E,y),f(y),y},ce=(E,Q)=>{Y.lastId=Q,E&&Y.byCall.set(E,Q)},ee=new Set,ve=new Map,we=new Set,ge=new Map,Me=E=>{if(!E)return!1;let Q=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return Q==="emit_artifact_markdown"||Q==="emit_artifact_component"},Se=(E,Q)=>{let y=E.toolId??E.id,S=de(E);if(y){let B=String(y);return ce(S,B),B}if(S){let B=Y.byCall.get(S);if(B)return Y.lastId=B,B}if(Y.lastId&&!Q)return Y.lastId;if(!Q)return null;let k=`tool-${c()}`;return ce(S,k),k},je=E=>{let Q=C.get(E);if(Q)return Q;let y={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return C.set(E,y),f(y),y},Ne=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let Q=Number(E);if(!Number.isNaN(Q)&&Number.isFinite(Q))return Q;let y=Date.parse(E);if(!Number.isNaN(y))return y}return Date.now()},Ie=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Be=new Map,it=new Map,_e=new Map,Qe=(E,Q,y)=>{let S=_e.get(E);S||(S=[],_e.set(E,S));let k=0,B=S.length;for(;k<B;){let H=k+B>>>1;S[H].seq<Q?k=H+1:B=H}S[k]?.seq===Q?S[k]={seq:Q,text:y}:S.splice(k,0,{seq:Q,text:y});let G="";for(let H=0;H<S.length;H++)G+=S[H].text;return G},an=(E,Q)=>{let y=Ie(Q),S=it.get(E.id),k=Pg(S,y);E.rawContent=k;let B=Be.get(E.id),G=We=>{let ct=E.content??"";We.trim()!==""&&(ct.trim().length===0||We.startsWith(ct)||We.trimStart().startsWith(ct.trim()))&&(E.content=We)},H=()=>{if(B){let We=B.close?.();We instanceof Promise&&We.catch(()=>{})}Be.delete(E.id),it.delete(E.id),E.streaming=!1,f(E)};if(!B){G(y),H();return}let q=Jr(k);if(q!==null&&q.trim()!==""){G(q),H();return}let se=We=>{let ct=typeof We=="string"?We:We?.text??null;if(ct!==null&&ct.trim()!=="")return ct;let K=B.getExtractedText();return K!==null&&K.trim()!==""?K:y},tt;try{tt=B.processChunk(k)}catch{G(y),H();return}if(tt instanceof Promise){tt.then(We=>{G(se(We)),H()}).catch(()=>{G(y),H()});return}G(se(tt)),H()},kt=null,gt=(E,Q,y,S)=>{E.rawContent=Q,Be.has(E.id)||Be.set(E.id,this.createStreamParser());let k=Be.get(E.id),B=Q.trim().startsWith("{")||Q.trim().startsWith("[");if(B&&it.set(E.id,Q),k.__isPlainTextParser===!0){E.content=S!==void 0?Q:E.content+y,it.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E);return}let H=k.processChunk(Q);if(H instanceof Promise)H.then(q=>{let se=typeof q=="string"?q:q?.text??null;se!==null&&se.trim()!==""?(E.content=se,f(E)):!B&&!Q.trim().startsWith("<")&&(E.content=S!==void 0?Q:E.content+y,it.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=S!==void 0?Q:E.content+y,it.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E)});else{let q=typeof H=="string"?H:H?.text??null;q!==null&&q.trim()!==""?(E.content=q,f(E)):!B&&!Q.trim().startsWith("<")&&(E.content=S!==void 0?Q:E.content+y,it.delete(E.id),Be.delete(E.id),E.rawContent=void 0,f(E))}},ke=(E,Q)=>{let y=Q??E.content;if(y==null||y===""){E.streaming=!1,f(E);return}let k=it.get(E.id)??Ie(y);E.rawContent=k;let B=Be.get(E.id),G=null,H=!1;if(B&&(G=B.getExtractedText(),G===null&&(G=Jr(k)),G===null)){let q=B.processChunk(k);q instanceof Promise?(H=!0,q.then(se=>{let tt=typeof se=="string"?se:se?.text??null;tt!==null&&(E.content=tt,E.streaming=!1,Be.delete(E.id),it.delete(E.id),f(E))}).catch(()=>{})):G=typeof q=="string"?q:q?.text??null}if(!H){G!==null&&G.trim()!==""?E.content=G:it.has(E.id)||(E.content=Ie(y));let q=Be.get(E.id);if(q){let se=q.close?.();se instanceof Promise&&se.catch(()=>{}),Be.delete(E.id)}it.delete(E.id),E.streaming=!1,f(E)}},he=(E,Q,y)=>{let S=$.get(E);if(S)return S;let k={id:`nested-${Q}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Q}};return $.set(E,k),f(k),k},lt=[],Re,fe=new Map,le=0,be="agent",vt=!1,N=null,oe=null,Fe=new Map,Le=this.config.iterationDisplay??"separate";for(Re=()=>{for(let E=0;E<lt.length;E++){let Q=lt[E].payloadType,y=lt[E].payload;if(!vt&&be!=="flow"&&typeof y.stepType=="string"&&(be="flow"),Q==="reasoning_start"){let S=typeof y.id=="string"?y.id:null,k=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(S&&k){D.set(S,k),he(S,k,"reasoning");continue}let B=me(y,!0)??`reason-${c()}`,G=Z(B);G.reasoning=G.reasoning??{id:B,status:"streaming",chunks:[]},G.reasoning.startedAt=G.reasoning.startedAt??Ne(y.startedAt??y.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(G.reasoning.scope=y.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(Q==="reasoning_delta"){let S=typeof y.id=="string"?y.id:null;if(S&&D.has(S)&&$.has(S)){let H=$.get(S),q=y.reasoningText??y.text??y.delta??"";q&&y.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(q)),f(H));continue}let k=me(y,!1)??me(y,!0)??`reason-${c()}`,B=Z(k);B.reasoning=B.reasoning??{id:k,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??Ne(y.startedAt??y.timestamp);let G=y.reasoningText??y.text??y.delta??"";if(G&&y.hidden!==!0){let H=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(H!==void 0){let q=Qe(k,H,String(G));B.reasoning.chunks=[q]}else B.reasoning.chunks.push(String(G))}if(B.reasoning.status=y.done?"complete":"streaming",y.done){B.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let H=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-H)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(Q==="reasoning_complete"){let S=typeof y.id=="string"?y.id:null;if(S&&D.has(S)&&$.has(S)){let q=$.get(S);if(q.reasoning){let se=typeof y.text=="string"?y.text:"";se&&q.reasoning.chunks.length===0&&q.reasoning.chunks.push(se),q.reasoning.status="complete",q.streaming=!1,f(q)}D.delete(S),$.delete(S);continue}let k=me(y,!1)??me(y,!0)??`reason-${c()}`,B=typeof y.text=="string"?y.text:"";!z.get(k)&&(B||y.scope==="loop")&&Z(k);let G=z.get(k);if(G?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(G.reasoning.scope=y.scope),B&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(B),G.reasoning.status="complete",G.reasoning.completedAt=Ne(y.completedAt??y.timestamp);let q=G.reasoning.startedAt??Date.now();G.reasoning.durationMs=Math.max(0,(G.reasoning.completedAt??Date.now())-q),G.streaming=!1,f(G)}let H=U(y);H&&V.byStep.delete(H)}else if(Q==="tool_start"){b&&(b.streaming=!1,f(b),b=null),typeof y.iteration=="number"&&(le=y.iteration);let S=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??Se(y,!0)??`tool-${c()}`,k=y.toolName??y.name;if(Me(k)){ee.add(S);continue}ce(de(y),S);let B=je(S),G=B.toolCall??{id:S,status:"pending"};G.name=k??G.name,G.status="running",y.parameters!==void 0?G.args=y.parameters:y.args!==void 0&&(G.args=y.args),G.startedAt=G.startedAt??Ne(y.startedAt??y.timestamp),G.completedAt=void 0,G.durationMs=void 0,B.toolCall=G,B.streaming=!0,y.executionId&&(B.agentMetadata={executionId:y.executionId,iteration:y.iteration}),f(B)}else if(Q==="tool_output_delta"){let S=Se(y,!1)??Se(y,!0)??`tool-${c()}`;if(ee.has(S))continue;let k=je(S),B=k.toolCall??{id:S,status:"running"};B.startedAt=B.startedAt??Ne(y.startedAt??y.timestamp);let G=y.text??y.delta??y.message??"";G&&(B.chunks=B.chunks??[],B.chunks.push(String(G))),B.status="running",k.toolCall=B,k.streaming=!0;let H=y.agentContext;(H||y.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(k)}else if(Q==="tool_complete"){let S=Se(y,!1)??Se(y,!0)??`tool-${c()}`;if(ee.has(S)){ee.delete(S);continue}let k=je(S),B=k.toolCall??{id:S,status:"running"};B.status="complete",y.result!==void 0&&(B.result=y.result),typeof y.duration=="number"&&(B.duration=y.duration),B.completedAt=Ne(y.completedAt??y.timestamp);let G=y.duration??y.executionTime;if(typeof G=="number")B.durationMs=G;else{let se=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-se)}k.toolCall=B,k.streaming=!1;let H=y.agentContext;(H||y.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:H?.executionId??y.executionId,iteration:H?.iteration??y.iteration}),f(k);let q=de(y);q&&Y.byCall.delete(q)}else if(Q==="await"&&y.toolName){let S=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,k=S??y.toolId??`local-${c()}`,B=je(k),G=y.toolName,H=y.origin==="webmcp"&&!er(G)?`webmcp:${G}`:G,q=er(H),se=B.toolCall??{id:k,status:"pending"};se.name=H,se.args=y.parameters,se.status=q?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Ne(y.startedAt??y.timestamp??y.awaitedAt),q?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,B.toolCall=se,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:y.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(B)}else if(Q==="text_start"){let S=typeof y.id=="string"?y.id:null,k=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(S&&k){D.set(S,k);continue}let B=b;B&&(be==="flow"?(ke(B),kt=B):(B.streaming=!1,f(B)),b=null),M=typeof y.id=="string"?y.id:M,R=""}else if(Q==="text_delta"){let S=typeof y.id=="string"?y.id:null,k=S?D.get(S):void 0;if(S&&k){let G=typeof y.delta=="string"?y.delta:"",H=(j.get(S)??"")+G;if(j.set(S,H),H.trim()==="")continue;let q=he(S,k);q.agentMetadata={...q.agentMetadata,executionId:y.executionId,parentToolId:k},gt(q,H,G,void 0);continue}if(M=typeof y.id=="string"?y.id:M,be==="flow"){let G=typeof y.delta=="string"?y.delta:"";if(R+=G,R.trim()==="")continue;let H=Ae();H.agentMetadata={executionId:y.executionId,iteration:y.iteration},gt(H,R,G,void 0),x=H;continue}let B=Ae();B.content+=y.delta??"",B.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:N??void 0,agentName:oe?.agentName},x=B,f(B)}else if(Q==="text_complete"){let S=typeof y.id=="string"?y.id:null;if(S&&D.has(S)){let B=$.get(S);B&&ke(B),D.delete(S),j.delete(S),$.delete(S);continue}let k=b;k&&(be==="flow"?(ke(k),kt=k):((k.content??"")===""&&typeof y.text=="string"&&(k.content=y.text),k.streaming=!1,f(k)),b=null),M=null,R=""}else if(Q==="step_complete"){let S=y.stepType,k=y.executionType;if(S==="tool"||k==="context")continue;if(y.success===!1){let B=y.error,G=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let H=b;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let B=kt;kt=null;let G=y.stopReason,H=y.result?.response;if(B)G&&(B.stopReason=G),H!=null?an(B,H):B.streaming!==!1&&(Be.delete(B.id),it.delete(B.id),B.streaming=!1,f(B));else{let q=H!=null&&H!=="";if(q||G){let se=Ae();G&&(se.stopReason=G),q?ke(se,H):(se.streaming=!1,f(se))}}continue}}else if(Q==="execution_start")be=y.kind==="flow"?"flow":"agent",vt=!0,be==="agent"&&(oe={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Ne(y.startedAt)});else if(Q==="turn_start"){let S=typeof y.iteration=="number"?y.iteration:le;if(S!==le){if(oe&&(oe.currentIteration=S),Le==="separate"&&S>1){let k=b;k&&(k.streaming=!1,f(k),Fe.set(S-1,k),b=null)}le=S}N=typeof y.id=="string"?y.id:null,x=null}else if(Q==="tool_input_delta"){let S=y.toolCallId??Y.lastId;if(S){let k=C.get(S);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(y.delta??""),f(k))}}else{if(Q==="tool_input_complete")continue;if(Q==="turn_complete"){let S=y.stopReason,k=b??x;if(S&&k!==null){let B=y.id;(!B||k.agentMetadata?.turnId===B)&&(k.stopReason=S,f(k))}N===y.id&&(N=null)}else if(Q==="media_start"){let S=String(y.id);fe.set(S,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(Q==="media_delta"){let S=fe.get(String(y.id));S&&typeof y.delta=="string"&&S.parts.push(y.delta)}else if(Q==="media_complete"){let S=String(y.id),k=fe.get(S);fe.delete(S);let B=(typeof y.mediaType=="string"?y.mediaType:void 0)??k?.mediaType??"application/octet-stream",G=typeof y.data=="string"?y.data:void 0,H=typeof y.url=="string"?y.url:k&&k.parts.length>0?k.parts.join(""):void 0,q=null;if(G)q={type:"media",data:G,mediaType:B};else if(H){let ct=B.toLowerCase();q={type:ct==="image"||ct.startsWith("image/")?"image-url":"file-url",url:H,mediaType:B}}let se=y.toolCallId??k?.toolCallId,tt=q?[q]:[],We=[];for(let ct of tt){if(!ct||typeof ct!="object")continue;let K=ct,Ue=typeof K.type=="string"?K.type:void 0,Ce=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",He=null,Pe="";if(Ue==="media"){let Je=typeof K.data=="string"?K.data:void 0;if(!Je)continue;Pe=Ce.length>0?Ce:"application/octet-stream",He=`data:${Pe};base64,${Je}`}else if(Ue==="image-url"){let Je=typeof K.url=="string"?K.url:void 0;if(!Je)continue;Pe=Ce,He=Je}else if(Ue==="file-url"){let Je=typeof K.url=="string"?K.url:void 0;if(!Je)continue;Pe=Ce,He=Je}else continue;if(He)if(Ue==="image-url"||Pe.startsWith("image/"))We.push({type:"image",image:He,...Pe.includes("/")?{mimeType:Pe}:{}});else if(Pe.startsWith("audio/"))We.push({type:"audio",audio:He,mimeType:Pe});else if(Pe.startsWith("video/"))We.push({type:"video",video:He,mimeType:Pe});else{let Je=Pe||"application/octet-stream";We.push({type:"file",data:He,mimeType:Je,filename:kg(Je)})}}if(We.length>0){let ct=c(),K=se,Ce={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${ct}`:String(ct)}`,role:"assistant",content:"",contentParts:We,createdAt:new Date().toISOString(),streaming:!1,sequence:ct,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:le}};f(Ce);let He=b;He&&(He.streaming=!1,f(He)),b=null,P.current=null}}else if(Q==="execution_complete"){let S=y.kind??be;S==="agent"&&oe&&(oe.status=y.success?"complete":"error",oe.completedAt=Ne(y.completedAt),oe.stopReason=y.stopReason);let k=b;k&&(S==="flow"&&k.streaming!==!1?ke(k):(k.streaming=!1,f(k)),b=null),M=null,R="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(Q==="execution_error"){let S=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(Q!=="ping"){if(Q==="approval_start"){let S=y.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:oe?.agentId??"virtual",executionId:y.executionId??oe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(k)}else if(Q==="step_await"&&y.awaitReason==="approval_required"){let S=y.approvalId??`approval-${c()}`,k={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:"pending",agentId:oe?.agentId??"virtual",executionId:y.executionId??oe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};f(k)}else if(Q==="approval_complete"){let S=y.approvalId;if(S){let B={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:S,status:y.decision??"approved",agentId:oe?.agentId??"virtual",executionId:y.executionId??oe?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};f(B)}}else if(Q==="artifact_start"||Q==="artifact_delta"||Q==="artifact_update"||Q==="artifact_complete"){if(Q==="artifact_start"){let S=y.artifactType,k=String(y.id),B=typeof y.title=="string"?y.title:void 0,G=y.file,H;G&&typeof G=="object"&&!Array.isArray(G)&&typeof G.path=="string"&&typeof G.mimeType=="string"&&(H={path:G.path,mimeType:G.mimeType,...typeof G.language=="string"?{language:G.language}:{}}),n({type:"artifact_start",id:k,artifactType:S,title:B,component:typeof y.component=="string"?y.component:void 0,...H?{file:H}:{}});let q=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(ge.set(k,{markdown:"",title:B,file:H,...q?{props:q}:{}}),!we.has(k)){we.add(k);let se=Lo(this.config.features?.artifacts,S),tt=typeof y.component=="string"?y.component:void 0,We={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:sa(se,{artifactId:k,title:B,artifactType:S,status:"streaming",...H?{file:H}:{},...tt?{component:tt}:{}})};ve.set(k,We),f(We)}}else if(Q==="artifact_delta"){let S=String(y.id),k=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:S,artDelta:k});let B=ge.get(S);B&&(B.markdown+=k)}else if(Q==="artifact_update"){let S=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:S,component:typeof y.component=="string"?y.component:void 0});let k=ge.get(String(y.id));k&&(k.props={...k.props??{},...S})}else if(Q==="artifact_complete"){let S=String(y.id);n({type:"artifact_complete",id:S});let k=ve.get(S);if(k){k.streaming=!1;try{let B=JSON.parse(k.rawContent??"{}");if(B.props){B.props.status="complete";let G=ge.get(S);G?.markdown&&(B.props.markdown=G.markdown),G?.file&&(B.props.file=G.file),B.component==="PersonaArtifactInline"&&G?.props&&Object.keys(G.props).length>0&&(B.props.componentProps=G.props)}k.rawContent=JSON.stringify(B)}catch{}ge.delete(S),f(k),ve.delete(S)}}}else if(Q==="transcript_insert"){let S=y.message;if(!S||typeof S!="object")continue;let k=String(S.id??`msg-${c()}`),B=S.role,H={id:k,role:B==="user"?"user":B==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let se=JSON.parse(H.rawContent)?.props?.artifactId;typeof se=="string"&&we.add(se)}catch{}b=null,P.current=null,Be.delete(k),it.delete(k)}else if(Q==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let S=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(S)});let k=b;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}else if(Q==="step_error"||Q==="dispatch_error"||Q==="flow_error"){let S=null;if(y.error instanceof Error)S=y.error;else if(Q==="dispatch_error"){let k=y.message??y.error;k!=null&&k!==""&&(S=new Error(String(k)))}else{let k=y.error;typeof k=="string"&&k!==""?S=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(S=new Error(String(k.message??k)))}if(S){n({type:"error",error:S});let k=b;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:E,value:Q}=await s.read();if(E)break;l+=a.decode(Q,{stream:!0});let y=l.split(`
12
12
 
13
- `);l=(fr=Me.pop())!=null?fr:"";for(let Le of Me){let He=Le.split(`
14
- `),nt="message",Xe="",yt=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Xe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(yt=ce.slice(3).trim());let fe=()=>{yt!==null&&yt!==""&&t({type:"cursor",id:yt})};if(!Xe){fe();continue}let D;try{D=JSON.parse(Xe)}catch(ce){t({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let ve=nt!=="message"?nt:(hr=D.type)!=null?hr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){T.current=y;let ce=await this.handleCustomSSEEvent(D,t,T,m,u,W);if(T.current&&T.current!==y&&(y=T.current),ce){fe();continue}}lt.push({payloadType:ve,payload:D}),Ve(),fe()}}Ve()}};function _a(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function bs(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var $a="[Image]";function Qi(n){return{type:"text",text:n}}var pm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Mh=["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"],Gr=[...pm,...Mh];function kh(n){return pm.includes(n)||n.startsWith("image/")}function Ua(n){return kh(n.type)}async function um(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(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 mm(n,e=Gr,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 Lh(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function gm(n,e){let t=Lh(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"}Xi();var fm=16e3,Ph=24e3,Ih=4096,Rh=1380533830;function Wh(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===Rh?new Uint8Array(n,44):new Uint8Array(n)}function Hh(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 ta=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,l,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=(l=this.config)==null?void 0:l.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:fm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:fm});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new vs(Ph);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Hh(r)}/ws/agents/${encodeURIComponent(e)}/voice`,y=new WebSocket(m,["runtype.bearer",t]);y.binaryType="arraybuffer",this.ws=y,y.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,y,o))},y.onmessage=w=>this.handleMessage(w,o),y.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},y.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let T=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),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(Ih,1,1);this.processor=a,a.onaudioprocess=l=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let g=Math.max(-1,Math.min(1,d[u]));c[u]=g<0?g*32768:g*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=Wh(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 zo=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 l;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&&!((l=this.config)!=null&&l.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 ws(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(!zo.isSupported())throw new Error("Browser speech recognition not supported");return new zo(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 hm(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ws({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ws({type:"runtype",runtype:n.runtype});if(zo.isSupported())return ws({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ji(n){try{return hm(n),!0}catch{return!1}}function qa(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 xs=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 l=s.find(d=>d.name===e.voice);l&&(o.voice=l)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):qa(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var l;return(l=t.onEnd)==null?void 0:l.call(t)},o.onerror=l=>{var c,u;let d=l.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(u=t.onError)==null||u.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var l;r.speak(o),(l=t.onStart)==null||l.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var na=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 Yi(n){if(!n)return"";let e=Bh(n);return ym(e!==null?e:n)}function Bh(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 ym(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,`
13
+ `);l=y.pop()??"";for(let S of y){let k=S.split(`
14
+ `),B="message",G="",H=null;for(let We of k)We.startsWith("event:")?B=We.replace("event:","").trim():We.startsWith("data:")?G+=We.replace("data:","").trim():We.startsWith("id:")&&(H=We.slice(3).trim());let q=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!G){q();continue}let se;try{se=JSON.parse(G)}catch(We){n({type:"error",error:We instanceof Error?We:new Error("Failed to parse chat stream payload")});continue}let tt=B!=="message"?B:se.type??"message";if(this.onSSEEvent?.(tt,se),this.parseSSEEvent){P.current=b;let We=await this.handleCustomSSEEvent(se,n,P,f,c,W);if(P.current&&P.current!==b&&(b=P.current),We){q();continue}}lt.push({payloadType:tt,payload:se}),Re(),q()}}Re()}};function ga(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function ar(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var ma="[Image]";function Ki(t){return{type:"text",text:t}}var Nd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ig=["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"],Fn=[...Nd,...Ig];function Rg(t){return Nd.includes(t)||t.startsWith("image/")}function ha(t){return Rg(t.type)}async function Od(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ha(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function _d(t,e=Fn,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Wg(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function $d(t,e){let n=Wg(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}Gi();var Ud=16e3,Bg=24e3,Hg=4096,Dg=1380533830;function Fg(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Dg?new Uint8Array(t,44):new Uint8Array(t)}function Ng(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var es=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(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Ud,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:Ud});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ir(Bg);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Ng(o)}/ws/agents/${encodeURIComponent(e)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let w=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${w}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(Hg,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=Fg(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Wo=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}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 lr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new es(t.runtype);case"browser":if(!Wo.isSupported())throw new Error("Browser speech recognition not supported");return new Wo(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function zd(t){if(t?.type==="custom"&&t.custom)return lr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return lr({type:"runtype",runtype:t.runtype});if(Wo.isSupported())return lr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xi(t){try{return zd(t),!0}catch{return!1}}function ya(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 n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var cr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ya(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var ts=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Qi(t){if(!t)return"";let e=Og(t);return jd(e!==null?e:t)}function Og(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function jd(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&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
15
  `),e=e.replace(/\n{2,}/g,`
16
- `),e.trim()}var Cm=null;var Zi=()=>Cm?Cm():Promise.resolve().then(()=>(xm(),wm));var _h=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function $h(n,e){return _h.some(t=>n[t]!==e[t])}function el(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}
16
+ `),e.trim()}var Xd=null;var Ji=()=>Xd?Xd():Promise.resolve().then(()=>(Gd(),Kd));var jg=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function qg(t,e){return jg.some(n=>t[n]!==e[n])}function Yi(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
17
17
 
18
- _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]}),Tm=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,Em=n=>us(n)||n===Kr,Va=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.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new na(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,l,d,c,u,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(us(h.name)||h.name===Kr&&((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&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(l=e.message.agentMetadata.iteration)!=null?l:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ea(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,l,d,c;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=(c=(d=e.agentId)!=null?d:(l=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:l.agentId)!=null?c:this.config.agentId;!t||!r||!this.config.clientToken||Zi().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 Ji((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,l,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=xs.isSupported()?new xs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(l=e.agentId)!=null?l:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&u&&g)return Zi().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:y})=>{let w=new m({host:c,agentId:u,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new y(w,t,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):w});if(h&&t)return g&&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=ws(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(l=>{l.provider!=="runtype"&&l.text&&l.text.trim()&&this.sendMessage(l.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((l,d,c)=>{if(l==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(l=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,l)}),this.voiceProvider.onError(l=>{console.error("Voice error:",l),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(l=>{var d,c;this.voiceStatus=l,this.voiceActive=l==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,l)}),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,l,d,c,u,g,h,m;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:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(l=(a=e.runtype)==null?void 0:a.clientToken)!=null?l:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.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(!$h(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 ea(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:l,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:g}=e,m={id:a!=null?a:t==="user"?_a():t==="assistant"?bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:l!=null?l:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:l,id:d,createdAt:c,sequence:u,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?_a():o==="assistant"?bs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}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:l,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},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,u,g,h,m;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(),this.teardownReconnect();let o=_a(),s=bs();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||$a,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 l=new AbortController;this.abortController=l;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(y){if(this.status==="resuming"||this.reconnecting)return;let w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!w){let T=el(y,this.config.errorMessage);if(T){let W={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(W)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(y instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,y):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(y))))}}async continueConversation(){var o,s,a,l,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=bs();this.activeAssistantMessageId=null,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){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=el(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(l=this.callbacks).onError)==null||d.call(l,new Error(String(c))))}}async connectStream(e,t){var s,a,l;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(l=(a=this.callbacks).onError)==null||l.call(a,d instanceof Error?d:new Error(String(d)))}}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(l=>{this.webMcpApprovalResolvers.set(r,l)})}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 u,g,h,m,y;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),l={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let T=null;if(w instanceof Response){if(!w.ok){let W=await w.json().catch(()=>null);throw new Error((h=W==null?void 0:W.error)!=null?h:`Approval request failed: ${w.status}`)}T=w.body}else w instanceof ReadableStream&&(T=w);T?await this.connectStream(T,{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(w){let T=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(y=(m=this.callbacks).onError)==null||y.call(m,w instanceof Error?w:new Error(String(w)))}}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 u,g,h,m,y,w,T,W,E,H,B,I;let r=this.messages.find(S=>S.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,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 S=(w=e.toolCall)==null?void 0:w.args,P=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(P.length===1){let z=typeof((T=P[0])==null?void 0:T.question)=="string"?P[0].question:"";z&&(a={[z]:t})}}this.markAskUserQuestionResolved(e,a),(W=this.abortController)==null||W.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=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 S=typeof t=="string"?t:Object.entries(t).map(([P,z])=>`${P}: ${Array.isArray(z)?z.join(", "):z}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};c.forEach((P,z)=>{let U=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!U)return;let k=S[U],_=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${l}-${z}`,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${z}`,role:"user",content:_||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(o,{[s]:t});if(!S.ok){let P=await S.json().catch(()=>null);throw new Error((H=P==null?void 0:P.error)!=null?H:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let P=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(I=(B=this.callbacks).onError)==null||I.call(B,S instanceof Error?S:new Error(String(S)))}}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 l=this.webMcpEpoch;queueMicrotask(()=>{l===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)!==Kr)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,u,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var I,S,P,z,U,k,_;let m=(I=h.toolCall)==null?void 0:I.name,y=(S=h.toolCall)==null?void 0:S.id;if(!m||!y)return null;let w=`${e}:${y}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let T=this.markWebMcpToolRunning(h),W=(z=(P=h.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?z:m;if(m===Kr)return{dedupeKey:w,resumeKey:W,output:ji(),toolMessage:h,startedAt:T,completedAt:Date.now()};let E=new AbortController;this.webMcpResolveControllers.add(E),o.push(E);let H=this.client.executeWebMcpToolCall(m,(U=h.toolCall)==null?void 0:U.args,E.signal),B;if(!H)B={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{B=await H}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(_=(k=this.callbacks).onError)==null||_.call(k,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(h,ra(Z?"Aborted by cancel()":Tm(O)),T),this.webMcpInflightKeys.delete(w),null}return E.signal.aborted?(this.markWebMcpToolComplete(h,ra("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:W,output:B,toolMessage:h,startedAt:T,completedAt:Date.now()}})),l=[];try{if(l=a.filter(y=>y!==null),l.length===0)return;let h={};for(let y of l)h[y.resumeKey]=y.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${m.status}`)}for(let y of l)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((c=y.toolMessage.toolCall)==null?void 0:c.name)===Kr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,h instanceof Error?h:new Error(String(h)));else for(let y of l)this.markWebMcpToolComplete(y.toolMessage,ra("Aborted by cancel()"),y.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var y,w,T,W,E,H,B,I,S,P,z,U;let t=(y=e.agentMetadata)==null?void 0:y.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(T=e.toolCall)==null?void 0:T.id;if(!t){(E=(W=this.callbacks).onError)==null||E.call(W,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(_){(B=(H=this.callbacks).onError)==null||B.call(H,_ instanceof Error?_:new Error(String(_)))}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),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let c=r===Kr,u=(I=e.toolCall)==null?void 0:I.args,g=c?null:this.client.executeWebMcpToolCall(r,u,d),h="execute",m=a;try{let k;if(c?k=ji():g?k=await g:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ra("Aborted by cancel()"),a);return}let _=(P=(S=e.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?P:r;h="resume",await this.resumeWithToolOutput(t,_,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,k,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let _=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(h==="execute"||_||d.aborted)&&this.markWebMcpToolComplete(e,ra(_||d.aborted?"Aborted by cancel()":Tm(k)),a),_||(U=(z=this.callbacks).onError)==null||U.call(z,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,l;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}`)}(l=o==null?void 0:o.onHttpOk)==null||l.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.teardownReconnect(),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.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(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.teardownReconnect(),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()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Sm(),Am)).then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>el(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=bs(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}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=Yi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return qa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Yi(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 u,g,h,m,y,w,T,W,E,H,B,I,S,P,z;if(s!==r)return o;let a={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let U=o.approval,k=t.approval;a.approval={...U,...k,executionId:k.executionId||U.executionId,toolName:k.toolName||U.toolName,description:k.description||U.description,toolType:(m=k.toolType)!=null?m:U.toolType,reason:(y=k.reason)!=null?y:U.reason,parameters:(w=k.parameters)!=null?w:U.parameters}}let l=(T=t.toolCall)==null?void 0:T.name,d=(W=t.agentMetadata)==null?void 0:W.executionId,c=(E=t.toolCall)==null?void 0:E.id;if(l&&Em(l)&&d&&c&&((H=t.agentMetadata)==null?void 0:H.awaitingLocalTool)===!0){let U=`${d}:${c}`,k=this.webMcpInflightKeys.has(U),_=this.webMcpResolvedKeys.has(U),O=(B=o.toolCall)==null?void 0:B.name,Z=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((S=o.toolCall)==null?void 0:S.id)===c&&O!==void 0&&Em(O)&&((P=o.toolCall)==null?void 0:P.status)==="complete";(k||_||Z)&&(a.agentMetadata={...(z=a.agentMetadata)!=null?z:{},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,l=(c=r.sequence)!=null?c:0;return a!==l?a-l:t.id.localeCompare(r.id)})}};var A=require("lucide"),Uh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ye=(n,e=24,t="currentColor",r=2)=>{let o=Uh[n];return o?qh(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 qh(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],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Ka={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function zh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function jh(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(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ka.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ka.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ka.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:Ka.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,l,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 u=mm(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await um(c),h=Ua(c)?URL.createObjectURL(c):null,m={id:zh(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(l=this.config).onAttachmentsChange)==null||d.call(l,this.getAttachments())}}removeAttachment(e){var s,a,l;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(),(l=(a=this.config).onAttachmentsChange)==null||l.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=Ua(e.file),r=v("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=v("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=v("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 l=jh(e.file.type),d=ye(l,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=v("span");c.textContent=gm(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=v("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=ye("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 Mm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function sa(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];Mm(s)&&Mm(o)?t[r]=sa(s,o):t[r]=o}return t}var Qr="min(440px, calc(100vw - 24px))",Lm="440px",Vh={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)"},Bt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Vh,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,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 km(n,e){if(!(!n&&!e))return n?e?sa(n,e):n:e}function Pm(n){var e,t,r,o,s,a,l,d,c,u,g,h,m,y,w,T,W,E,H,B,I;return n?{...Bt,...n,theme:km(Bt.theme,n.theme),darkTheme:km(Bt.darkTheme,n.darkTheme),launcher:{...Bt.launcher,...n.launcher,dock:{...(e=Bt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...n.copy},sendButton:{...Bt.sendButton,...n.sendButton},statusIndicator:{...Bt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,oe,de,Ae,$e,K,J,Se,Y,le;let S=(re=Bt.features)==null?void 0:re.artifacts,P=(oe=n.features)==null?void 0:oe.artifacts,z=(de=Bt.features)==null?void 0:de.scrollToBottom,U=(Ae=n.features)==null?void 0:Ae.scrollToBottom,k=($e=Bt.features)==null?void 0:$e.scrollBehavior,_=(K=n.features)==null?void 0:K.scrollBehavior,O=(J=Bt.features)==null?void 0:J.streamAnimation,Z=(Se=n.features)==null?void 0:Se.streamAnimation,ke=(Y=Bt.features)==null?void 0:Y.askUserQuestion,pe=(le=n.features)==null?void 0:le.askUserQuestion,ee=S===void 0&&P===void 0?void 0:{...S,...P,layout:{...S==null?void 0:S.layout,...P==null?void 0:P.layout}},Pe=z===void 0&&U===void 0?void 0:{...z,...U},Ie=k===void 0&&_===void 0?void 0:{...k,..._},ie=O===void 0&&Z===void 0?void 0:{...O,...Z},he=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...n.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ie!==void 0?{streamAnimation:ie}:{},...he!==void 0?{askUserQuestion:he}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Bt.layout,...n.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(l=n.layout)==null?void 0:l.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(u=Bt.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(y=Bt.layout)==null?void 0:y.messages)==null?void 0:w.timestamp,...(W=(T=n.layout)==null?void 0:T.messages)==null?void 0:W.timestamp}},slots:{...(E=Bt.layout)==null?void 0:E.slots,...(H=n.layout)==null?void 0:H.slots}},markdown:{...Bt.markdown,...n.markdown,options:{...(B=Bt.markdown)==null?void 0:B.options,...(I=n.markdown)==null?void 0:I.options}},messageActions:{...Bt.messageActions,...n.messageActions}}:Bt}var Kh={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"}},Gh={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"}},Qh={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:Lm,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Cs(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."))?Cs(n,r):r}function Im(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let l=`${o}.${s}`;if(typeof a=="string"){let d=Cs(n,a);d!==void 0&&(e[l]={path:l,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,l)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Xh(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 Rm(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]=Rm(s,o):t[r]=o}return t}function Jh(n,e){return e?Rm(n,e):n}function jo(n,e={}){var o,s,a,l,d,c,u,g,h,m,y,w,T;let t={palette:Kh,semantic:Gh,components:Qh},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,...(l=n==null?void 0:n.palette)==null?void 0:l.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,...(u=n==null?void 0:n.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(y=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(T=n==null?void 0:n.semantic)==null?void 0:T.typography}},components:Jh(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let W=Xh(r);if(!W.valid)throw new Error(`Theme validation failed: ${W.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let W of e.plugins)r=W.transform(r);return r}function Wm(n){var w,T,W,E,H,B,I,S,P,z,U,k,_,O,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me,X,lt,Ve,Ee,xe,Ze,jt,be,ue,An,At,yn,fr,hr,qe,M,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,Zt,yr,Wr,rr,or,Xr,Vt,sr,Hr,Bn,In,Dn,ar,br,Jr,Vn,Yr,St,vr,wr,Br,ir,bt,So,xr,To,Rn,Jo,Zr,Dr,eo,to,Eo,Mo,no,xt,Nn,Fn,Sn,Tt,Kn,Gn,On,ro;let e=Im(n),t={};for(let[Ce,Nr]of Object.entries(e)){let Qn=Ce.replace(/\./g,"-");t[`--persona-${Qn}`]=Nr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(W=t["--persona-semantic-colors-accent"])!=null?W: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"]=(H=t["--persona-semantic-colors-background"])!=null?H:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(B=t["--persona-semantic-colors-container"])!=null?B:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(I=t["--persona-semantic-colors-text"])!=null?I:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(S=t["--persona-semantic-colors-text-muted"])!=null?S:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(z=t["--persona-semantic-colors-border"])!=null?z:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(U=t["--persona-semantic-colors-divider"])!=null?U: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"]=(_=t["--persona-components-voice-recording-background"])!=null?_:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Z=t["--persona-components-voice-speaking-icon"])!=null?Z:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ke=t["--persona-components-approval-requested-background"])!=null?ke:t["--persona-surface"],t["--persona-approval-border"]=(pe=t["--persona-components-approval-requested-border"])!=null?pe:t["--persona-border"],t["--persona-approval-text"]=(ee=t["--persona-components-approval-requested-text"])!=null?ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Pe=t["--persona-components-approval-requested-shadow"])!=null?Pe:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Ie=t["--persona-components-approval-approve-background"])!=null?Ie:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ie=t["--persona-components-approval-deny-background"])!=null?ie:t["--persona-container"],t["--persona-attachment-image-bg"]=(he=t["--persona-components-attachment-image-background"])!=null?he: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"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(de=t["--persona-semantic-typography-fontSize"])!=null?de:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ae=t["--persona-semantic-typography-fontWeight"])!=null?Ae:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=($e=t["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(J=t["--persona-palette-radius-md"])!=null?J:"0.375rem",t["--persona-radius-lg"]=(Se=t["--persona-palette-radius-lg"])!=null?Se:"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"]=(Ye=(Te=t["--persona-components-launcher-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?Ye:"9999px",t["--persona-launcher-bg"]=(tt=t["--persona-components-launcher-background"])!=null?tt:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ht=t["--persona-components-launcher-border"])!=null?ht:t["--persona-border"],t["--persona-button-primary-bg"]=(ot=t["--persona-components-button-primary-background"])!=null?ot:t["--persona-primary"],t["--persona-button-primary-fg"]=(me=t["--persona-components-button-primary-foreground"])!=null?me:t["--persona-text-inverse"],t["--persona-button-radius"]=(lt=(X=t["--persona-components-button-primary-borderRadius"])!=null?X:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-panel-radius"]=(Ee=(Ve=t["--persona-components-panel-borderRadius"])!=null?Ve:t["--persona-radius-xl"])!=null?Ee:"0.75rem",t["--persona-panel-border"]=(xe=t["--persona-components-panel-border"])!=null?xe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(jt=(Ze=t["--persona-components-panel-shadow"])!=null?Ze:t["--persona-palette-shadows-xl"])!=null?jt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(be=t["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(An=(ue=t["--persona-components-input-borderRadius"])!=null?ue:t["--persona-radius-lg"])!=null?An:"0.5rem",t["--persona-message-user-radius"]=(yn=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?yn:"0.5rem",t["--persona-message-assistant-radius"]=(hr=(fr=t["--persona-components-message-assistant-borderRadius"])!=null?fr:t["--persona-radius-lg"])!=null?hr:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(M=t["--persona-components-header-border"])!=null?M:t["--persona-divider"],t["--persona-header-icon-bg"]=(ge=t["--persona-components-header-iconBackground"])!=null?ge:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(He=t["--persona-components-header-subtitleForeground"])!=null?He:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(nt=t["--persona-components-header-actionIconForeground"])!=null?nt:t["--persona-muted"];let r=(Xe=n.components)==null?void 0:Xe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=n.components)==null?void 0:yt.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(D=t["--persona-components-introCard-borderRadius"])!=null?D:"1rem",t["--persona-intro-card-padding"]=(ve=t["--persona-components-introCard-padding"])!=null?ve:"1.5rem",t["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:t["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ge=t["--persona-components-input-background"])!=null?Ge:t["--persona-surface"],t["--persona-input-placeholder"]=(Pt=t["--persona-components-input-placeholder"])!=null?Pt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ht=t["--persona-components-message-user-shadow"])!=null?Ht:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Xt=t["--persona-components-message-assistant-background"])!=null?Xt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(Zt=t["--persona-components-message-assistant-border"])!=null?Zt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(yr=t["--persona-components-message-assistant-shadow"])!=null?yr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(rr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?rr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Xr=(or=t["--persona-components-scrollToBottom-foreground"])!=null?or:t["--persona-button-primary-fg"])!=null?Xr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Vt=t["--persona-components-scrollToBottom-border"])!=null?Vt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(sr=t["--persona-components-scrollToBottom-size"])!=null?sr:"40px",t["--persona-scroll-to-bottom-radius"]=(In=(Bn=(Hr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Hr:t["--persona-button-radius"])!=null?Bn:t["--persona-radius-full"])!=null?In:"9999px",t["--persona-scroll-to-bottom-shadow"]=(ar=(Dn=t["--persona-components-scrollToBottom-shadow"])!=null?Dn:t["--persona-palette-shadows-sm"])!=null?ar:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(br=t["--persona-components-scrollToBottom-padding"])!=null?br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Jr=t["--persona-components-scrollToBottom-gap"])!=null?Jr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Yr=(Vn=t["--persona-components-scrollToBottom-fontSize"])!=null?Vn:t["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(St=t["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",t["--persona-tool-bubble-shadow"]=(vr=t["--persona-components-toolBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(wr=t["--persona-components-reasoningBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Br=t["--persona-components-composer-shadow"])!=null?Br:"none",t["--persona-md-inline-code-bg"]=(ir=t["--persona-components-markdown-inlineCode-background"])!=null?ir:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(xr=(So=t["--persona-components-markdown-link-foreground"])!=null?So:t["--persona-accent"])!=null?xr:"#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 l=t["--persona-components-markdown-heading-h2-fontSize"];l&&(t["--persona-md-h2-size"]=l);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"]=(To=t["--persona-components-markdown-codeBlock-background"])!=null?To:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Rn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Rn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Jo=t["--persona-components-markdown-codeBlock-textColor"])!=null?Jo:"inherit",t["--persona-md-table-header-bg"]=(Zr=t["--persona-components-markdown-table-headerBackground"])!=null?Zr:t["--persona-container"],t["--persona-md-table-border-color"]=(Dr=t["--persona-components-markdown-table-borderColor"])!=null?Dr:t["--persona-border"],t["--persona-md-hr-color"]=(eo=t["--persona-components-markdown-hr-color"])!=null?eo:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(to=t["--persona-components-markdown-blockquote-borderColor"])!=null?to:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Eo=t["--persona-components-markdown-blockquote-background"])!=null?Eo:"transparent",t["--persona-md-blockquote-text-color"]=(Mo=t["--persona-components-markdown-blockquote-textColor"])!=null?Mo:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(no=t["--persona-components-collapsibleWidget-container"])!=null?no:t["--persona-surface"],t["--cw-surface"]=(xt=t["--persona-components-collapsibleWidget-surface"])!=null?xt:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Fn=t["--persona-components-message-border"])!=null?Fn:t["--persona-border"];let u=n.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=u==null?void 0:u.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let y=u==null?void 0:u.artifact;if(y!=null&&y.toolbar){let Ce=y.toolbar;Ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,t["--persona-dropdown-bg"]=(Sn=t["--persona-dropdown-bg"])!=null?Sn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,t["--persona-dropdown-border"]=(Tt=t["--persona-dropdown-border"])!=null?Tt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Gn=t["--persona-dropdown-radius"])!=null?Gn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(On=t["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(y!=null&&y.tab){let Ce=y.tab;Ce.background&&(t["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(t["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(t["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(y!=null&&y.pane){let Ce=y.pane;if(Ce.toolbarBackground){let Nr=(ro=Cs(n,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nr}}return t}var Yh={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"}}},Hm=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},tl=()=>{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"},Zh=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":tl()},ey=n=>Zh(n),ty=n=>jo(n),ny=n=>{var t;let e=jo(void 0,{validate:!1});return jo({...n,palette:{...e.palette,colors:{...Yh.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ga=n=>{let e=ey(n),t=Hm(n==null?void 0:n.theme),r=Hm(n==null?void 0:n.darkTheme);return e==="dark"?ny(sa(t!=null?t:{},r!=null?r:{})):ty(t)},ry=n=>Wm(n),As=(n,e)=>{let t=Ga(e),r=ry(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Bm=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(tl())});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(tl());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 Dm=require("idiomorph"),Qa=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Dm.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,l;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;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=(l=s.textContent)!=null?l:"";if(d!==c)return}return!1}}}}})};var Nm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Xa={index:-1,draft:""};function Fm(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 l=t.length-1;return{handled:!0,value:t[l],state:{index:l,draft:r}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:t[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let l=s.index+1;return{handled:!0,value:t[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Xa}}}function Om(n,e){var t,r,o,s,a,l,d,c,u,g,h,m,y,w,T,W,E,H,B,I,S,P,z,U,k,_,O,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de;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=(l=n.rawContent)==null?void 0:l.length)!=null?d:0,(u=(c=n.llmContent)==null?void 0:c.length)!=null?u:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(y=(m=n.toolCall)==null?void 0:m.status)!=null?y:"",(T=(w=n.toolCall)==null?void 0:w.name)!=null?T:"",(H=(E=(W=n.toolCall)==null?void 0:W.chunks)==null?void 0:E.length)!=null?H:0,(P=(S=(I=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:I[n.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?P:"",typeof((z=n.toolCall)==null?void 0:z.args)=="string"?n.toolCall.args.length:(U=n.toolCall)!=null&&U.args?JSON.stringify(n.toolCall.args).length:0,(O=(_=(k=n.reasoning)==null?void 0:k.chunks)==null?void 0:_.length)!=null?O:0,(ee=(pe=(ke=(Z=n.reasoning)==null?void 0:Z.chunks)==null?void 0:ke[n.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(he=(ie=(Ie=(Pe=n.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?he:"",(oe=(re=n.contentParts)==null?void 0:re.length)!=null?oe:0,(de=n.stopReason)!=null?de:"",e].join("\0")}function _m(){return new Map}function $m(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Um(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function qm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Ja(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Rr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function xo(n,e){return Rr(n)-n.scrollTop<=e}function Ya(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Za(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 zm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function jm(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 Vm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Co=xn+1;var aa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},oy=["pre","code","a","script","style"],ei=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:aa.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t: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}},sy=[{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"}],Gm=new Map;for(let n of sy)Gm.set(n.name,n);var Ss=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Gm.get(n))!=null?r:null},ti=(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},ay=(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},iy=(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},nl=/\s/,ly=(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},cy=(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(),l=0;for(;l<s.length;)if(nl.test(s[l])){let c=l;for(;c<s.length&&nl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(l,c))),l=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=l;for(;u<s.length&&!nl.test(s[u]);)c.appendChild(ay(r,s[u],e,t.value)),t.value+=1,u+=1;a.appendChild(c),l=u}o.replaceChild(a,n)},dy=(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(),l=s.split(/(\s+)/);for(let c of l)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(iy(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},ia=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:oy).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)ly(d,s)||l.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},u=e==="char"?cy:dy;for(let m of l)u(m,t,c);return o.innerHTML},ni=(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},la=(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},Km=new WeakMap,py=(n,e)=>{var s;if(!n.styles)return;let t=Km.get(e);if(t||(t=new Set,Km.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)},rl=new WeakMap,uy=(n,e)=>{if(!n.onAttach)return;let t=rl.get(e);if(t||(t=new Map,rl.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Qm=n=>{let e=rl.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},ri=(n,e)=>{py(n,e),uy(n,e)};function ol(n,e=xn){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 ca=0,Ao=null;function sl(n=document){var t;if(ca++,ca===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;Ao={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,ca=Math.max(0,ca-1),ca===0&&Ao)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=Ao.originalOverflow,o.style.position=Ao.originalPosition,o.style.top=Ao.originalTop,o.style.width=Ao.originalWidth,s.scrollTo(0,Ao.scrollY),Ao=null}}}var da={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},hn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},pa=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},mr=n=>{var t,r,o,s,a,l;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:da.side,width:(o=e==null?void 0:e.width)!=null?o:da.width,animate:(s=e==null?void 0:e.animate)!=null?s:da.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:da.reveal,maxHeight:(l=e==null?void 0:e.maxHeight)!=null?l:da.maxHeight}};var gr={"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 my="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",oi=(n,e={})=>{var T,W,E,H,B,I;let{showClose:t=!0,wrapperClassName:r=my,buttonSize:o,iconSize:s="28px"}=e,a=(T=n==null?void 0:n.launcher)!=null?T:{},l=(W=o!=null?o:a.closeButtonSize)!=null?W:"32px",d=v("div",r),c=(E=a.closeButtonTooltipText)!=null?E:"Close chat",u=(H=a.closeButtonShowTooltip)!=null?H:!0,g=(B=a.closeButtonIconName)!=null?B:"x",h=(I=a.closeButtonIconText)!=null?I:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Mt("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:l,width:l,display:t?void 0:"none",color:a.closeButtonColor||Pn.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}}),w=ye(g,s,"currentColor",1);if(w?(w.style.display="block",y.appendChild(w)):y.textContent=h,d.appendChild(y),u&&c){let S=null,P=()=>{if(S)return;let U=y.ownerDocument,k=U.body;if(!k)return;S=Ir(U,"div","persona-clear-chat-tooltip"),S.textContent=c;let _=Ir(U,"div");_.className="persona-clear-chat-tooltip-arrow",S.appendChild(_);let O=y.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(Co),S.style.left=`${O.left+O.width/2}px`,S.style.top=`${O.top-8}px`,S.style.transform="translate(-50%, -100%)",k.appendChild(S)},z=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};d.addEventListener("mouseenter",P),d.addEventListener("mouseleave",z),y.addEventListener("focus",P),y.addEventListener("blur",z),d._cleanupTooltip=()=>{z(),d.removeEventListener("mouseenter",P),d.removeEventListener("mouseleave",z),y.removeEventListener("focus",P),y.removeEventListener("blur",z)}}return{button:y,wrapper:d}},gy="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",si=(n,e={})=>{var S,P,z,U,k,_,O,Z,ke,pe,ee,Pe,Ie;let{wrapperClassName:t=gy,buttonSize:r,iconSize:o="20px"}=e,a=(P=((S=n==null?void 0:n.launcher)!=null?S:{}).clearChat)!=null?P:{},l=(z=r!=null?r:a.size)!=null?z:"32px",d=(U=a.iconName)!=null?U:"refresh-cw",c=(k=a.iconColor)!=null?k:"",u=(_=a.backgroundColor)!=null?_:"",g=(O=a.borderWidth)!=null?O:"",h=(Z=a.borderColor)!=null?Z:"",m=(ke=a.borderRadius)!=null?ke:"",y=(pe=a.paddingX)!=null?pe:"",w=(ee=a.paddingY)!=null?ee:"",T=(Pe=a.tooltipText)!=null?Pe:"Clear chat",W=(Ie=a.showTooltip)!=null?Ie:!0,E=v("div",t),H=!!(g||h),B=Mt("button",{className:Ks("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!H&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:c||Pn.actionIconColor,backgroundColor:u||void 0,border:H?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),I=ye(d,o,"currentColor",1);if(I&&(I.style.display="block",B.appendChild(I)),E.appendChild(B),W&&T){let ie=null,he=()=>{if(ie)return;let oe=B.ownerDocument,de=oe.body;if(!de)return;ie=Ir(oe,"div","persona-clear-chat-tooltip"),ie.textContent=T;let Ae=Ir(oe,"div");Ae.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Ae);let $e=B.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(Co),ie.style.left=`${$e.left+$e.width/2}px`,ie.style.top=`${$e.top-8}px`,ie.style.transform="translate(-50%, -100%)",de.appendChild(ie)},re=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};E.addEventListener("mouseenter",he),E.addEventListener("mouseleave",re),B.addEventListener("focus",he),B.addEventListener("blur",re),E._cleanupTooltip=()=>{re(),E.removeEventListener("mouseenter",he),E.removeEventListener("mouseleave",re),B.removeEventListener("focus",he),B.removeEventListener("blur",re)}}return{button:B,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))"},Vo=n=>{var I,S,P,z,U,k,_,O,Z,ke,pe,ee,Pe,Ie,ie,he;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=(I=e==null?void 0:e.launcher)!=null?I:{},s=(S=o.headerIconSize)!=null?S:"48px",a=(P=o.closeButtonPlacement)!=null?P:"inline",l=(z=o.headerIconHidden)!=null?z:!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(!l)if(d){let re=parseFloat(s)||24,oe=ye(d,re*.6,"currentColor",1);oe?c.replaceChildren(oe):c.textContent=(k=(U=e==null?void 0:e.launcher)==null?void 0:U.agentIconText)!=null?k:"\u{1F4AC}"}else if((_=e==null?void 0:e.launcher)!=null&&_.iconUrl){let re=v("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=(Z=(O=e==null?void 0:e.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(ke=e==null?void 0:e.launcher)==null?void 0:ke.title)!=null?pe:"Chat Assistant",style:{color:Pn.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Pe=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:Pn.subtitleColor}});u.append(g,h),l?r.append(u):r.append(c,u);let m=(Ie=o.clearChat)!=null?Ie:{},y=(ie=m.enabled)!=null?ie:!0,w=(he=m.placement)!=null?he:"inline",T=null,W=null;if(y){let oe=si(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=oe.button,W=oe.wrapper,w==="top-right"&&(W.style.right="48px"),w==="inline"&&r.appendChild(W)}let E=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&w==="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:H,wrapper:B}=oi(e,{showClose:t,wrapperClassName:E});return a!=="top-right"&&r.appendChild(B),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:H,closeButtonWrapper:B,clearChatButton:T,clearChatButtonWrapper:W}},ua=(n,e,t)=>{var a,l,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(l=r.closeButtonPlacement)!=null?l:"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 Ts(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=v("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 m of e){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let T=ye(m.icon,16,"currentColor",1.5);T&&y.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,y.appendChild(w),y.addEventListener("click",T=>{T.stopPropagation(),u(),t(m.id)}),a.appendChild(y)}let l=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=y=>{!a.contains(y.target)&&!r.contains(y.target)&&u()};document.addEventListener("click",m,!0),l=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),l==null||l(),l=null}function g(){a.classList.contains("persona-hidden")?c():u()}function h(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:g,destroy:h}}function Cn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:l}=n,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=ye(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),l)for(let[u,g]of Object.entries(l))d.setAttribute(u,g);return d}function al(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:l,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=v("button",c);if(u.type="button",u.setAttribute("aria-label",t),e){let h=ye(e,s!=null?s:14,"currentColor",2);h&&u.appendChild(h)}let g=v("span");if(g.textContent=t,u.appendChild(g),l&&u.addEventListener("click",l),d)for(let[h,m]of Object.entries(d))u.setAttribute(h,m);return u}function Xm(n){var m,y;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:l,hover:d}=n,c=v("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let g=ye(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(y=d.padding)!=null?y:"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 w,T;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=Ts({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let T=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{u.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var fy=n=>{var r;let e=Vo({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 hy(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let l=v("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(l.type="button",l.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&l.appendChild(d)}else a.label&&(l.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(l);let c=Ts({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),l.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),n.appendChild(d)}else l.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(l)}}var yy=n=>{var E,H,B,I,S,P,z,U,k;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(E=e==null?void 0:e.launcher)!=null?E:{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,u;if(d)c=Xm({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Pn.titleColor,u=(B=c.querySelector(".persona-combo-btn-label"))!=null?B:c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=Pn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),hy(c,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let O=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||O()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),O())})}let _=o==null?void 0:o.titleRowHover;_&&(c.style.borderRadius=(P=_.borderRadius)!=null?P:"10px",c.style.padding=(z=_.padding)!=null?z:"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 O,Z;c.style.backgroundColor=(O=_.background)!=null?O:"",c.style.borderColor=(Z=_.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let g=(U=a.closeButtonSize)!=null?U:"32px",h=v("div",""),m=v("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=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||Pn.actionIconColor;let y=(k=a.closeButtonIconName)!=null?k:"x",w=ye(y,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),l.appendChild(h);let T=v("div");T.style.display="none";let W=v("span");return W.style.display="none",{header:l,iconHolder:T,headerTitle:u,headerSubtitle:W,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},Jm={default:fy,minimal:yy},by=n=>{var e;return(e=Jm[n])!=null?e:Jm.default},ai=(n,e,t)=>{var a,l,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}),u=v("div");u.style.display="none";let g=v("span"),h=v("span"),m=v("button");m.style.display="none";let y=v("div");return y.style.display="none",{header:c,iconHolder:u,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=by(r)({config:n,showClose:(d=(l=e==null?void 0:e.showCloseButton)!=null?l: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 ii=n=>{var a,l;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(l=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?l:"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}},li=n=>{var I,S,P,z,U,k,_,O,Z,ke,pe,ee;let e=(I=n==null?void 0:n.sendButton)!=null?I:{},t=(S=e.useIcon)!=null?S:!1,r=(P=e.iconText)!=null?P:"\u2191",o=e.iconName,s=(z=e.stopIconName)!=null?z:"square",a=(U=e.tooltipText)!=null?U:"Send message",l=(k=e.stopTooltipText)!=null?k:"Stop generating",d=(O=(_=n==null?void 0:n.copy)==null?void 0:_.sendButtonLabel)!=null?O:"Send",c=(ke=(Z=n==null?void 0:n.copy)==null?void 0:Z.stopButtonLabel)!=null?ke:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,g=(ee=e.size)!=null?ee:"40px",h=e.backgroundColor,m=e.textColor,y=v("div","persona-send-button-wrapper"),w=Mt("button",{className:Ks("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&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||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}}),T=null,W=null;if(t){let Pe=parseFloat(g)||24,Ie=(m==null?void 0:m.trim())||"currentColor";o?(T=ye(o,Pe,Ie,2),T?w.appendChild(T):w.textContent=r):w.textContent=r,W=ye(s,Pe,Ie,2)}else w.textContent=d;let E=null;u&&a&&(E=v("div","persona-send-button-tooltip"),E.textContent=a,y.appendChild(E)),w.setAttribute("aria-label",a),y.appendChild(w);let H="send";return{button:w,wrapper:y,setMode:Pe=>{if(Pe===H)return;H=Pe;let Ie=Pe==="stop"?l:a;if(w.setAttribute("aria-label",Ie),E&&(E.textContent=Ie),t){if(T&&W){let ie=Pe==="stop"?W:T;w.replaceChildren(ie)}}else w.textContent=Pe==="stop"?c:d}}},ci=n=>{var E,H,B,I,S,P,z,U,k,_,O,Z;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=((H=e.provider)==null?void 0:H.type)==="runtype";if(!(r||o))return null;let a=(I=(B=n==null?void 0:n.sendButton)==null?void 0:B.size)!=null?I:"40px",l=(S=e.iconName)!=null?S:"mic",d=(P=e.iconSize)!=null?P:a,c=parseFloat(d)||24,u=(U=e.backgroundColor)!=null?U:(z=n==null?void 0:n.sendButton)==null?void 0:z.backgroundColor,g=(_=e.iconColor)!=null?_:(k=n==null?void 0:n.sendButton)==null?void 0:k.textColor,h=v("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",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:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=ye(l,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let T=(O=e.tooltipText)!=null?O:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&T){let ke=v("div","persona-send-button-tooltip");ke.textContent=T,h.appendChild(ke)}return{button:m,wrapper:h}},di=n=>{var y,w,T,W,E,H,B,I;let e=(y=n==null?void 0:n.attachments)!=null?y:{};if(e.enabled!==!0)return null;let t=(T=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?T:"40px",r=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((W=e.allowedTypes)!=null?W:Gr).join(","),o.multiple=((E=e.maxFiles)!=null?E:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(H=e.buttonIconName)!=null?H:"paperclip",a=t,l=parseFloat(a)||40,d=Math.round(l*.6),c=v("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 persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(B=e.buttonTooltipText)!=null?B:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=ye(s,d,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",S=>{S.preventDefault(),o.click()}),c.appendChild(u);let h=(I=e.buttonTooltipText)!=null?I:"Attach file",m=v("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},pi=n=>{var a,l,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=v("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(l=e.visible)!=null?l:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=v("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},ui=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var mi=n=>{var y,w,T,W,E,H;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=ui(),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}=ii(e);a();let l=li(e),d=ci(e),c=di(e),u=pi(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(l.wrapper),g.append(h,m),o.append(g),o.addEventListener("click",B=>{B.target!==l.button&&B.target!==l.wrapper&&B.target!==(d==null?void 0:d.button)&&B.target!==(d==null?void 0:d.wrapper)&&B.target!==(c==null?void 0:c.button)&&B.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:u,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(H=c==null?void 0:c.previewsContainer)!=null?H:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:l.setMode}};var Ym=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),t=ye("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},Zm=n=>{var y,w,T,W,E,H;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ui();r.style.display="none";let o=pi(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ii(e);s.style.maxHeight="100px",a();let l=li(e),d=ci(e),c=di(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(l.wrapper),u.addEventListener("click",B=>{B.target!==l.button&&B.target!==l.wrapper&&B.target!==(d==null?void 0:d.button)&&B.target!==(d==null?void 0:d.wrapper)&&B.target!==(c==null?void 0:c.button)&&B.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(g,s,h),c&&t.append(c.previewsContainer),t.append(u,r,o);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(W=c==null?void 0:c.wrapper)!=null?W:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(H=c==null?void 0:c.previewsContainer)!=null?H:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:l.setMode}};var eg=n=>{var u,g,h,m,y,w,T,W,E,H,B,I,S,P,z,U,k;let e=(g=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?g:!0,t=hn(n);if(pa(n)){let _=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},O=v("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(y=_.expandedSize)!=null?y:"anchored",O.style.zIndex=String((T=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?T:xn);let Z=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",O.appendChild(Z);let ke=v("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(W=_.expandedSize)!=null?W:"anchored",ke.style.zIndex=String((H=(E=n==null?void 0:n.launcher)==null?void 0:E.zIndex)!=null?H:xn),{wrapper:O,panel:Z,pillRoot:ke}}if(t){let _=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return _.appendChild(O),{wrapper:_,panel:O}}if(!e){let _=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(I=(B=n==null?void 0:n.launcher)==null?void 0:B.width)!=null?I:"100%";return _.style.width=Z,O.style.width="100%",_.appendChild(O),{wrapper:_,panel:O}}let o=(S=n==null?void 0:n.launcher)!=null?S:{},s=o.position&&gr[o.position]?gr[o.position]:gr["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((z=(P=n==null?void 0:n.launcher)==null?void 0:P.zIndex)!=null?z:xn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(U=n==null?void 0:n.launcher)==null?void 0:U.width)!=null?k:n==null?void 0:n.launcherWidth,c=d!=null?d:Qr;return l.style.width=c,l.style.maxWidth=c,a.appendChild(l),{wrapper:a,panel:l}},vy=(n,e)=>{var B,I,S,P,z,U,k,_,O;let t=v("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}=oi(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=(S=(I=(B=n==null?void 0:n.launcher)==null?void 0:B.clearChat)==null?void 0:I.enabled)!=null?S:!0,a=null,l=null;if(s){let Z=si(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,l=Z.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.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 u=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(z=(P=n==null?void 0:n.copy)==null?void 0:P.welcomeTitle)!=null?z:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(U=n==null?void 0:n.copy)==null?void 0:U.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),h=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},u,g),m=v("div","persona-flex persona-flex-col persona-gap-3"),y=(_=n==null?void 0:n.layout)==null?void 0:_.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((O=n==null?void 0:n.copy)==null?void 0:O.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let T=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"}}),W=Zm({config:n}),{root:E,textNode:H}=Ym();return t.append(d,o,c,T),l&&t.appendChild(l),{container:t,body:c,messagesWrapper:m,composerOverlay:T,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:u,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:E,peekTextNode:H}},tg=(n,e=!0)=>{var T,W,E,H,B,I,S,P,z;if(pa(n))return vy(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=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=((W=n==null?void 0:n.layout)==null?void 0:W.showHeader)!==!1,s=r?ai(n,r,{showClose:e}):Vo({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 l=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(E=n==null?void 0:n.copy)==null?void 0:E.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(B=n==null?void 0:n.copy)==null?void 0:B.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:hn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},l,d),u=v("div","persona-flex persona-flex-col persona-gap-3"),g=(S=n==null?void 0:n.layout)==null?void 0:S.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((P=n==null?void 0:n.copy)==null?void 0:P.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=mi({config:n}),y=((z=n==null?void 0:n.layout)==null?void 0:z.showFooter)!==!1;o?ua(t,s,n):(s.header.style.display="none",ua(t,s,n)),t.append(a);let w=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 y||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:u,composerOverlay:w,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:l,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 il=(n,e)=>{let t=v("button");t.type="button",t.innerHTML=`
18
+ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]}),Yd=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Zd=t=>er(t)||t===Dn,wa=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ts(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(er(n.name)||n.name===Dn&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.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:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Zr(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,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(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Ji().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Xi(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=cr.isSupported()?new cr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return Ji().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=lr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!qg(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new Zr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=e,f={id:a??(n==="user"?ga():n==="assistant"?ar():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:w,rawContent:f}=o,x={id:p??(r==="user"?ga():r==="assistant"?ar():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...w!==void 0&&{voiceProcessing:w},...f!==void 0&&{rawContent:f}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:p}=e,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ga(),s=ar();this.activeAssistantMessageId=null;let a={id:r,role:"user",content:o||ma,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let l=new AbortController;this.abortController=l;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:l.signal,assistantMessageId:s},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let c=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!c){let u=Yi(d,this.config.errorMessage);if(u){let w={id:s,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(w)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=ar();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Yi(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):c=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let w=await c.json().catch(()=>null);throw new Error(w?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(c=>c.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=e.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let w=typeof u[0]?.question=="string"?u[0].question:"";w&&(a={[w]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,w])=>`${u}: ${Array.isArray(w)?w.join(", "):w}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,w)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let b=c[f],x=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${w}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${w}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==Dn?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${e}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let w=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Dn)return{dedupeKey:u,resumeKey:f,output:zi(),toolMessage:p,startedAt:w,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let x=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),P;if(!x)P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{P=await x}catch(W){let M=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));return M||this.callbacks.onError?.(W instanceof Error?W:new Error(String(W))),this.markWebMcpToolComplete(p,ns(M?"Aborted by cancel()":Yd(W)),w),this.webMcpInflightKeys.delete(u),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,ns("Aborted by cancel()"),w),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:P,toolMessage:p,startedAt:w,completedAt:Date.now()}})),l=[];try{if(l=a.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(e,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Dn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,ns("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(x){this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===Dn,c=e.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),w="execute",f=a;try{let b;if(d?b=zi():u?b=await u:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,ns("Aborted by cancel()"),a);return}let x=e.agentMetadata?.webMcpToolCallId??o;w="resume",await this.resumeWithToolOutput(n,x,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,b,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let x=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(w==="execute"||x||p.aborted)&&this.markWebMcpToolComplete(e,ns(x||p.aborted?"Aborted by cancel()":Yd(b)),a),x||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=Lo(this.config.features?.artifacts,e.artifactType),r=sa(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){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:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Jd(),Qd)).then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Yi(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=ar(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=Qi(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return ya(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=Qi(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&Zd(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),w=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&Zd(f)&&r.toolCall?.status==="complete";(u||w||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};var A=require("lucide"),Vg={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,"code-xml":A.CodeXml,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ie=(t,e=24,n="currentColor",o=2)=>{let r=Vg[t];return r?Kg(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Kg(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var xa={allowedTypes:Fn,maxFileSize:10*1024*1024,maxFiles:4};function Gg(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Xg(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var os=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??xa.allowedTypes,maxFileSize:e.maxFileSize??xa.maxFileSize,maxFiles:e.maxFiles??xa.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:xa.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){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=_d(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Od(n),s=ha(n)?URL.createObjectURL(n):null,a={id:Gg(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=ha(e.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let a=m("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",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let l=Xg(e.file.type),p=ie(l,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=$d(e.file.type,e.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};var ep=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function rs(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];ep(s)&&ep(r)?n[o]=rs(s,r):n[o]=r}return n}var Nn="min(440px, calc(100vw - 24px))",np="440px",Qg={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:Nn,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)"},pt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Qg,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function tp(t,e){if(!(!t&&!e))return t?e?rs(t,e):t:e}function op(t){return t?{...pt,...t,theme:tp(pt.theme,t.theme),darkTheme:tp(pt.darkTheme,t.darkTheme),launcher:{...pt.launcher,...t.launcher,dock:{...pt.launcher?.dock,...t.launcher?.dock},clearChat:{...pt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...pt.copy,...t.copy},sendButton:{...pt.sendButton,...t.sendButton},statusIndicator:{...pt.statusIndicator,...t.statusIndicator},voiceRecognition:{...pt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=pt.features?.artifacts,n=t.features?.artifacts,o=pt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=pt.features?.scrollBehavior,a=t.features?.scrollBehavior,l=pt.features?.streamAnimation,p=t.features?.streamAnimation,d=pt.features?.askUserQuestion,c=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},w=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},b=l===void 0&&p===void 0?void 0:{...l,...p},x=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...pt.features,...t.features,...w!==void 0?{scrollToBottom:w}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...b!==void 0?{streamAnimation:b}:{},...x!==void 0?{askUserQuestion:x}:{}}})(),suggestionChips:t.suggestionChips??pt.suggestionChips,suggestionChipsConfig:{...pt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...pt.layout,...t.layout,header:{...pt.layout?.header,...t.layout?.header},messages:{...pt.layout?.messages,...t.layout?.messages,avatar:{...pt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...pt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...pt.layout?.slots,...t.layout?.slots}},markdown:{...pt.markdown,...t.markdown,options:{...pt.markdown?.options,...t.markdown?.options}},messageActions:{...pt.messageActions,...t.messageActions}}:pt}var Ca="16px",Aa="transparent",Jg={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"}},Yg={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"}},Zg={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:Nn,maxWidth:np,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ca,canvasBackground:Aa},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Gt(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(t,o):o}function rp(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let p=Gt(t,a);p!==void 0&&(e[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function em(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function sp(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=sp(s,r):n[o]=r}return n}function tm(t,e){return e?sp(t,e):t}function Bo(t,e={}){let n={palette:Jg,semantic:Yg,components:Zg},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:tm(n.components,t?.components)};if(e.validate!==!1){let r=em(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function ap(t){let e=rp(t),n={};for(let[C,V]of Object.entries(e)){let Y=C.replace(/\./g,"-");n[`--persona-${Y}`]=V.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Ca,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Aa,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let r=t.components?.introCard;n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??n["--persona-surface"],n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=r?.shadow??n["--persona-components-introCard-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let l=n["--persona-components-markdown-heading-h2-fontSize"];l&&(n["--persona-md-h2-size"]=l);let p=n["--persona-components-markdown-heading-h2-fontWeight"];p&&(n["--persona-md-h2-weight"]=p);let d=n["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(n["--persona-md-prose-font-family"]=d),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=t.components,u=c?.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let w=c?.labelButton;w&&(w.background&&(n["--persona-label-btn-bg"]=w.background),w.border&&(n["--persona-label-btn-border"]=w.border),w.color&&(n["--persona-label-btn-color"]=w.color),w.padding&&(n["--persona-label-btn-padding"]=w.padding),w.borderRadius&&(n["--persona-label-btn-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-label-btn-hover-bg"]=w.hoverBackground),w.fontSize&&(n["--persona-label-btn-font-size"]=w.fontSize),w.gap&&(n["--persona-label-btn-gap"]=w.gap));let f=c?.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let b=c?.artifact;if(b?.toolbar){let C=b.toolbar;C.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=C.iconHoverColor),C.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=C.iconHoverBackground),C.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=C.iconPadding),C.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=C.iconBorderRadius),C.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=C.iconBorder),C.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=C.toggleGroupGap),C.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=C.toggleBorderRadius),C.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=C.toggleGroupPadding),C.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=C.toggleGroupBorder),C.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=C.toggleGroupBorderRadius),C.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(t,C.toggleGroupBackground)??C.toggleGroupBackground),C.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=C.copyBackground),C.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=C.copyBorder),C.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=C.copyColor),C.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=C.copyBorderRadius),C.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=C.copyPadding),C.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=C.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??C.copyMenuBackground),C.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=C.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??C.copyMenuBorder),C.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=C.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??C.copyMenuShadow),C.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=C.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??C.copyMenuBorderRadius),C.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=C.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??C.copyMenuItemHoverBackground),C.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=C.iconBackground),C.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=C.toolbarBorder)}if(b?.tab){let C=b.tab;C.background&&(n["--persona-artifact-tab-bg"]=C.background),C.activeBackground&&(n["--persona-artifact-tab-active-bg"]=C.activeBackground),C.activeBorder&&(n["--persona-artifact-tab-active-border"]=C.activeBorder),C.borderRadius&&(n["--persona-artifact-tab-radius"]=C.borderRadius),C.textColor&&(n["--persona-artifact-tab-color"]=C.textColor),C.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=C.hoverBackground),C.listBackground&&(n["--persona-artifact-tab-list-bg"]=C.listBackground),C.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=C.listBorderColor),C.listPadding&&(n["--persona-artifact-tab-list-padding"]=C.listPadding)}if(b?.pane){let C=b.pane;if(C.toolbarBackground){let V=Gt(t,C.toolbarBackground)??C.toolbarBackground;n["--persona-artifact-toolbar-bg"]=V}}if(b?.card){let C=b.card;C.background&&(n["--persona-artifact-card-bg"]=C.background),C.border&&(n["--persona-artifact-card-border"]=C.border),C.borderRadius&&(n["--persona-artifact-card-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=C.hoverBackground),C.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=C.hoverBorderColor)}if(b?.inline){let C=b.inline;C.background&&(n["--persona-artifact-inline-bg"]=Gt(t,C.background)??C.background),C.border&&(n["--persona-artifact-inline-border"]=C.border),C.borderRadius&&(n["--persona-artifact-inline-radius"]=C.borderRadius),C.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(t,C.chromeBackground)??C.chromeBackground),C.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(t,C.chromeBorder)??C.chromeBorder),C.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(t,C.titleColor)??C.titleColor),C.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(t,C.mutedColor)??C.mutedColor),C.frameHeight&&(n["--persona-artifact-inline-frame-height"]=C.frameHeight)}let x=c?.code;x&&(x.keywordColor&&(n["--persona-code-keyword-color"]=x.keywordColor),x.stringColor&&(n["--persona-code-string-color"]=x.stringColor),x.commentColor&&(n["--persona-code-comment-color"]=x.commentColor),x.numberColor&&(n["--persona-code-number-color"]=x.numberColor),x.tagColor&&(n["--persona-code-tag-color"]=x.tagColor),x.attrColor&&(n["--persona-code-attr-color"]=x.attrColor),x.propertyColor&&(n["--persona-code-property-color"]=x.propertyColor),x.lineNumberColor&&(n["--persona-code-line-number-color"]=x.lineNumberColor),x.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=x.gutterBorderColor),x.background&&(n["--persona-code-bg"]=Gt(t,x.background)??x.background));let P=n["--persona-surface"],W=n["--persona-container"],M=n["--persona-palette-colors-gray-100"]??"#f3f4f6",R=n["--persona-palette-colors-gray-200"]??"#e5e7eb",D=n["--persona-palette-colors-gray-300"]??"#d1d5db",$=!W||W===P,j=$?M:W,z=$?R:W;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??j,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??z,$&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??D),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??j,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??j,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??j,n}var nm={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"}}},ip=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Zi=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",om=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Zi()},lp=t=>om(t),rm=t=>Bo(t),sm=t=>{let e=Bo(void 0,{validate:!1});return Bo({...t,palette:{...e.palette,colors:{...nm.colors,...t?.palette?.colors}}},{validate:!1})},dr=t=>{let e=lp(t),n=ip(t?.theme),o=ip(t?.darkTheme);return e==="dark"?sm(rs(n??{},o??{})):rm(n)},am=t=>ap(t),ss=(t,e)=>{let n=dr(e),o=am(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",lp(e))},Sa=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Zi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Zi());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};function Mn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function cp(t){let e=Mn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Ta(t){if(typeof t!="string")return"";let e=t.indexOf(`
19
+ `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
20
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function as(t){let e=cp(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function oo(t){switch(as(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=cp(t.path);return e?e.toUpperCase():"File"}}}function dp(t){let e=t.markdown??"";return t.file?{filename:Mn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Ta(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}var el="http://www.w3.org/2000/svg";function pp(t){let e=document.createElementNS(el,"svg");e.setAttribute("class",Po("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(el,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(el,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}var ro=(t,e,n)=>{let o=n;for(let r of e){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function up(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),ro(t,e,0)}var tl="persona-artifact-status-label",fp="persona-artifact-status-detail",gp="data-artifact-status-label",nl=new Map,mp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function pr(t){t&&nl.delete(t)}function im(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?oo(e):t.artifactType==="component"?"Component":"Document"}function ur(t,e,n){let o=im(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=nl.get(a);t.status!=="complete"&&l===void 0&&(l=mp(),nl.set(a,l));let p=l===void 0?0:Math.max(0,mp()-l),d=t.artifactType==="component",c=!d&&typeof t.markdown=="string"?t.markdown:"",u=d?0:c.length,w=d||c===""?0:c.split(`
21
+ `).length,f=t.artifactType==="markdown"?t.file:void 0,b={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:w,elapsedMs:p,content:()=>d?"":c,surface:n};try{let x=s(b);return typeof x=="string"?{label:x}:x&&typeof x=="object"&&typeof x.label=="string"?{label:x.label,detail:typeof x.detail=="string"?x.detail:void 0}:{label:r}}catch{return{label:r}}}function lm(t){t.className=tl,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function Ho(t,e,n){let o=t.querySelector(`:scope > .${tl}`);o||(o=m("span",tl),t.appendChild(o)),o.getAttribute(gp)!==e.label&&(lm(o),up(o,e.label,n),o.setAttribute(gp,e.label));let r=t.querySelector(`:scope > .${fp}`),s=e.detail;s?(r||(r=m("span",fp),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var cm={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},dm=15e4,Ma={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function pm(t,e){let n=(t||"").trim().toLowerCase();if(n&&Ma[n])return Ma[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Ma[r])return Ma[r]}}return null}function Ea(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}var um=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),fm=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>um.has(t)?"keyword":"plain"}];function hp(t){return Ea(t,fm)}var gm=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function mm(t){let e=Ea(t,gm);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var hm=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function yp(t){let e=Ea(t,hm),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var ym=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function bm(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,p=t.slice(r,l);for(let c of Ea(p,ym))e.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),w=new RegExp("</\\s*"+c+"\\s*>","i").exec(t.slice(r)),f=w?r+w.index:o,b=t.slice(r,f),x=c==="script"?hp(b):yp(b);for(let P of x)e.push(P);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function vm(t,e){switch(e){case"html":return bm(t);case"css":return yp(t);case"js":return hp(t);case"json":return mm(t)}}function wm(t){let e=gd(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=cm[r];if(a){let l=m("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
22
+ `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
23
+ `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function bp(t,e,n){let o=t.length<=dm?pm(e,n):null,r=o?vm(t,o):[{type:"plain",value:t}];return wm(r)}var Wt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},zt=1e5,so=zt+1;function fr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(so)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of e){if(f.dividerBefore){let P=document.createElement("hr");a.appendChild(P)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",f.id),f.destructive&&b.setAttribute("data-destructive",""),f.icon){let P=ie(f.icon,16,"currentColor",1.5);P&&b.appendChild(P)}let x=document.createElement("span");x.textContent=f.label,b.appendChild(x),b.addEventListener("click",P=>{P.stopPropagation(),c(),n(f.id)}),a.appendChild(b)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=b=>{!a.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),l?.(),l=null}function u(){a.classList.contains("persona-hidden")?d():c()}function w(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:w}}function Bt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ie(e,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),l)for(let[c,u]of Object.entries(l))p.setAttribute(c,u);return p}function Do(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:p}=t,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),e){let w=ie(e,s??14,"currentColor",2);w&&c.appendChild(w)}let u=m("span");if(u.textContent=n,c.appendChild(u),l&&c.addEventListener("click",l),p)for(let[w,f]of Object.entries(p))c.setAttribute(w,f);return c}function ka(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of e){let u;c.icon?u=Bt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),l.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function vp(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:p}=t,d=m("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",e);let c=m("span","persona-combo-btn-label");c.textContent=e,d.appendChild(c);let u=ie(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let w=fr({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(w.element),d.addEventListener("click",f=>{f.stopPropagation();let b=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),w.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),w.show()},close:()=>{d.setAttribute("aria-expanded","false"),w.hide()},toggle:()=>{let f=!w.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),w.toggle()},destroy:()=>{w.destroy(),d.remove()}}}var La="persona-artifact-custom-action-btn";function gr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+La+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+La+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=m("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Do({icon:t.icon,label:t.label,className:La+(n?" persona-artifact-doc-copy-btn":"")}):o=Bt({icon:t.icon,label:t.label,className:La+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function is(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function wp(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Mn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=n?oo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let w=document.createElement("div");w.className="persona-truncate persona-text-sm persona-font-medium",w.style.color="var(--persona-text, #1f2937)",w.textContent=r;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)",a==="streaming"){let b=e?.config?.features?.artifacts,x={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},P=ur(x,b,"card");Ho(f,P,b)}else s&&pr(s),f.textContent=p;if(u.append(w,f),d.append(c,u),a==="complete"){let b=e?.config?.features?.artifacts?.cardActions;if(b&&b.length>0){let P={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let W of b)try{if(W.visible===void 0||W.visible(P)){let M=gr(W);M.setAttribute("data-artifact-custom-action",W.id),M.className=`${M.className} persona-flex-shrink-0`,d.append(M)}}catch{}}let x=Do({label:"Download",className:"persona-flex-shrink-0"});x.title=`Download ${r}`,x.setAttribute("data-download-artifact",s),d.append(x)}return d}var Pa=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>wp(t,e)});if(l)return l}return wp(t,e)};var ao=new WeakMap;function ol(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=ao.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Tp(t){return ao.has(t)}function xm(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete";if(t.artifactType==="component"){let s=t.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:a}}let r=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...r?{file:r}:{}}}function xp(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Mn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?oo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Cm(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var Cp=180,Am=240,Sm=.8,Tm=300,Mm=500,Em="cubic-bezier(0.2, 0, 0, 1)",Ap=240,km=.35;function Lm(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:Cp,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let W of a)W.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let d=Math.abs(e-p),c=Math.round(Math.min(Mm,Math.max(Tm,Am+d*Sm))),u=Math.round(c*km),w=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=w?w.animate([{opacity:0},{opacity:1}],{duration:Ap,delay:u,easing:"ease-out",fill:"backwards"}):null,b=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:c,easing:Em});t.style.height=`${p}px`;let x=!1,P=()=>{x||(x=!0,l(),r())};Promise.allSettled([b.finished,f?.finished].filter(Boolean)).then(P),window.setTimeout(P,Math.max(c,u+Ap)+120)},Cp)}function Pm(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var ls="--persona-artifact-inline-body-height";function Im(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,d,c,u=e?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let w=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:w,completeDisplay:f}}function Sp(t,e){let n=xm(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=Pm(o),p=o?.inlineActions??[],d=Im(o),c=d.completeDisplay==="card",u=null,w=n,f=m("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let b=Z=>Pa(Cm(Z),e),x=Z=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ls),f.replaceChildren(b(Z)),ao.set(f,ce=>{f.replaceChildren(b(ce))})};if(c&&n.status==="complete")return x(n),f;let P=Ia(n,{config:e.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),W=m("div","persona-artifact-inline-body");W.appendChild(P.el);let M=Z=>{let ce=Z.status!=="complete",ee=ce?d.streamingHeight:d.completeHeight,ve=typeof ee=="number";ve?f.style.setProperty(ls,`${ee}px`):f.style.removeProperty(ls);let we=!!P.el.querySelector(".persona-code-pre"),ge=!!P.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");W.classList.toggle("persona-artifact-content-flush",we),W.classList.toggle("persona-artifact-inline-body--sized",ve&&ge),W.classList.toggle("persona-artifact-inline-body--cap",!ce&&!ge&&typeof d.completeHeight=="number")},R=n.status,D=(Z,ce)=>{R!=="complete"&&Z.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(ls,`${d.completeHeight}px`):f.style.removeProperty(ls),Ep(W,ce?.suppressTransition?"none":d.transition,Z.id,()=>{P.update(Z),M(Z)})):P.update(Z),M(Z),R=Z.status};M(n);let $=d.overflow==="clip"&&a&&!!n.id;if($&&(W.setAttribute("data-expand-artifact-inline",n.id),W.setAttribute("role","button"),W.setAttribute("tabindex","0"),W.classList.add("persona-cursor-pointer"),W.setAttribute("aria-label",`Open ${xp(n).title} in panel`)),!r)return f.appendChild(W),ao.set(f,D),f;let j=m("div","persona-artifact-inline-chrome");j.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let z=m("div","persona-artifact-inline-chrome-lead"),C=m("span","persona-flex persona-items-center persona-flex-shrink-0"),V=ie("file-text",16,"currentColor",2);V&&C.appendChild(V);let Y=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),F=m("span","persona-artifact-inline-type");z.append(C,Y,F);let U=m("div","persona-artifact-inline-chrome-actions"),de=m("span","persona-flex persona-items-center persona-gap-1"),ye=()=>u??d.viewMode,Ee=l?ka({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ye(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Z=>{let ce=Z==="source"?"source":"rendered";ce!==ye()&&(u=ce,P.update(w),M(w))}}):null,Ae=s?Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ae&&n.id&&Ae.setAttribute("data-copy-artifact",n.id);let ne=a?Bt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-expand-artifact-inline",n.id),U.appendChild(de),Ee&&U.appendChild(Ee.element),Ae&&U.appendChild(Ae),ne&&U.appendChild(ne),j.append(z,U),f.append(j,W);let me=Z=>{let{title:ce,typeLabel:ee}=xp(Z);Y.textContent=ce,Y.title=ce,$&&W.setAttribute("aria-label",`Open ${ce} in panel`);let ve=Z.status!=="complete";if(ve){F.classList.contains("persona-artifact-inline-status")||(F.className="persona-artifact-inline-status",F.removeAttribute("data-preserve-animation"),F.replaceChildren());let we=ur(Z,o,"inline-chrome");Ho(F,we,o)}else pr(Z.id),F.className="persona-artifact-inline-type",F.removeAttribute("data-preserve-animation"),F.replaceChildren(),F.textContent=ee;if(Ae&&Ae.classList.toggle("persona-hidden",ve),Ee){let we=Z.artifactType==="markdown"?Z.file:void 0,ge=!1;if(!ve&&we&&d.viewMode!=="source"){let Me=as(we);Me==="markdown"?ge=!0:(Me==="html"||Me==="svg")&&(ge=o?.filePreview?.enabled!==!1)}Ee.element.classList.toggle("persona-hidden",!ge),Ee.setSelected(ye())}if(de.replaceChildren(),!ve&&p.length>0){let we=is(Z);if(we)for(let ge of p)try{if(ge.visible===void 0||ge.visible(we)){let Me=gr(ge,{documentChrome:!0});Me.setAttribute("data-artifact-custom-action",ge.id),Me.classList.add("persona-flex-shrink-0"),de.appendChild(Me)}}catch{}}};return me(n),ao.set(f,(Z,ce)=>{if(c&&R!=="complete"&&Z.status==="complete"){let ee=f.isConnected?f.getBoundingClientRect().height:0;R="complete";let ve=Z,we=!1,ge=Me=>{ve=Me,we=!0};ao.set(f,ge),Lm(f,ee,{swap:()=>{x(ve),we=!1,ao.set(f,ge)},onSettled:()=>{we?x(ve):ao.set(f,Me=>{f.replaceChildren(b(Me))})}});return}(Z.status!=="complete"||Z.id!==w.id)&&(u=null),w=Z,D(Z,ce),me(Z)}),f}var Mp=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>Sp(t,e)});if(l)return l}return Sp(t,e)};var rl=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},On=new rl;On.register("PersonaArtifactCard",Pa,{bubbleChrome:!1});On.register("PersonaArtifactInline",Mp,{bubbleChrome:!1});function cs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Ta(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var sl=!1;function Rm(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ep(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||sl||s){o();return}sl=!0;let a=Rm(n);t.style.setProperty("view-transition-name",a);let l=()=>{sl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Wm="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Bm="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Hm(t){let e=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function Dm(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var Fm=220;function Nm(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Om(t){return`
24
+ <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function _m(t,e,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(pp());let s=null;return n.label!==!1&&(s=m("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function $m(t,e,n,o,r,s){let a=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(R=>clearTimeout(R)),d.clear()},u=(R,D)=>{let $=setTimeout(()=>{d.delete($),R()},D);d.add($)},w=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let R=_m(r,s,o);a=R.el,t.appendChild(a),l=Date.now(),o.label!==!1&&u(R.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(w,Fm))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",W):e.removeEventListener("load",M)},P=()=>{if(p||(p=!0,x(),c(),!a))return;let R=Math.max(0,o.minVisibleMs-(Date.now()-l));R>0?u(b,R):b()};function W(R){if(n===null)return;let D=R.data;!D||D.persona!=="artifact-preview-ready"||D.token!==n||R.source===e.contentWindow&&P()}function M(){let R=D=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>D()):setTimeout(D,0)};R(()=>R(()=>P()))}return u(f,o.delayMs),u(P,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",W):e.addEventListener("load",M),()=>{p=!0,c(),x(),w()}}function Ia(t,e){let{config:n}=e,o=e.registry??On,r=e.bodyLayout,s=n.markdown?ta(n.markdown):null,a=na(n.sanitize),l=t,p=!1,d=ne=>{let me=Bn()!==null;s&&!me&&!p&&(p=!0,ea(()=>Ae(l)));let Z=s?s(ne):Yn(ne);return s&&me&&a?a(Z):Z},c=m("div","persona-artifact-preview-body"),u=null,w=null,f=null,b=()=>{f&&(f(),f=null),u=null,w=null},x=null,P=null,W=null,M=!1,R=()=>{x=null,P=null,W=null,M=!1},D=null,$=null,j=()=>{D=null,$=null},z=40,C=0,V=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),Y=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=z,F=ne=>{if(!r)return;let me=ne.scrollHeight-ne.clientHeight>1,Z=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&me&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&me&&Z>1)},U=ne=>{C||(C=V(()=>{C=0,ne.scrollTop=ne.scrollHeight,F(ne)}))},de=(ne,me,Z,ce)=>{let ee=!!r,ve=Z.id+"|"+(ee?"w":"p");if(!x||W!==ve||x.parentElement!==c){b(),j(),c.replaceChildren();let Me=m("pre",Wm+" persona-code-pre"),Se=m("code","persona-code");if(Me.appendChild(Se),ee){let je=m("div","persona-artifact-source-window");if(je.appendChild(Me),c.appendChild(je),!(r?.overflow==="clip")&&typeof je.addEventListener=="function"){let Ie=()=>je.scrollHeight-je.clientHeight>1;je.addEventListener("scroll",()=>{Y(je)&&(M=!1),F(je)},{passive:!0}),je.addEventListener("wheel",Be=>{Ie()&&Be.deltaY<0&&(M=!0)},{passive:!0}),je.addEventListener("touchmove",()=>{Ie()&&(M=!0)},{passive:!0})}x=je}else c.appendChild(Me),x=Me;P=Se,W=ve}let we=ee?x:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",ce),we.classList.toggle("persona-artifact-source-window--clip",ce&&r?.overflow==="clip"));let ge=we?Y(we):!0;if(P.replaceChildren(bp(ne,me?.language,me?.path)),we){let Me=Z.status!=="complete";ce&&Me&&r?.followOutput&&!M&&ge?U(we):Me||(M=!1),F(we)}},ye=ne=>{b(),R(),j(),c.replaceChildren();let me=m("div",Bm);me.innerHTML=d(ne),c.appendChild(me)},Ee=ne=>{let me=ne.id,Z=n.features?.artifacts,ce=ur(ne,Z,"status-body");if(D&&$===me&&D.parentElement===c){let we=D.querySelector(".persona-artifact-status-view-text");we&&Ho(we,ce,Z);return}b(),R(),c.replaceChildren();let ee=m("div","persona-artifact-status-view"),ve=m("div","persona-artifact-status-view-text");Ho(ve,ce,Z),ee.appendChild(ve),c.appendChild(ee),D=ee,$=me},Ae=ne=>{l=ne;let me=e.resolveViewMode?.(ne)??r?.viewMode??"rendered",Z=ne.artifactType==="markdown"?ne.file:void 0,ce=ne.status!=="complete";ce||pr(ne.id);let ee=ce?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&ce){Ee(ne);return}if(Z){let ge=Ta(ne.markdown??""),Me=as(Z),Se=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&me==="rendered"&&Se&&(Me==="html"||Me==="svg")){let Ne=ne.id+"\0"+ge;if(u&&w===Ne&&u.parentElement===c)return;R(),j(),b(),c.replaceChildren();let Ie=n.features?.artifacts?.filePreview,Be=Ie?.iframeSandbox??"allow-scripts";!Ie?.dangerouslyAllowSameOrigin&&Be.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Be=Be.split(/\s+/).filter(kt=>kt&&kt!=="allow-same-origin").join(" "));let it=Dm(Ie?.loading),_e=m("div","persona-artifact-frame"),Qe=m("iframe","persona-artifact-iframe");Qe.setAttribute("sandbox",Be),Qe.setAttribute("data-artifact-id",ne.id);let an=null;it.enabled&&it.injectReadySignal?(an=Nm(),Qe.srcdoc=ge+Om(an)):Qe.srcdoc=ge,_e.appendChild(Qe),c.appendChild(_e),it.enabled&&(f=$m(_e,Qe,an,it,ne.id,n)),u=_e,w=Ne;return}if(b(),!ce&&Me==="markdown"&&me==="rendered"){ye(ge);return}de(ge,{language:Z.language,path:Z.path},ne,ve);return}if(ne.artifactType==="markdown"){if(me==="source"){b(),de(ne.markdown??"",void 0,ne,ve);return}ye(ne.markdown??"");return}b(),R(),j(),c.replaceChildren();let we=ne.component?o.get(ne.component):void 0;if(we){let Me={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Se=we(ne.props??{},Me);if(Se){c.appendChild(Se);return}}catch{}}c.appendChild(Hm(ne))};return Ae(t),{el:c,update(ne){Ae(ne)}}}var kp=require("idiomorph"),Ra=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;kp.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var Lp=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Wa={index:-1,draft:""};function Pp(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Wa}}}function Ip(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Rp(){return new Map}function Wp(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Bp(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function Hp(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Ba(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function En(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function io(t,e){return En(t)-t.scrollTop<=e}function Ha(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=t,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!e&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:e&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function Da(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function Dp(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Fp(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function Np(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var ds={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Um=["pre","code","a","script","style"],Fa=t=>({type:t?.type??ds.type,placeholder:t?.placeholder??ds.placeholder,speed:t?.speed??ds.speed,duration:t?.duration??ds.duration,buffer:t?.buffer??ds.buffer}),zm=[{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"}],_p=new Map;for(let t of zm)_p.set(t.name,t);var mr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:_p.get(t)??null,Na=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
25
+ `);return s<0?"":t.slice(0,s)}return t},jm=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},qm=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},al=/\s/,Vm=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Km=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(al.test(s[l])){let p=l;for(;p<s.length&&al.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<s.length&&!al.test(s[d]);)p.appendChild(jm(o,s[d],e,n.value)),n.value+=1,d+=1;a.appendChild(p),l=d}r.replaceChild(a,t)},Gm=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(qm(o,p,e,n.value)),n.value+=1));r.replaceChild(a,t)},ps=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??Um).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=a.nextNode();for(;p;)Vm(p,s)||l.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=e==="char"?Km:Gm;for(let u of l)c(u,n,d);return r.innerHTML},Oa=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},us=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Op=new WeakMap,Xm=(t,e)=>{if(!t.styles)return;let n=Op.get(e);if(n||(n=new Set,Op.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},il=new WeakMap,Qm=(t,e)=>{if(!t.onAttach)return;let n=il.get(e);if(n||(n=new Map,il.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},$p=t=>{let e=il.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},_a=(t,e)=>{Xm(t,e),Qm(t,e)};function ll(t,e=zt){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var fs=0,lo=null;function cl(t=document){if(fs++,fs===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;lo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,fs=Math.max(0,fs-1),fs===0&&lo)){let n=t.body,o=t.defaultView??window;n.style.overflow=lo.originalOverflow,n.style.position=lo.originalPosition,n.style.top=lo.originalTop,n.style.width=lo.originalWidth,o.scrollTo(0,lo.scrollY),lo=null}}}var gs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ot=t=>(t?.launcher?.mountMode??"floating")==="docked",ms=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",fn=t=>{let e=t?.launcher?.dock;return{side:e?.side??gs.side,width:e?.width??gs.width,animate:e?.animate??gs.animate,reveal:e?.reveal??gs.reveal,maxHeight:e?.maxHeight??gs.maxHeight}};var xn={"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 Jm="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",$a=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Jm,buttonSize:r,iconSize:s="28px"}=e,a=t?.launcher??{},l=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",w=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=ot("button",{className:Po("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:a.closeButtonColor||Xt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=ie(u,s,"currentColor",1);if(x?(x.style.display="block",b.appendChild(x)):b.textContent=w,p.appendChild(b),c&&d){let P=null,W=()=>{if(P)return;let R=b.ownerDocument,D=R.body;if(!D)return;P=Tn(R,"div","persona-clear-chat-tooltip"),P.textContent=d;let $=Tn(R,"div");$.className="persona-clear-chat-tooltip-arrow",P.appendChild($);let j=b.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(so),P.style.left=`${j.left+j.width/2}px`,P.style.top=`${j.top-8}px`,P.style.transform="translate(-50%, -100%)",D.appendChild(P)},M=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};p.addEventListener("mouseenter",W),p.addEventListener("mouseleave",M),b.addEventListener("focus",W),b.addEventListener("blur",M),p._cleanupTooltip=()=>{M(),p.removeEventListener("mouseenter",W),p.removeEventListener("mouseleave",M),b.removeEventListener("focus",W),b.removeEventListener("blur",M)}}return{button:b,wrapper:p}},Ym="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ua=(t,e={})=>{let{wrapperClassName:n=Ym,buttonSize:o,iconSize:r="20px"}=e,a=(t?.launcher??{}).clearChat??{},l=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",w=a.borderColor??"",f=a.borderRadius??"",b=a.paddingX??"",x=a.paddingY??"",P=a.tooltipText??"Clear chat",W=a.showTooltip??!0,M=m("div",n),R=!!(u||w),D=ot("button",{className:Po("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!R&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":P},style:{height:l,width:l,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:R?`${u||"0px"} solid ${w||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),$=ie(p,r,"currentColor",1);if($&&($.style.display="block",D.appendChild($)),M.appendChild(D),W&&P){let j=null,z=()=>{if(j)return;let V=D.ownerDocument,Y=V.body;if(!Y)return;j=Tn(V,"div","persona-clear-chat-tooltip"),j.textContent=P;let F=Tn(V,"div");F.className="persona-clear-chat-tooltip-arrow",j.appendChild(F);let U=D.getBoundingClientRect();j.style.position="fixed",j.style.zIndex=String(so),j.style.left=`${U.left+U.width/2}px`,j.style.top=`${U.top-8}px`,j.style.transform="translate(-50%, -100%)",Y.appendChild(j)},C=()=>{j&&j.parentNode&&(j.parentNode.removeChild(j),j=null)};M.addEventListener("mouseenter",z),M.addEventListener("mouseleave",C),D.addEventListener("focus",z),D.addEventListener("blur",C),M._cleanupTooltip=()=>{C(),M.removeEventListener("mouseenter",z),M.removeEventListener("mouseleave",C),D.removeEventListener("focus",z),D.removeEventListener("blur",C)}}return{button:D,wrapper:M}};var Xt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Fo=t=>{let{config:e,showClose:n=!0}=t,o=ot("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,d=ot("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let $=parseFloat(s)||24,j=ie(p,$*.6,"currentColor",1);j?d.replaceChildren(j):d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let $=m("img");$.src=e.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=s,$.style.width=s,d.replaceChildren($)}else d.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=ot("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor}}),w=ot("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});c.append(u,w),l?o.append(c):o.append(d,c);let f=r.clearChat??{},b=f.enabled??!0,x=f.placement??"inline",P=null,W=null;if(b){let j=Ua(e,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});P=j.button,W=j.wrapper,x==="top-right"&&(W.style.right="48px"),x==="inline"&&o.appendChild(W)}let M=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:D}=$a(e,{showClose:n,wrapperClassName:M});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:w,closeButton:R,closeButtonWrapper:D,clearChatButton:P,clearChatButtonWrapper:W}},hs=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};var Zm=t=>{let e=Fo({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function eh(t,e,n){if(e?.length)for(let o of e){let r=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ie(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var th=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=vp({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),eh(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let R=r.onTitleClick;d.addEventListener("click",D=>{D.target.closest("button")||R()}),d.addEventListener("keydown",D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),R())})}let M=r?.titleRowHover;M&&(d.style.borderRadius=M.borderRadius??"10px",d.style.padding=M.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=M.background??"",d.style.borderColor=M.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let u=a.closeButtonSize??"32px",w=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Xt.actionIconColor;let b=a.closeButtonIconName??"x",x=ie(b,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",o&&f.addEventListener("click",o),w.appendChild(f),l.appendChild(w);let P=m("div");P.style.display="none";let W=m("span");return W.style.display="none",{header:l,iconHolder:P,headerTitle:c,headerSubtitle:W,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}},Up={default:Zm,minimal:th},nh=t=>Up[t]??Up.default,za=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=m("div");l.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=nh(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction: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=t=>{let e=m("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let a=parseFloat(e.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,r());e.style.height=`${a}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},qa=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",d=t?.copy?.stopButtonLabel??"Stop",c=e.showTooltip??!1,u=e.size??"40px",w=e.backgroundColor,f=e.textColor,b=m("div","persona-send-button-wrapper"),x=ot("button",{className:Po("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!w&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&w||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}}),P=null,W=null;if(n){let $=parseFloat(u)||24,j=f?.trim()||"currentColor";r?(P=ie(r,$,j,2),P?x.appendChild(P):x.textContent=o):x.textContent=o,W=ie(s,$,j,2)}else x.textContent=p;let M=null;c&&a&&(M=m("div","persona-send-button-tooltip"),M.textContent=a,b.appendChild(M)),x.setAttribute("aria-label",a),b.appendChild(x);let R="send";return{button:x,wrapper:b,setMode:$=>{if($===R)return;R=$;let j=$==="stop"?l:a;if(x.setAttribute("aria-label",j),M&&(M.textContent=j),n){if(P&&W){let z=$==="stop"?W:P;x.replaceChildren(z)}}else x.textContent=$==="stop"?d:p}}},Va=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??a,d=parseFloat(p)||24,c=e.backgroundColor??t?.sendButton?.backgroundColor,u=e.iconColor??t?.sendButton?.textColor,w=m("div","persona-send-button-wrapper"),f=ot("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:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||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=ie(l,d,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",w.appendChild(f);let P=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&P){let M=m("div","persona-send-button-tooltip");M.textContent=P,w.appendChild(M)}return{button:f,wrapper:w}},Ka=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??Fn).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,p=Math.round(l*.6),d=m("div","persona-send-button-wrapper"),c=ot("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":e.buttonTooltipText??"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"}});c.addEventListener("mouseenter",()=>{c.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="transparent"});let u=ie(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",b=>{b.preventDefault(),r.click()}),d.appendChild(c);let w=e.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=w,d.appendChild(f),{button:c,wrapper:d,input:r,previewsContainer:o}},Ga=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=m("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},Xa=()=>ot("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Qa=t=>{let{config:e}=t,n=ot("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=Xa(),r=ot("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 l=qa(e),p=Va(e),d=Ka(e),c=Ga(e);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=ot("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),w=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&w.append(d.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(w,f),r.append(u),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:w,rightActions:f,setSendButtonMode:l.setMode}};var zp=()=>{let t=ot("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=m("span","persona-pill-peek__icon"),n=ie("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=ie("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},jp=t=>{let{config:e}=t,n=ot("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Xa(),r=Ga(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=ja(e);s.style.maxHeight="100px",a();let l=qa(e),p=Va(e),d=Ka(e);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=ot("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let w=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&w.append(p.wrapper),w.append(l.wrapper),c.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,w),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:w,setSendButtonMode:l.setMode}};var qp=t=>{let e=t?.launcher?.enabled??!0,n=Ot(t);if(ms(t)){let c=t?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??zt);let w=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");w.style.width="100%",u.appendChild(w);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??zt),{wrapper:u,panel:w,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!e){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=t?.launcher?.width??"100%";return c.style.width=w,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=t?.launcher??{},s=r.position&&xn[r.position]?xn[r.position]:xn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??zt);let l=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=t?.launcher?.width??t?.launcherWidth??Nn;return l.style.width=d,l.style.maxWidth=d,a.appendChild(l),{wrapper:a,panel:l}},oh=(t,e)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=$a(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let D=Ua(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=D.button,l=D.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=ot("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=ot("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let c=ot("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=ot("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),w=ot("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},c,u),f=m("div","persona-flex persona-flex-col persona-gap-3"),b=t?.layout?.contentMaxWidth;b&&(f.style.maxWidth=b,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(w.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(w,f);let P=ot("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"}}),W=jp({config:t}),{root:M,textNode:R}=zp();return n.append(p,r,d,P),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:f,composerOverlay:P,suggestions:W.suggestions,textarea:W.textarea,sendButton:W.sendButton,sendButtonWrapper:W.sendButtonWrapper,micButton:W.micButton,micButtonWrapper:W.micButtonWrapper,composerForm:W.composerForm,statusText:W.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:W.footer,attachmentButton:W.attachmentButton,attachmentButtonWrapper:W.attachmentButtonWrapper,attachmentInput:W.attachmentInput,attachmentPreviewsContainer:W.attachmentPreviewsContainer,actionsRow:W.actionsRow,leftActions:W.leftActions,rightActions:W.rightActions,setSendButtonMode:W.setSendButtonMode,peekBanner:M,peekTextNode:R}},Vp=(t,e=!0)=>{if(ms(t))return oh(t,e);let n=ot("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?za(t,o,{showClose:e}):Fo({config:t,showClose:e}),a=ot("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 l=ot("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=ot("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=ot("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:Ot(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},l,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=Qa({config:t}),b=t?.layout?.showFooter!==!1;r?hs(n,s,t):(s.header.style.display="none",hs(n,s,t)),n.append(a);let x=ot("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 b||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:c,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var dl=(t,e)=>{let n=m("button");n.type="button",n.innerHTML=`
20
26
  <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>
21
27
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
28
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,14 +30,14 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
24
30
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
31
  </span>
26
32
  <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>
27
- `,t.addEventListener("click",e);let r=s=>{var H,B,I,S,P,z,U,k,_,O,Z,ke,pe;let a=(H=s.launcher)!=null?H:{},l=hn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ee=(B=a.title)!=null?B:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let g=t.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let ee=(S=a.agentIconSize)!=null?S:"40px";if(g.style.height=ee,g.style.width=ee,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let Pe=parseFloat(ee)||24,Ie=ye(a.agentIconName,Pe*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(g.appendChild(Ie),g.style.display=""):(g.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(z=a.agentIconText)!=null?z:"\u{1F4AC}",g.style.display="")}let h=t.querySelector("[data-role='launcher-image']");if(h){let ee=(U=a.agentIconSize)!=null?U:"40px";h.style.height=ee,h.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ee=(k=a.callToActionIconSize)!=null?k:"32px";m.style.height=ee,m.style.width=ee,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 Pe=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Pe=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",a.callToActionIconName){let Ie=parseFloat(ee)||24,ie=Math.max(Ie-Pe,8),he=ye(a.callToActionIconName,ie,"currentColor",2);he?m.appendChild(he):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let y=a.position&&gr[a.position]?gr[a.position]:gr["bottom-right"],w="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",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=l?T:`${w} ${y}`,l||(t.style.zIndex=String((Z=a.zIndex)!=null?Z:xn));let W="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=(ke=a.border)!=null?ke:W,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,l?(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=(pe=a.collapsedMaxWidth)!=null?pe:"",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 ng=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=eg(n),s=tg(n,e),a={wrapper:t,panel:r,pillRoot:o},l={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:l,header:d,composer:c,replaceHeader:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{c.footer.replaceWith(h),c.footer=h}}},ll=({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:()=>il(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=il(n,t);return{instance:o,element:o.element}};var wy=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}},xy=(n,e)=>{if(!n)return null;let t=wy(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},Cy=(n,e)=>{let t=v("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},Ay=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},cl=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(":"))},dl=320,og=320,Sy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Ty=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Ey=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),My=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),ky=(n,e,t)=>{if(n.length===0)return null;try{let r=v("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((l,d)=>{var g;let c=v("img");c.alt=((g=l.alt)==null?void 0:g.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=`${dl}px`,c.style.maxHeight=`${og}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Ay(l.image)?(c.src=l.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return t==null||t(),null}},Ly=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!cl(r.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${dl}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},Py=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!cl(r.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${dl}px`,o.style.maxHeight=`${og}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}},Iy=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!cl(r.data))return;let o=v("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}},ma=()=>{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},Ry=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:ma};if(e){let o=e(r);if(o!==null)return o}return ma()},Wy=(n,e)=>{let t=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=v("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},rg=(n,e,t="div")=>{let r=v(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},Hy=(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},By=(n,e,t)=>{var y,w,T,W,E,H,B;let r=(y=e.showCopy)!=null?y:!0,o=(w=e.showUpvote)!=null?w:!0,s=(T=e.showDownvote)!=null?T:!0,a=(W=e.showReadAloud)!=null?W:!1;if(!r&&!o&&!s&&!a){let I=v("div");return I.style.display="none",I.id=`actions-${n.id}`,I.setAttribute("data-actions-for",n.id),I}let l=(E=e.visibility)!=null?E:"hover",d=(H=e.align)!=null?H:"right",c=(B=e.layout)!=null?B:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],h=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);h.id=`actions-${n.id}`,h.setAttribute("data-actions-for",n.id);let m=(I,S,P)=>{let z=Cn({icon:I,label:S,size:14,className:"persona-message-action-btn"});return z.setAttribute("data-action",P),z};return r&&h.appendChild(m("copy","Copy message","copy")),a&&h.appendChild(m("volume-2","Read aloud","read-aloud")),o&&h.appendChild(m("thumbs-up","Upvote","upvote")),s&&h.appendChild(m("thumbs-down","Downvote","downvote")),h},pl=(n,e,t,r,o,s)=>{var re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me;let a=t!=null?t:{},l=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,u=(oe=d==null?void 0:d.show)!=null?oe:!1,g=(de=c==null?void 0:c.show)!=null?de:!1,h=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=($e=c==null?void 0:c.position)!=null?$e:"below",y=Hy(n.role,l),w=v("div",y.join(" "));w.id=`bubble-${n.id}`,w.setAttribute("data-message-id",n.id),w.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Sy(n),W=(J=(K=n.content)==null?void 0:K.trim())!=null?J:"",H=T.length>0&&W===$a,B=ei((Y=(Se=s==null?void 0:s.widgetConfig)==null?void 0:Se.features)==null?void 0:Y.streamAnimation),I=(Ye=(Te=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Te.streamAnimation)==null?void 0:Ye.plugins,S=n.role==="assistant"&&B.type!=="none"?Ss(B.type,I):null,P=n.role==="assistant"&&((tt=S==null?void 0:S.isAnimating)==null?void 0:tt.call(S,n))===!0,z=n.role==="assistant"&&S!==null&&(!!n.streaming||P);z&&(S!=null&&S.bubbleClass)&&w.classList.add(S.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),n.streaming&&U.classList.add("persona-content-streaming"),z&&S&&(S.containerClass&&U.classList.add(S.containerClass),U.style.setProperty("--persona-stream-step",`${B.speed}ms`),U.style.setProperty("--persona-stream-duration",`${B.duration}ms`));let k=z?ti((Wt=n.content)!=null?Wt:"",B.buffer,S,n,!!n.streaming):(ht=n.content)!=null?ht:"",_=e({text:k,message:n,streaming:!!n.streaming,raw:n.rawContent}),O=_;z&&(S==null?void 0:S.wrap)==="char"?O=ia(_,"char",n.id,{skipTags:S.skipTags}):z&&(S==null?void 0:S.wrap)==="word"&&(O=ia(_,"word",n.id,{skipTags:S.skipTags}));let Z=null;if(H?(Z=document.createElement("div"),Z.innerHTML=O,Z.style.display="none",U.appendChild(Z)):U.innerHTML=O,z&&(S!=null&&S.useCaret)&&!H&&W){let X=ni(),lt=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=lt[lt.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Ee=U.lastElementChild;Ee?Ee.appendChild(X):U.appendChild(X)}}if(g&&m==="inline"&&n.createdAt){let X=rg(n,c,"span");X.classList.add("persona-timestamp-inline");let lt=U.lastElementChild;lt?lt.appendChild(X):U.appendChild(X)}if(T.length>0){let X=ky(T,!H&&!!W,()=>{H&&Z&&(Z.style.display="")});X?w.appendChild(X):H&&Z&&(Z.style.display="")}let ke=Ty(n);if(ke.length>0){let X=Ly(ke);X&&w.appendChild(X)}let pe=Ey(n);if(pe.length>0){let X=Py(pe);X&&w.appendChild(X)}let ee=My(n);if(ee.length>0){let X=Iy(ee);X&&w.appendChild(X)}if(w.appendChild(U),g&&m==="below"&&n.createdAt){let X=rg(n,c);X.classList.add("persona-mt-1"),w.appendChild(X)}let Pe=n.role==="assistant"?xy(n.stopReason,(me=(ot=s==null?void 0:s.widgetConfig)==null?void 0:ot.copy)==null?void 0:me.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let X=!!(k&&k.trim()),lt=B.placeholder==="skeleton",Ve=lt&&B.buffer==="line"&&X;if(X)Ve&&w.appendChild(la());else if(lt)w.appendChild(la());else{let Ee=Ry("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ee&&w.appendChild(Ee)}}if(Pe&&n.stopReason&&!n.streaming&&(W||(U.style.display="none"),w.appendChild(Cy(n.stopReason,Pe))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=By(n,r,o);w.appendChild(X)}if(!u||n.role==="system")return w;let ie=v("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),he=Wy(d,n.role);return h==="right"||h==="left"&&n.role==="user"?ie.append(w,he):ie.append(he,w),w.classList.remove("persona-max-w-[85%]"),w.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ie};var Es=new Set,Dy=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Ny=(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
- `):""},sg=(n,e)=>{let t=Es.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"),l=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let c=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},ul=(n,e)=>{var pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e;let t=n.reasoning,r=v("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=(ee=(pe=e==null?void 0:e.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Es.has(n.id),l=t.status!=="complete",d=Ny(n,(Pe=o.previewMaxLines)!=null?Pe:3),c=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let u=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",m=(Ie=e==null?void 0:e.reasoning)!=null?Ie:{},y=String((ie=t.startedAt)!=null?ie:Date.now()),w=()=>{let K=v("span","");return K.setAttribute("data-tool-elapsed",y),K.textContent=Na(t),K},T=(he=m.renderCollapsedSummary)==null?void 0:he.call(m,{message:n,reasoning:t,defaultSummary:h,previewText:d,isActive:l,config:e!=null?e:{},elapsed:Na(t),createElapsedElement:w});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=h,u.appendChild(g));let W=v("span","persona-text-xs persona-text-persona-primary");W.textContent=rm(t),u.appendChild(W);let E=(re=o.loadingAnimation)!=null?re:"none",H=m.activeTextTemplate,B=m.completeTextTemplate,I=l?H:B,S=T instanceof HTMLElement,P=(K,J,Se)=>{let Y=Se;for(let le of J){let Te=v("span","persona-tool-char");Te.style.setProperty("--char-index",String(Y)),Te.textContent=le===" "?"\xA0":le,K.appendChild(Te),Y++}return Y},z=(K,J)=>{g.textContent="";let Se=Fa(K,""),Y=0;for(let le of Se){let Te=le.styles.length>0?(()=>{let Ye=v("span",le.styles.map(tt=>`persona-tool-text-${tt}`).join(" "));return g.appendChild(Ye),Ye})():g;if(le.isDuration&&l)Te.appendChild(w());else{let Ye=le.isDuration?Na(t):le.text;J?Y=P(Te,Ye,Y):Te.appendChild(document.createTextNode(Ye))}}};if(!S&&I)if(W.style.display="none",g.style.display="",l&&E!=="none"){let K=(oe=m.loadingAnimationDuration)!=null?oe:2e3;g.setAttribute("data-preserve-animation","true"),E==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),z(I,!1)):(g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),z(I,!0))}else z(I,!1);else if(!S&&l&&E!=="none"){g.style.display="";let K=(de=m.loadingAnimationDuration)!=null?de:2e3;if(g.setAttribute("data-preserve-animation","true"),E==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let J=g.textContent||h;g.textContent="",P(g,J,0)}t.status==="complete"&&(g.style.display="none")}else S||(t.status==="complete"?g.style.display="none":g.style.display="");let U=null;if(s){U=v("div","persona-flex persona-items-center");let J=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);J?U.appendChild(J):U.textContent=a?"Hide":"Show";let Se=v("div","persona-flex persona-items-center persona-ml-auto");Se.append(U),c.append(u,Se)}else c.append(u);let k=v("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&&l&&o.activePreview&&d){let K=($e=(Ae=e==null?void 0:e.reasoning)==null?void 0:Ae.renderCollapsedPreview)==null?void 0:$e.call(Ae,{message:n,reasoning:t,defaultPreview:d,isActive:l,config:e!=null?e:{}});Dy(k,K)||(k.textContent=d),k.style.display=""}if(!a&&l&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,k),r;let _=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");_.style.display=a?"":"none";let O=t.chunks.join(""),Z=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=O||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),_.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let J=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);J?U.appendChild(J):U.textContent=a?"Hide":"Show"}_.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,_),r};var Ms=new Set,Fy=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Oy=(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(l=>l.trim()).filter(Boolean).slice(-e).join(`
29
- `);let o=wo(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
30
- `):""},ml=(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)"},_y=(n,e)=>{var u,g,h,m,y;let t=n.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(g=r==null?void 0:r.collapsedMode)!=null?g:"tool-call",s=Oy(n,(h=r==null?void 0:r.previewMaxLines)!=null?h:3),a=t?om(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let l=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((y=t.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(c=s),l&&d.activeTextTemplate?c=Ki(t,d.activeTextTemplate,c):!l&&d.completeTextTemplate&&(c=Ki(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},ag=(n,e,t)=>{var u;let r=Ms.has(n),o=(u=t==null?void 0:t.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=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 g=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",h=ye(r?"chevron-up":"chevron-down",16,g,2);h?c.appendChild(h):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",l&&(l.style.display=r?"none":l.textContent||l.childNodes.length?"":"none")},gl=(n,e)=>{var O,Z,ke,pe,ee,Pe,Ie,ie,he;let t=n.toolCall,r=(O=e==null?void 0:e.toolCall)!=null?O:{},o=v("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=(ke=(Z=e==null?void 0:e.features)==null?void 0:Z.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,l=a&&Ms.has(n.id),{summary:d,previewText:c,isActive:u}=_y(n,e),g=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let y=String((pe=t.startedAt)!=null?pe:Date.now()),w=()=>{let re=v("span","");return re.setAttribute("data-tool-elapsed",y),re.textContent=Js(t),re},T=(Pe=r.renderCollapsedSummary)==null?void 0:Pe.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Js(t),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,h.appendChild(m)):T instanceof HTMLElement?h.appendChild(T):(m.textContent=d,h.appendChild(m));let W=(Ie=s.loadingAnimation)!=null?Ie:"none",E=r.activeTextTemplate,H=r.completeTextTemplate,B=u?E:H,I=T instanceof HTMLElement,S=(re,oe,de)=>{let Ae=de;for(let $e of oe){let K=v("span","persona-tool-char");K.style.setProperty("--char-index",String(Ae)),K.textContent=$e===" "?"\xA0":$e,re.appendChild(K),Ae++}return Ae},P=(re,oe)=>{var K;m.textContent="";let de=((K=t.name)==null?void 0:K.trim())||"tool",Ae=Fa(re,de),$e=0;for(let J of Ae){let Se=J.styles.length>0?(()=>{let Y=v("span",J.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(Y),Y})():m;if(J.isDuration&&u)Se.appendChild(w());else{let Y=J.isDuration?Js(t):J.text;oe?$e=S(Se,Y,$e):Se.appendChild(document.createTextNode(Y))}}};if(!I)if(u&&W!=="none"){let re=(ie=r.loadingAnimationDuration)!=null?ie:2e3;if(m.setAttribute("data-preserve-animation","true"),W==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),B&&P(B,!1);else if(m.classList.add(`persona-tool-loading-${W}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),W==="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)),B)P(B,!0);else{let oe=m.textContent||d;m.textContent="",S(m,oe,0)}}else B&&P(B,!1);let z=null;if(a){z=v("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=ye(l?"chevron-up":"chevron-down",16,re,2);oe?z.appendChild(oe):z.textContent=l?"Hide":"Show";let de=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(z),g.append(h,de)}else g.append(h);let U=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!l&&u&&s.activePreview&&c){let re=(he=r.renderCollapsedPreview)==null?void 0:he.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:u,config:e!=null?e:{}});Fy(U,re)||(U.textContent=c),U.style.display=""}if(!l&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(g,U),o;let k=v("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=l?"":"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=v("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=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Arguments";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",ml(de,r),de.textContent=wo(t.args),re.append(oe,de),k.appendChild(re)}if(t.chunks&&t.chunks.length){let re=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Activity";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",ml(de,r),de.textContent=t.chunks.join(""),re.append(oe,de),k.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Result";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",ml(de,r),de.textContent=wo(t.result),re.append(oe,de),k.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=v("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(g.setAttribute("aria-expanded",l?"true":"false"),z){z.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=ye(l?"chevron-up":"chevron-down",16,re,2);oe?z.appendChild(oe):z.textContent=l?"Hide":"Show"}k.style.display=l?"":"none",U.style.display=l?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(g,U,k),o};var Ko=new Map,gi=n=>{let t=(n.startsWith(Vr)?n.slice(Vr.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)},ig=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,lg=(n,e)=>{var r,o,s;let t=(o=(r=ig(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ko.get(n))!=null?s:t==="expanded"},cg=(n,e,t)=>{var a,l;let r=ig(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":(l=r==null?void 0:r.showDetailsLabel)!=null?l:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},dg=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=lg(n,t);cg(r,s,t),o.style.display=s?"":"none"};var fi=(n,e)=>{var P,z,U,k,_,O,Z,ke,pe,ee,Pe,Ie,ie,he,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=v("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=(P=r==null?void 0:r.backgroundColor)!=null?P:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(z=r==null?void 0:r.borderColor)!=null?z:"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=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=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)":(U=r==null?void 0:r.titleColor)!=null?U:"currentColor",u=ye(d,20,c,2);u&&l.appendChild(u);let g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),m=v("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",h.appendChild(m),!o){let oe=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");oe.setAttribute("data-approval-status",t.status),t.status==="approved"?(oe.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",oe.style.color="var(--persona-palette-colors-success-700, #15803d)",oe.textContent="Approved"):t.status==="denied"?(oe.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",oe.style.color="var(--persona-palette-colors-error-700, #b91c1c)",oe.textContent="Denied"):t.status==="timeout"&&(oe.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",oe.style.color="var(--persona-palette-colors-warning-700, #b45309)",oe.textContent="Timeout"),h.appendChild(oe)}g.appendChild(h);let w=t.toolType==="webmcp"||t.toolName.startsWith(Vr)?Vs(t.toolName):void 0,T=(_=r==null?void 0:r.formatDescription)==null?void 0:_.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...w?{displayTitle:w}:{},...t.reason?{reason:t.reason}:{}}),W=!t.toolName,E=T||(W?t.description:`The assistant wants to use \u201C${w!=null?w:gi(t.toolName)}\u201D.`),H=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(H.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(H.style.color=r.descriptionColor),H.textContent=E,g.appendChild(H),t.reason){let oe=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");oe.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?oe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let de=v("span","persona-font-medium");de.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,oe.appendChild(de),oe.appendChild(document.createTextNode(t.reason)),g.appendChild(oe)}let B=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",I=!!t.description&&!W,S=I||!!t.parameters;if(B!=="hidden"&&S){let oe=lg(n.id,e),de=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Ae=v("span");Ae.setAttribute("data-approval-details-label","true");let $e=v("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),de.append(Ae,$e),cg(de,oe,e),g.appendChild(de);let K=v("div");if(K.setAttribute("data-approval-details","true"),K.style.display=oe?"":"none",I){let J=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(J.style.color=r.descriptionColor),J.textContent=t.description,K.appendChild(J)}if(t.parameters){let J=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(J.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(J.style.color=r.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=wo(t.parameters),K.appendChild(J)}g.appendChild(K)}if(o){let oe=v("div","persona-flex persona-gap-2 persona-mt-2");oe.setAttribute("data-approval-buttons","true");let de=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");de.type="button",de.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let Ae=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);Ae&&(Ae.style.marginRight="4px",de.appendChild(Ae));let $e=document.createTextNode((Pe=r==null?void 0:r.approveLabel)!=null?Pe:"Approve");de.appendChild($e);let K=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",K.style.color=(ie=r==null?void 0:r.denyButtonTextColor)!=null?ie:"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 J=ye("shield-x",14,(he=r==null?void 0:r.denyButtonTextColor)!=null?he:"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",K.appendChild(J));let Se=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");K.appendChild(Se),oe.append(de,K),g.appendChild(oe)}return a.append(l,g),s.appendChild(a),s};function $y(n){var t,r;let e=(t=n.getRootNode)==null?void 0:t.call(n);return e instanceof ShadowRoot?e:((r=n.ownerDocument)!=null?r:document).body}function pg(n){var w;let{anchor:e,content:t,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:l,onDismiss:d}=n,c=(w=n.container)!=null?w:$y(e),u=!1,g=null,h=()=>{if(!u)return;let T=e.getBoundingClientRect();t.style.position="fixed",s&&(t.style.minWidth=`${T.width}px`);let W=r==="top-start"||r==="top-end"?T.top-o-t.getBoundingClientRect().height:T.bottom+o,E=r==="bottom-end"||r==="top-end"?T.right-t.getBoundingClientRect().width:T.left;t.style.top=`${W}px`,t.style.left=`${E}px`},m=()=>{u&&(u=!1,g&&(g(),g=null),t.remove())},y=()=>{var I,S,P;if(u)return;u=!0,a!=null&&(t.style.zIndex=String(a)),c.appendChild(t),h();let T=(S=((I=e.ownerDocument)!=null?I:document).defaultView)!=null?S:window,W=(P=e.ownerDocument)!=null?P:document,E=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}h()},H=z=>{let U=typeof z.composedPath=="function"?z.composedPath():[];U.includes(t)||U.includes(e)||(m(),d==null||d("outside"))},B=T.setTimeout(()=>{W.addEventListener("pointerdown",H,!0)},0);T.addEventListener("scroll",E,!0),T.addEventListener("resize",E),g=()=>{T.clearTimeout(B),W.removeEventListener("pointerdown",H,!0),T.removeEventListener("scroll",E,!0),T.removeEventListener("resize",E)},l==null||l()};return{get isOpen(){return u},open:y,close:m,toggle:()=>u?m():y(),reposition:h,destroy:m}}function ug(n){return(typeof n.composedPath=="function"?n.composedPath():[]).some(t=>t instanceof HTMLElement&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}var Uy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),mg=(n,e)=>{let t=n.keyHandlers.get(e);t&&(document.removeEventListener("keydown",t),n.keyHandlers.delete(e));let r=n.popovers.get(e);r&&(r.destroy(),n.popovers.delete(e))},Go=(n,e)=>{mg(n,e);let t=n.pendingOrder.indexOf(e);t!==-1&&n.pendingOrder.splice(t,1),n.latestPendingApprovalId===e&&(n.latestPendingApprovalId=n.pendingOrder.length?n.pendingOrder[n.pendingOrder.length-1]:null)},qy=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,zy=(n,e)=>{var r,o;let t=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=Ko.get(n))!=null?o:t==="expanded"},fl=n=>{let e=v("span","persona-approval-kbd");return e.textContent=n,e},jy=(n,e)=>{var c,u;let t=v("span","persona-approval-title");e!=null&&e.titleColor&&(t.style.color=e.titleColor);let o=n.toolType==="webmcp"||n.toolName.startsWith(Vr)?Vs(n.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:n.toolName,toolType:n.toolType,description:(c=n.description)!=null?c:"",parameters:n.parameters,...o?{displayTitle:o}:{},...n.reason?{reason:n.reason}:{}});if(s)return t.textContent=s,t;let a=o!=null?o:gi(n.toolName),l=n.toolType&&n.toolType!=="webmcp"?n.toolType:null;t.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,t.appendChild(d),l){t.append(" from ");let g=document.createElement("strong");g.textContent=l,t.appendChild(g)}return t},Vy=n=>{let e=v("div","persona-approval-resolved"),t=ye("ban",15,"currentColor",2);t&&e.appendChild(t);let r=v("span","persona-approval-resolved-name");return r.textContent=n.toolName?gi(n.toolName):"Tool",e.append(r,document.createTextNode(n.status==="timeout"?" timed out":" denied")),e},Ky=(n,e,t,r,o,s,a)=>{var z,U,k,_,O,Z,ke;let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(l.style.background=r.backgroundColor),r!=null&&r.borderColor&&(l.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(l.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(z=r==null?void 0:r.detailsDisplay)!=null?z:"collapsed",c=!!t.description&&d!=="hidden",u=t.parameters!=null&&d!=="hidden",g=c||u,h=g&&zy(e.id,r),m=(U=r==null?void 0:r.showDetailsLabel)!=null?U:"Show details",y=(k=r==null?void 0:r.hideDetailsLabel)!=null?k:"Hide details",w=v("button","persona-approval-head");w.type="button",g?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",h?"true":"false"),w.setAttribute("aria-label",h?y:m)):w.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),W=ye("shield-check",16,"currentColor",2);W&&T.appendChild(W),w.appendChild(T);let E=jy(t,r);if(g){let pe=v("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),E.append(" "),E.appendChild(pe)}w.appendChild(E),l.appendChild(w);let H=v("div","persona-approval-body");if(g){let pe=v("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!h,c){let ee=v("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=t.description,pe.appendChild(ee)}if(u){let ee=v("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=wo(t.parameters),pe.appendChild(ee)}H.appendChild(pe)}if(t.reason){let pe=v("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=v("span","persona-approval-reason-label");ee.textContent=`${(_=r==null?void 0:r.reasonLabel)!=null?_:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(t.reason)),H.appendChild(pe)}let B=v("div","persona-approval-actions"),I=null,S=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},P=v("button","persona-approval-deny");if(P.type="button",P.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(P.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(P.style.color=r.denyButtonTextColor),P.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let pe=v("div","persona-approval-split"),ee=v("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),S(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",fl("\u23CE"));let Pe=v("button","persona-approval-caret");Pe.type="button",Pe.setAttribute("data-action","toggle-menu"),Pe.setAttribute("aria-label","More options"),S(Pe);let Ie=ye("chevron-down",15,"currentColor",2);Ie&&Pe.appendChild(Ie),pe.append(ee,Pe),B.append(pe,P),P.append(fl("Esc"));let ie=v("div","persona-approval-menu"),he=v("button","persona-approval-menu-item");he.type="button",he.append("Allow once",fl("\u2318\u23CE")),ie.appendChild(he),I=pg({anchor:pe,content:ie,placement:"bottom-start",matchAnchorWidth:!0}),n.popovers.set(e.id,I),he.addEventListener("click",()=>{Go(n,e.id),o()})}else{let pe=v("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),S(pe),pe.append((ke=r==null?void 0:r.approveLabel)!=null?ke:"Allow"),B.append(pe,P)}return H.appendChild(B),l.appendChild(H),l.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let Pe=ee.getAttribute("data-action");if(Pe==="toggle-params"){let Ie=l.querySelector('[data-role="params"]');if(Ie){let ie=Ie.hidden;Ie.hidden=!ie,w.setAttribute("aria-expanded",ie?"true":"false"),w.setAttribute("aria-label",ie?y:m),Ko.set(e.id,ie)}return}if(Pe==="toggle-menu"){I==null||I.toggle();return}if(Pe==="always"){Go(n,e.id),o({remember:!0});return}if(Pe==="allow"){Go(n,e.id),o();return}if(Pe==="deny"){Go(n,e.id),s();return}}),l},gg=()=>{let n=Uy();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let l=r==null?void 0:r.approval;if(!l)return null;let d=qy(a);if(l.status!=="pending"){if(Go(n,r.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return Vy(l)}mg(n,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=Ky(n,r,l,d,o,s,c);if(c){n.pendingOrder.includes(r.id)||n.pendingOrder.push(r.id),n.latestPendingApprovalId=n.pendingOrder[n.pendingOrder.length-1];let g=h=>{ug(h)||r.id===n.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Go(n,r.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?o():o({remember:!0})))};n.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return u}},teardown:()=>{for(let r of[...n.keyHandlers.keys(),...n.popovers.keys()])Go(n,r);n.latestPendingApprovalId=null}}};var fg=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,l,d,c)=>{n.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(t=null),!o||!o.length||!u&&(l!=null?l:s?s.getMessages():[]).some(T=>T.role==="user"))return;let g=document.createDocumentFragment(),h=s?s.isStreaming():!1,m=y=>{switch(y){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(y=>{let w=v("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");w.type="button",w.textContent=y,w.disabled=h,d!=null&&d.fontFamily&&(w.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(w.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY),w.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",u&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),g.appendChild(w),e.push(w)}),n.appendChild(g),u){let y=JSON.stringify(o);y!==t&&(t=y,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ga=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 fa=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 Gy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Qy=new Set(["step_start","execution_start"]),Xy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Jy=new Set(["step_complete","agent_turn_complete"]),Yy=new Set(["flow_complete","agent_complete"]),hg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),bg=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),jn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Qo=(n,e)=>{let t=n[e];return bg(t)?t:void 0};function hl(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function hi(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Zy(n,e){return typeof e.type=="string"?e.type:n}function eb(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 tb(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 yg(n){var r,o,s,a,l;let e=Qo(n,"result"),t=[Qo(n,"tokens"),Qo(n,"totalTokens"),e?Qo(e,"tokens"):void 0,Qo(n,"usage"),e?Qo(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=jn(d.output))!=null?r:jn(d.outputTokens))!=null?o:jn(d.completionTokens);if(c!==void 0)return c}return(l=(s=jn(n.outputTokens))!=null?s:jn(n.completionTokens))!=null?l:e?(a=jn(e.outputTokens))!=null?a:jn(e.completionTokens):void 0}function nb(n){var t,r,o,s,a;let e=Qo(n,"result");return(a=(o=(r=(t=jn(n.executionTime))!=null?t:jn(n.executionTimeMs))!=null?r:jn(n.execution_time))!=null?o:jn(n.duration))!=null?a:e?(s=jn(e.executionTime))!=null?s:jn(e.executionTimeMs):void 0}function rb(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ha=class{constructor(e=rb){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:hi(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(!bg(t)){hg.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Zy(e,t),o=this.now();if(Gy.has(r)){this.startRun(o);return}if(Qy.has(r)){this.run||this.startRun(o);return}if(Xy.has(r)){if(!tb(r,t))return;let a=eb(t);if(!a)return;this.run||this.startRun(o);let l=this.run;(s=l.firstDeltaAt)!=null||(l.firstDeltaAt=o),l.visibleCharCount+=a.length;let d=l.exactOutputTokens+hl(l.visibleCharCount),c=o-l.firstDeltaAt;this.metric={status:"running",tokensPerSecond:hi(d,c),outputTokens:d,durationMs:c,source:l.exactOutputTokens>0?"usage":"estimate"};return}if(Jy.has(r)){if(!this.run)return;let a=this.run,l=yg(t);l!==void 0&&(a.exactOutputTokens+=l,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+hl(a.visibleCharCount),u=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:hi(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(Yy.has(r)){if(!this.run)return;let a=this.run,l=yg(t),d=l!=null?l:a.exactOutputTokens+hl(a.visibleCharCount),c=l!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:hi(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(hg.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=nb(t);return s!=null?s:r-e.startedAt}};function ks(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var ob={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)"}},sb={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ab=["flowName","stepName","reasoningText","text","name","tool","toolName"],ib=100;function lb(n,e){let t={...ob,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return sb}function cb(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function db(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 pb(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 ub(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 mb(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 gb(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function fb(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 hb(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(l=>l.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let l=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(l)return l}return a();function a(){let l=v("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=v("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,l.appendChild(d),l}}function yl(n,e,t,r,o,s,a,l){var h;let d=o.has(n.id),c=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ks(c,(h=r.classNames)==null?void 0:h.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&l){let m=u.renderEventStreamRow({event:n,index:e,config:l,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(g()),c;function g(){var O,Z;let m=v("div",""),y=v("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");y.setAttribute("data-event-id",n.id);let w=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),T=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);T&&w.appendChild(T);let W=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(O=r.timestampFormat)!=null?O:"relative";W.textContent=E==="relative"?cb(n.timestamp,t):db(n.timestamp);let H=null;r.showSequenceNumbers!==!1&&(H=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(e+1));let B=lb(n.type,r.badgeColors),I=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");I.style.backgroundColor=B.bg,I.style.color=B.text,I.style.borderColor=B.text+"50",I.textContent=n.type;let S=(Z=r.descriptionFields)!=null?Z:ab,P=pb(n.payload,S),z=null;P&&(z=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),z.textContent=P);let U=v("div","persona-flex-1 persona-min-w-0"),k=v("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"),_=ye("clipboard","12px","currentColor",1.5);return _&&k.appendChild(_),k.addEventListener("click",async ke=>{ke.stopPropagation(),await ub(mb(n)),k.innerHTML="";let pe=ye("check","12px","currentColor",1.5);pe&&k.appendChild(pe),setTimeout(()=>{k.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&k.appendChild(ee)},1500)}),y.appendChild(w),y.appendChild(W),H&&y.appendChild(H),y.appendChild(I),z&&y.appendChild(z),y.appendChild(U),y.appendChild(k),m.appendChild(y),d&&m.appendChild(hb(n,a,l)),m}}function vg(n){var y,w,T,W,E;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,l=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(l==null?void 0:l.enabled)!==!1,c=(w=l==null?void 0:l.iconName)!=null?w:"arrow-down",u=(T=l==null?void 0:l.label)!=null?T:"",g=(E=(W=o==null?void 0:o.features)==null?void 0:W.eventStream)!=null?E:{},h=s.find(H=>H.renderEventStreamView);if(h!=null&&h.renderEventStreamView&&o){let H=h.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(H)return{element:H,update:()=>{},destroy:()=>{}}}return m();function m(){let H=g.classNames,B=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ks(B,H==null?void 0:H.panel);let I=[],S="",P="",z=null,U=[],k={},_=0,O=Ja(),Z=0,ke=0,pe=!1,ee=null,Pe=!1,Ie=0,ie=new Set,he=new Map,re="",oe="",de=null,Ae,$e,K,J,Se=null,Y=null,le=null;function Te(){let fe=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),D=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(ks(D,H==null?void 0:H.headerBar),a){Y=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),Y.style.cursor="help",Se=v("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"),Se.textContent="-- tok/s",le=v("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"),le.style.display="none",le.style.pointerEvents="none";let Ot=Y,Zt=le,yr=()=>{if(!Zt.textContent)return;let rr=Ot.getBoundingClientRect(),or=fe.getBoundingClientRect();Zt.style.left=`${rr.left-or.left}px`,Zt.style.top=`${rr.bottom-or.top+4}px`,Zt.style.display="block"},Wr=()=>{Zt.style.display="none"};Y.addEventListener("mouseenter",yr),Y.addEventListener("mouseleave",Wr),Y.appendChild(Se)}let ve=v("div","persona-flex-1");Ae=v("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 ce=v("option","");ce.value="",ce.textContent="All events (0)",Ae.appendChild(ce),$e=v("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"),$e.type="button",$e.title="Copy All";let Ge=ye("clipboard-copy","12px","currentColor",1.5);Ge&&$e.appendChild(Ge);let Pt=v("span","persona-event-copy-all persona-text-xs");Pt.textContent="Copy All",$e.appendChild(Pt),Y&&D.appendChild(Y),D.appendChild(ve),D.appendChild(Ae),D.appendChild($e);let kt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ks(kt,H==null?void 0:H.searchBar);let wt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Ht=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");wt&&Ht.appendChild(wt),K=v("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"),ks(K,H==null?void 0:H.searchInput),K.type="text",K.placeholder="Search event payloads...",J=v("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"),J.type="button",J.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&J.appendChild(Xt),kt.appendChild(Ht),kt.appendChild(K),kt.appendChild(J),fe.appendChild(D),fe.appendChild(kt),le&&fe.appendChild(le),fe}let Ye,tt=s.find(fe=>fe.renderEventStreamToolbar);if(tt!=null&&tt.renderEventStreamToolbar&&o){let fe=tt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:D=>{S=D,be(),At()},onSearchChange:D=>{P=D,be(),At()}});Ye=fe!=null?fe:Te()}else Ye=Te();let Wt=v("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");Wt.style.display="none";function ht(){if(!a||!Se||!Y)return;let fe=a(),D=gb(fe);Se.textContent=D;let ve=fb(fe);le&&(le.textContent=ve,ve||(le.style.display="none")),Y.setAttribute("aria-label",ve?`Throughput: ${D}, ${ve}`:`Throughput: ${D}`)}let ot=v("div","persona-flex-1 persona-min-h-0 persona-relative"),me=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");me.style.height="100%";let X=v("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");ks(X,H==null?void 0:H.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let lt=ye(c,"14px","currentColor",2);lt&&X.appendChild(lt);let Ve=v("span","");Ve.textContent=u,X.appendChild(Ve);let Ee=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ee.style.display="none",ot.appendChild(me),ot.appendChild(Ee),ot.appendChild(X),B.setAttribute("tabindex","0"),B.appendChild(Ye),B.appendChild(Wt),B.appendChild(ot);function xe(){let fe=e.getAll(),D={};for(let kt of fe)D[kt.type]=(D[kt.type]||0)+1;let ve=Object.keys(D).sort(),ce=ve.length!==U.length||!ve.every((kt,wt)=>kt===U[wt]),ft=!ce&&ve.some(kt=>D[kt]!==k[kt]),Ge=fe.length!==Object.values(k).reduce((kt,wt)=>kt+wt,0);if(!ce&&!ft&&!Ge||(U=ve,k=D,!Ae))return;let Pt=Ae.value;if(Ae.options[0].textContent=`All events (${fe.length})`,ce){for(;Ae.options.length>1;)Ae.remove(1);for(let kt of ve){let wt=v("option","");wt.value=kt,wt.textContent=`${kt} (${D[kt]||0})`,Ae.appendChild(wt)}Pt&&ve.includes(Pt)?Ae.value=Pt:Pt&&(Ae.value="",S="")}else for(let kt=1;kt<Ae.options.length;kt++){let wt=Ae.options[kt];wt.textContent=`${wt.value} (${D[wt.value]||0})`}}function Ze(){let fe=e.getAll();if(S&&(fe=fe.filter(D=>D.type===S)),P){let D=P.toLowerCase();fe=fe.filter(ve=>ve.type.toLowerCase().includes(D)||ve.payload.toLowerCase().includes(D))}return fe}function jt(){return S!==""||P!==""}function be(){_=0,Z=0,O.resume(),X.style.display="none"}function ue(fe){ie.has(fe)?ie.delete(fe):ie.add(fe),de=fe;let D=me.scrollTop,ve=O.isFollowing();Pe=!0,O.pause(),At(),me.scrollTop=D,ve&&O.resume(),Pe=!1}function An(){return xo(me,50)}function At(){ke=Date.now(),pe=!1,ht(),xe();let fe=e.getEvictedCount();fe>0?(Wt.textContent=`${fe.toLocaleString()} older events truncated`,Wt.style.display=""):Wt.style.display="none",I=Ze();let D=I.length,ve=e.getSize()>0;D===0&&ve&&jt()?(Ee.textContent=P?`No events matching '${P}'`:"No events matching filter",Ee.style.display="",me.style.display="none"):(Ee.style.display="none",me.style.display=""),$e&&($e.title=jt()?`Copy Filtered (${D})`:"Copy All"),d&&!O.isFollowing()&&D>_&&(Z+=D-_,Ve.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",X.style.display=""),_=D;let ce=e.getAll(),ft=ce.length>0?ce[0].timestamp:0,Ge=new Set(I.map(wt=>wt.id));for(let wt of ie)Ge.has(wt)||ie.delete(wt);let Pt=S!==re||P!==oe,kt=he.size===0&&I.length>0;if(Pt||kt||I.length===0){me.innerHTML="",he.clear();let wt=document.createDocumentFragment();for(let Ht=0;Ht<I.length;Ht++){let Xt=yl(I[Ht],Ht,ft,g,ie,ue,s,o);he.set(I[Ht].id,Xt),wt.appendChild(Xt)}me.appendChild(wt),re=S,oe=P,de=null}else{if(de!==null){let Ht=he.get(de);if(Ht&&Ht.parentNode===me){let Xt=I.findIndex(Ot=>Ot.id===de);if(Xt>=0){let Ot=yl(I[Xt],Xt,ft,g,ie,ue,s,o);me.insertBefore(Ot,Ht),Ht.remove(),he.set(de,Ot)}}de=null}let wt=new Set(I.map(Ht=>Ht.id));for(let[Ht,Xt]of he)wt.has(Ht)||(Xt.remove(),he.delete(Ht));for(let Ht=0;Ht<I.length;Ht++){let Xt=I[Ht];if(!he.has(Xt.id)){let Ot=yl(Xt,Ht,ft,g,ie,ue,s,o);he.set(Xt.id,Ot),me.appendChild(Ot)}}}O.isFollowing()&&(me.scrollTop=me.scrollHeight)}function yn(){if(Date.now()-ke>=ib){ee!==null&&(cancelAnimationFrame(ee),ee=null),At();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,At()}))}let fr=(fe,D)=>{if(!$e)return;$e.innerHTML="";let ve=ye(fe,"12px","currentColor",1.5);ve&&$e.appendChild(ve);let ce=v("span","persona-text-xs");ce.textContent="Copy All",$e.appendChild(ce),setTimeout(()=>{$e.innerHTML="";let ft=ye("clipboard-copy","12px","currentColor",1.5);ft&&$e.appendChild(ft);let Ge=v("span","persona-text-xs");Ge.textContent="Copy All",$e.appendChild(Ge),$e.disabled=!1},D)},hr=async()=>{if($e){$e.disabled=!0;try{let fe;jt()?fe=I:t?(fe=await t(),fe.length===0&&(fe=e.getAll())):fe=e.getAll();let D=fe.map(ve=>{try{return JSON.parse(ve.payload)}catch{return ve.payload}});await navigator.clipboard.writeText(JSON.stringify(D,null,2)),fr("check",1500)}catch{fr("x",1500)}}},qe=()=>{Ae&&(S=Ae.value,be(),At())},M=()=>{!K||!J||(J.style.display=K.value?"":"none",z&&clearTimeout(z),z=setTimeout(()=>{P=K.value,be(),At()},150))},ge=()=>{!K||!J||(K.value="",P="",J.style.display="none",z&&clearTimeout(z),be(),At())},Me=()=>{if(Pe)return;let fe=me.scrollTop,{action:D,nextLastScrollTop:ve}=Ya({following:O.isFollowing(),currentScrollTop:fe,lastScrollTop:Ie,nearBottom:An(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=ve,D==="resume"?(O.resume(),Z=0,X.style.display="none"):D==="pause"&&(O.pause(),d&&(Ve.textContent=u,X.style.display=""))},Le=fe=>{let D=Za({following:O.isFollowing(),deltaY:fe.deltaY,nearBottom:An(),resumeWhenNearBottom:!0});D==="pause"?(O.pause(),d&&(Ve.textContent=u,X.style.display="")):D==="resume"&&(O.resume(),Z=0,X.style.display="none")},He=()=>{d&&(me.scrollTop=me.scrollHeight,O.resume(),Z=0,X.style.display="none")},nt=fe=>{let D=fe.target;if(!D||D.closest("button"))return;let ve=D.closest("[data-event-id]");if(!ve)return;let ce=ve.getAttribute("data-event-id");ce&&ue(ce)},Xe=fe=>{if((fe.metaKey||fe.ctrlKey)&&fe.key==="f"){fe.preventDefault(),K==null||K.focus(),K==null||K.select();return}fe.key==="Escape"&&(K&&document.activeElement===K?(ge(),K.blur(),B.focus()):r&&r())};$e&&$e.addEventListener("click",hr),Ae&&Ae.addEventListener("change",qe),K&&K.addEventListener("input",M),J&&J.addEventListener("click",ge),me.addEventListener("scroll",Me),me.addEventListener("wheel",Le,{passive:!0}),me.addEventListener("click",nt),X.addEventListener("click",He),B.addEventListener("keydown",Xe);function yt(){z&&clearTimeout(z),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,he.clear(),$e&&$e.removeEventListener("click",hr),Ae&&Ae.removeEventListener("change",qe),K&&K.removeEventListener("input",M),J&&J.removeEventListener("click",ge),me.removeEventListener("scroll",Me),me.removeEventListener("wheel",Le),me.removeEventListener("click",nt),X.removeEventListener("click",He),B.removeEventListener("keydown",Xe)}return{element:B,update:yn,destroy:yt}}}function wg(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",l=document.createElement("div");l.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",l.style.border="1px solid var(--persona-border, #e5e7eb)",l.style.backgroundColor="var(--persona-surface, #ffffff)",l.style.cursor="pointer",l.tabIndex=0,l.setAttribute("role","button"),l.setAttribute("aria-label",`Open ${t} in artifact panel`),r&&l.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let h=document.createElement("span");h.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",h.style.backgroundColor="var(--persona-primary, #171717)",h.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(h);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(c.append(u,g),l.append(d,c),o==="complete"){let h=document.createElement("button");h.type="button",h.textContent="Download",h.title=`Download ${t}`,h.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",h.style.border="1px solid var(--persona-border, #e5e7eb)",h.style.color="var(--persona-text, #1f2937)",h.style.backgroundColor="transparent",h.style.cursor="pointer",h.setAttribute("data-download-artifact",r),l.append(h)}return l}var xg=(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",l=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",u=t({artifact:{artifactId:l,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>wg(n,e)});if(u)return u}return wg(n,e)};var bl=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)})}},Xo=new bl;Xo.register("PersonaArtifactCard",xg);function yb(n){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=v("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=v("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 Cg(n,e){var $e,K,J,Se;let t=(K=($e=n.features)==null?void 0:$e.artifacts)==null?void 0:K.layout,o=((J=t==null?void 0:t.toolbarPreset)!=null?J:"default")==="document",s=(Se=t==null?void 0:t.panePadding)==null?void 0:Se.trim(),a=n.markdown?ka(n.markdown):null,l=La(n.sanitize),d=Y=>{let le=a?a(Y):ho(Y);return l?l(le):le},c=typeof document!="undefined"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,u=()=>{c==null||c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};c&&c.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let g=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),o&&g.classList.add("persona-artifact-pane-document");let h=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");h.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&h.classList.add("persona-artifact-toolbar-document");let m=v("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let y=v("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let w="rendered",T=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),W=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"}),H=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),B=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,I=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,S=t==null?void 0:t.documentToolbarCopyMenuItems,P=!!(I&&S&&S.length>0),z=null,U,k=null,_=null;if(o&&(B||I)&&!P){if(U=B?al({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let Y=ye("chevron-down",14,"currentColor",2);Y&&U.appendChild(Y)}}else o&&P?(z=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),U=B?al({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"}}),z.append(U,k)):o?U=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):U=Cn({icon:"copy",label:"Copy"});let O=o?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),Z=o?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),ke=()=>{var tt,Wt,ht;let Y=(tt=he.find(ot=>ot.id===re))!=null?tt:he[he.length-1],le=(Wt=Y==null?void 0:Y.id)!=null?Wt:null,Te=(Y==null?void 0:Y.artifactType)==="markdown"&&(ht=Y.markdown)!=null?ht:"",Ye=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Te,jsonPayload:Ye,id:le}},pe=async()=>{var tt;let{markdown:Y,jsonPayload:le}=ke(),Te=(tt=he.find(Wt=>Wt.id===re))!=null?tt:he[he.length-1],Ye=(Te==null?void 0:Te.artifactType)==="markdown"?Y:Te?le:"";try{await navigator.clipboard.writeText(Ye)}catch{}};if(U.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&P){let{markdown:le,jsonPayload:Te,id:Ye}=ke();try{await Y({actionId:"primary",artifactId:Ye,markdown:le,jsonPayload:Te})}catch{}return}await pe()}),k&&(S!=null&&S.length)){let Y=()=>{var Te;return(Te=g.closest("[data-persona-root]"))!=null?Te:document.body},le=()=>{_=Ts({items:S.map(Te=>({id:Te.id,label:Te.label})),onSelect:async Te=>{let{markdown:Ye,jsonPayload:tt,id:Wt}=ke(),ht=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ht?await ht({actionId:Te,artifactId:Wt,markdown:Ye,jsonPayload:tt}):Te==="markdown"||Te==="md"?await navigator.clipboard.writeText(Ye):Te==="json"||Te==="source"?await navigator.clipboard.writeText(tt):await navigator.clipboard.writeText(Ye||tt)}catch{}},anchor:z!=null?z:k,position:"bottom-right",portal:Y()})};g.isConnected?le():requestAnimationFrame(le),k.addEventListener("click",Te=>{Te.stopPropagation(),_==null||_.toggle()})}O.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}de()}),Z.addEventListener("click",()=>{var Y;u(),(Y=e.onDismiss)==null||Y.call(e)});let ee=()=>{o&&(W.setAttribute("aria-pressed",w==="rendered"?"true":"false"),E.setAttribute("aria-pressed",w==="source"?"true":"false"))};W.addEventListener("click",()=>{w="rendered",ee(),de()}),E.addEventListener("click",()=>{w="source",ee(),de()});let Pe=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(h.replaceChildren(),T.append(W,E),z?H.append(z,O,Z):H.append(U,O,Z),h.append(T,Pe,H),ee()):(h.appendChild(m),h.appendChild(y)),s&&(h.style.paddingLeft=s,h.style.paddingRight=s);let Ie=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ie=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,ie.style.padding=s),g.appendChild(h),g.appendChild(Ie),g.appendChild(ie);let he=[],re=null,oe=!1,de=()=>{var Ye,tt,Wt,ht;let Y=o&&he.length<=1;Ie.classList.toggle("persona-hidden",Y),Ie.replaceChildren();for(let ot of he){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=ot.title||ot.id.slice(0,8),ot.id===re&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(ot.id)),Ie.appendChild(me)}ie.replaceChildren();let le=re&&he.find(ot=>ot.id===re)||he[he.length-1];if(!le)return;if(o){let ot=le.artifactType==="markdown"?"MD":(Ye=le.component)!=null?Ye:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Pe.textContent=`${X} \xB7 ${ot}`}else m.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&w==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(tt=le.markdown)!=null?tt:"",ie.appendChild(me);return}let ot=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ot.innerHTML=d((Wt=le.markdown)!=null?Wt:""),ie.appendChild(ot);return}let Te=le.component?Xo.get(le.component):void 0;if(Te){let me={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let X=Te((ht=le.props)!=null?ht:{},me);if(X){ie.appendChild(X);return}}catch{}}ie.appendChild(yb(le))},Ae=()=>{var le;let Y=he.length>0;if(g.classList.toggle("persona-hidden",!Y),c){let Te=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,tt=((le=Te==null?void 0:Te.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&tt&&oe?(c.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:c,update(Y){var le,Te,Ye;he=Y.artifacts,re=(Ye=(Te=Y.selectedId)!=null?Te:(le=Y.artifacts[Y.artifacts.length-1])==null?void 0:le.id)!=null?Ye:null,he.length>0&&(oe=!0),de(),Ae()},setMobileOpen(Y){oe=Y,!Y&&c?(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):Ae()}}}function nr(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 Ag(n,e){var s,a,l,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"),!nr(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(l=t==null?void 0:t.paneBorder)==null?void 0:l.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 bb(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 yi(n,e){var d,c,u,g,h,m,y,w,T,W;if(!nr(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"),bb(n),Ag(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",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(g=t==null?void 0:t.paneWidth)!=null?g:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(h=t==null?void 0:t.paneMaxWidth)!=null?h:"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=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(y=t==null?void 0:t.panePadding)==null?void 0:y.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(w=t==null?void 0:t.documentToolbarIconColor)==null?void 0:w.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(T=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:T.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let l=(W=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:W.trim();l?n.style.setProperty("--persona-artifact-doc-toggle-active-border",l):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ag(n,e)}var Sg=["panel","seamless"];function bi(n,e){var l,d,c,u,g,h;for(let m of Sg)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"),!nr(e))return;let t=(d=(l=e.features)==null?void 0:l.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Sg.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=t==null?void 0:t.paneShadow)==null?void 0:g.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 m=((h=t.unifiedSplitOuterRadius)==null?void 0:h.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Tg(n,e){var t,r,o;return!e||!nr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function vb(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 wb(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 xb(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function Cb(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function Eg(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 Mg(n,e,t,r,o,s){let a=vb(o,200),l=Cb(e,t,r,200);l=Math.max(a,l);let d=wb(s);return d!==null&&(l=Math.min(l,d)),xb(n,a,l)}var kg={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"}},vl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,w,T;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let l=(w=kg[a])!=null?w:kg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),c=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,d.appendChild(c),l.description){let W=v("p","persona-text-sm persona-text-persona-muted");W.textContent=l.description,d.appendChild(W)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(W=>{var S,P;let E=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${W.name}`;let H=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=W.label,E.appendChild(H);let B=(S=W.type)!=null?S:"text",I;B==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=B),I.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",I.id=`${e.id}-${a}-${W.name}`,I.name=W.name,I.placeholder=(P=W.placeholder)!=null?P:"",W.required&&(I.required=!0),E.appendChild(I),u.appendChild(E)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(T=l.submitLabel)!=null?T:"Submit",g.appendChild(h),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async W=>{var I,S;W.preventDefault();let E=(I=t.formEndpoint)!=null?I:"/form",H=new FormData(u),B={};H.forEach((P,z)=>{B[z]=P}),B.type=a,m.disabled=!0,h.textContent="Submitting\u2026";try{let P=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let z=await P.json();h.textContent=(S=z.message)!=null?S:"Thanks! We'll be in touch soon.",z.success&&z.nextPrompt&&await r.sendMessage(String(z.nextPrompt))}catch(P){h.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var wl=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 l,d;return((l=a.priority)!=null?l: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()}},xl=new wl;var Lg=()=>{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(l=>{try{l(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ab=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},Sb=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},Al=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=Ab(n),t=Sb(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}},Cl=n=>typeof n=="string"?n:n==null?"":String(n),ya={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Cl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=Cl(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:Cl(t.text)}}},Pg=n=>Array.isArray(n)?n.map(e=>String(e)):[],Sl=n=>{let e=new Set(Pg(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(Pg(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 l=a?n.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!l)return null;e.add(s.message.id),r();let d={action:l,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let u=()=>{n.emit("action:resubmit",d)},g=c(l,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let h=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:h,resubmit:g.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var Tb=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}},Eb=n=>n.map(e=>({...e,streaming:!1})),Mb=n=>n.map(e=>({...e,status:"complete"})),Ig=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?Tb(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?Eb(t.messages):void 0,artifacts:t.artifacts?Mb(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 Tl=require("partial-json");function Rg(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Xo.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:l=>{o&&o(l)}};try{return s(n.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,l),null}}function Wg(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 El(n){let e=Wg(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 Hg(n){let e=Wg(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 kb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Bg(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:l="Skip",showComment:d=!0,ratingLabels:c=kb}=n,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=r,m.appendChild(y);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,m.appendChild(w),h.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let S=1;S<=5;S++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),P.title=c[S-1],P.dataset.rating=String(S),P.innerHTML=`
33
+ `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Ot(s),p=n.querySelector("[data-role='launcher-title']");if(p){let R=a.title??"Chat Assistant";p.textContent=R,p.setAttribute("title",R)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let R=a.subtitle??"Here to help you get answers fast";d.textContent=R,d.setAttribute("title",R)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||l?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let R=a.agentIconSize??"40px";if(u.style.height=R,u.style.width=R,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let D=parseFloat(R)||24,$=ie(a.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let w=n.querySelector("[data-role='launcher-image']");if(w){let R=a.agentIconSize??"40px";w.style.height=R,w.style.width=R,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(w.src=a.iconUrl,w.style.display="block"):w.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let R=a.callToActionIconSize??"32px";f.style.height=R,f.style.width=R,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let D=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,D=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",a.callToActionIconName){let $=parseFloat(R)||24,j=Math.max($-D,8),z=ie(a.callToActionIconName,j,"currentColor",2);z?f.appendChild(z):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&xn[a.position]?xn[a.position]:xn["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",P="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?P:`${x} ${b}`,l||(n.style.zIndex=String(a.zIndex??zt));let W="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}};var Kp=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=qp(t),s=Vp(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:l,header:p,composer:d,replaceHeader:w=>(p.element.replaceWith(w.header),p.element=w.header,p.iconHolder=w.iconHolder,p.headerTitle=w.headerTitle,p.headerSubtitle=w.headerSubtitle,p.closeButton=w.closeButton,p.closeButtonWrapper=w.closeButtonWrapper,p.clearChatButton=w.clearChatButton,p.clearChatButtonWrapper=w.clearChatButtonWrapper,w),replaceComposer:w=>{d.footer.replaceWith(w),d.footer=w}}},pl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>dl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=dl(t,n);return{instance:r,element:r.element}};var rh=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},sh=(t,e)=>{if(!t)return null;let n=rh(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},ah=(t,e)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},ih=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ul=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},fl=320,Xp=320,lh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ch=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),dh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),ph=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),uh=(t,e,n)=>{if(t.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let d=m("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${fl}px`,d.style.maxHeight=`${Xp}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),ih(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},fh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ul(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${fl}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},gh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ul(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${fl}px`,r.style.maxHeight=`${Xp}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},mh=t=>{if(t.length===0)return null;try{let e=m("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ul(o.data))return;let r=m("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},ys=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},hh=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:ys};if(e){let r=e(o);if(r!==null)return r}return ys()},yh=(t,e)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Gp=(t,e,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},bh=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},vh=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let b=m("div");return b.style.display="none",b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id),b}let l=e.visibility??"hover",p=e.align??"right",d=e.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],w=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);w.id=`actions-${t.id}`,w.setAttribute("data-actions-for",t.id);let f=(b,x,P)=>{let W=Bt({icon:b,label:x,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",P),W};return o&&w.appendChild(f("copy","Copy message","copy")),a&&w.appendChild(f("volume-2","Read aloud","read-aloud")),r&&w.appendChild(f("thumbs-up","Upvote","upvote")),s&&w.appendChild(f("thumbs-down","Downvote","downvote")),w},gl=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,w=p?.position??"left",f=d?.position??"below",b=bh(t.role,l),x=m("div",b.join(" "));x.id=`bubble-${t.id}`,x.setAttribute("data-message-id",t.id),x.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):t.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 P=lh(t),W=t.content?.trim()??"",R=P.length>0&&W===ma,D=Fa(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,j=t.role==="assistant"&&D.type!=="none"?mr(D.type,$):null,z=t.role==="assistant"&&j?.isAnimating?.(t)===!0,C=t.role==="assistant"&&j!==null&&(!!t.streaming||z);C&&j?.bubbleClass&&x.classList.add(j.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),t.streaming&&V.classList.add("persona-content-streaming"),C&&j&&(j.containerClass&&V.classList.add(j.containerClass),V.style.setProperty("--persona-stream-step",`${D.speed}ms`),V.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let Y=C?Na(t.content??"",D.buffer,j,t,!!t.streaming):t.content??"",F=e({text:Y,message:t,streaming:!!t.streaming,raw:t.rawContent}),U=F;C&&j?.wrap==="char"?U=ps(F,"char",t.id,{skipTags:j.skipTags}):C&&j?.wrap==="word"&&(U=ps(F,"word",t.id,{skipTags:j.skipTags}));let de=null;if(R?(de=document.createElement("div"),de.innerHTML=U,de.style.display="none",V.appendChild(de)):V.innerHTML=U,C&&j?.useCaret&&!R&&W){let ee=Oa(),ve=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=ve[ve.length-1];if(we?.parentNode)we.parentNode.insertBefore(ee,we.nextSibling);else{let ge=V.lastElementChild;ge?ge.appendChild(ee):V.appendChild(ee)}}if(u&&f==="inline"&&t.createdAt){let ee=Gp(t,d,"span");ee.classList.add("persona-timestamp-inline");let ve=V.lastElementChild;ve?ve.appendChild(ee):V.appendChild(ee)}if(P.length>0){let ee=uh(P,!R&&!!W,()=>{R&&de&&(de.style.display="")});ee?x.appendChild(ee):R&&de&&(de.style.display="")}let ye=ch(t);if(ye.length>0){let ee=fh(ye);ee&&x.appendChild(ee)}let Ee=dh(t);if(Ee.length>0){let ee=gh(Ee);ee&&x.appendChild(ee)}let Ae=ph(t);if(Ae.length>0){let ee=mh(Ae);ee&&x.appendChild(ee)}if(x.appendChild(V),u&&f==="below"&&t.createdAt){let ee=Gp(t,d);ee.classList.add("persona-mt-1"),x.appendChild(ee)}let ne=t.role==="assistant"?sh(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ee=!!(Y&&Y.trim()),ve=D.placeholder==="skeleton",we=ve&&D.buffer==="line"&&ee;if(ee)we&&x.appendChild(us());else if(ve)x.appendChild(us());else{let ge=hh("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ge&&x.appendChild(ge)}}if(ne&&t.stopReason&&!t.streaming&&(W||(V.style.display="none"),x.appendChild(ah(t.stopReason,ne))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let ee=vh(t,o,r);x.appendChild(ee)}if(!c||t.role==="system")return x;let Z=m("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ce=yh(p,t.role);return w==="right"||w==="left"&&t.role==="user"?Z.append(x,ce):Z.append(ce,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z};var hr=new Set,wh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),xh=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
34
+ `):""},Qp=(t,e)=>{let n=hr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let d=ie(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ml=(t,e)=>{let n=t.reasoning,o=m("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(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&hr.has(t.id),l=n.status!=="complete",p=xh(t,r.previewMaxLines??3),d=m("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),w="Thinking...",f=e?.reasoning??{},b=String(n.startedAt??Date.now()),x=()=>{let ye=m("span","");return ye.setAttribute("data-tool-elapsed",b),ye.textContent=pa(n),ye},P=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:w,previewText:p,isActive:l,config:e??{},elapsed:pa(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(u.textContent=P,c.appendChild(u)):P instanceof HTMLElement?c.appendChild(P):(u.textContent=w,c.appendChild(u));let W=m("span","persona-text-xs persona-text-persona-primary");W.textContent=Pd(n),c.appendChild(W);let M=r.loadingAnimation??"none",R=f.activeTextTemplate,D=f.completeTextTemplate,$=l?R:D,j=P instanceof HTMLElement,z=(ye,Ee)=>{u.textContent="";let Ae=ua(ye,""),ne=0;for(let me of Ae){let Z=me.styles.length>0?(()=>{let ce=m("span",me.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return u.appendChild(ce),ce})():u;if(me.isDuration&&l)Z.appendChild(x());else{let ce=me.isDuration?pa(n):me.text;Ee?ne=ro(Z,ce,ne):Z.appendChild(document.createTextNode(ce))}}};if(!j&&$)if(W.style.display="none",u.style.display="",l&&M!=="none"){let ye=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),M==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),z($,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),z($,!0))}else z($,!1);else if(!j&&l&&M!=="none"){u.style.display="";let ye=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Ee=u.textContent||w;u.textContent="",ro(u,Ee,0)}n.status==="complete"&&(u.style.display="none")}else j||(n.status==="complete"?u.style.display="none":u.style.display="");let C=null;if(s){C=m("div","persona-flex persona-items-center");let Ee=ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?C.appendChild(Ee):C.textContent=a?"Hide":"Show";let Ae=m("div","persona-flex persona-items-center persona-ml-auto");Ae.append(C),d.append(c,Ae)}else d.append(c);let V=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&p){let ye=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});wh(V,ye)||(V.textContent=p),V.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,V),o;let Y=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Y.style.display=a?"":"none";let F=n.chunks.join(""),U=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return U.textContent=F||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Y.appendChild(U),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),C){C.innerHTML="";let Ee=ie(a?"chevron-up":"chevron-down",16,"currentColor",2);Ee?C.appendChild(Ee):C.textContent=a?"Hide":"Show"}Y.style.display=a?"":"none",V.style.display=a?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(d,V,Y),o};var yr=new Set,Ch=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Ah=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
35
+ `);let r=no(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
36
+ `):""},hl=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},Sh=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Ah(t,o?.previewMaxLines??3),a=n?Id(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),l&&p.activeTextTemplate?d=qi(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=qi(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:l}},Jp=(t,e,n)=>{let o=yr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=ie(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},yl=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=m("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(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&yr.has(t.id),{summary:p,previewText:d,isActive:c}=Sh(t,e),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let w=m("div","persona-flex persona-flex-col persona-text-left"),f=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),x=()=>{let F=m("span","");return F.setAttribute("data-tool-elapsed",b),F.textContent=Qr(n),F},P=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:e??{},elapsed:Qr(n),createElapsedElement:x});typeof P=="string"&&P.trim()?(f.textContent=P,w.appendChild(f)):P instanceof HTMLElement?w.appendChild(P):(f.textContent=p,w.appendChild(f));let W=s.loadingAnimation??"none",M=o.activeTextTemplate,R=o.completeTextTemplate,D=c?M:R,$=P instanceof HTMLElement,j=(F,U)=>{f.textContent="";let de=n.name?.trim()||"tool",ye=ua(F,de),Ee=0;for(let Ae of ye){let ne=Ae.styles.length>0?(()=>{let me=m("span",Ae.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return f.appendChild(me),me})():f;if(Ae.isDuration&&c)ne.appendChild(x());else{let me=Ae.isDuration?Qr(n):Ae.text;U?Ee=ro(ne,me,Ee):ne.appendChild(document.createTextNode(me))}}};if(!$)if(c&&W!=="none"){let F=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),W==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),D&&j(D,!1);else if(f.classList.add(`persona-tool-loading-${W}`),f.style.setProperty("--persona-tool-anim-duration",`${F}ms`),W==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),D)j(D,!0);else{let U=f.textContent||p;f.textContent="",ro(f,U,0)}}else D&&j(D,!1);let z=null;if(a){z=m("div","persona-flex persona-items-center");let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ie(l?"chevron-up":"chevron-down",16,F,2);U?z.appendChild(U):z.textContent=l?"Hide":"Show";let de=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(z),u.append(w,de)}else u.append(w);let C=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(C.setAttribute("data-persona-collapsed-preview","tool"),C.style.display="none",C.style.whiteSpace="pre-wrap",!l&&c&&s.activePreview&&d){let F=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:d,isActive:c,config:e??{}});Ch(C,F)||(C.textContent=d),C.style.display=""}if(!l&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,C),r;let V=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=l?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let F=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?F.style.color=o.contentTextColor:o.headerTextColor&&(F.style.color=o.headerTextColor),F.textContent=n.name,V.appendChild(F)}if(n.args!==void 0){let F=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Arguments";let de=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",hl(de,o),de.textContent=no(n.args),F.append(U,de),V.appendChild(F)}if(n.chunks&&n.chunks.length){let F=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Activity";let de=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",hl(de,o),de.textContent=n.chunks.join(""),F.append(U,de),V.appendChild(F)}if(n.status==="complete"&&n.result!==void 0){let F=m("div","persona-space-y-1"),U=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(U.style.color=o.labelTextColor),U.textContent="Result";let de=m("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",hl(de,o),de.textContent=no(n.result),F.append(U,de),V.appendChild(F)}if(n.status==="complete"&&typeof n.duration=="number"){let F=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(F.style.color=o.contentTextColor),F.textContent=`Duration: ${n.duration}ms`,V.appendChild(F)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),z){z.innerHTML="";let F=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",U=ie(l?"chevron-up":"chevron-down",16,F,2);U?z.appendChild(U):z.textContent=l?"Hide":"Show"}V.style.display=l?"":"none",C.style.display=l?"none":C.textContent||C.childNodes.length?"":"none"})(),r.append(u,C,V),r};var No=new Map,Ja=t=>{let n=(t.startsWith(Hn)?t.slice(Hn.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Yp=t=>t?.approval!==!1?t?.approval:void 0,Zp=(t,e)=>{let n=Yp(e)?.detailsDisplay??"collapsed";return No.get(t)??n==="expanded"},eu=(t,e,n)=>{let o=Yp(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=ie(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},tu=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Zp(t,n);eu(o,s,n),r.style.display=s?"":"none"};var Ya=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=m("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=ie(p,20,d,2);c&&l.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),w=m("div","persona-flex persona-items-center persona-gap-2"),f=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",w.appendChild(f),!r){let z=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",n.status),n.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):n.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):n.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),w.appendChild(z)}u.appendChild(w);let x=n.toolType==="webmcp"||n.toolName.startsWith(Hn)?Vr(n.toolName):void 0,P=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),W=!n.toolName,M=P||(W?n.description:`The assistant wants to use \u201C${x??Ja(n.toolName)}\u201D.`),R=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(R.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(R.style.color=o.descriptionColor),R.textContent=M,u.appendChild(R),n.reason){let z=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");z.setAttribute("data-approval-reason","true"),o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let C=m("span","persona-font-medium");C.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.appendChild(C),z.appendChild(document.createTextNode(n.reason)),u.appendChild(z)}let D=o?.detailsDisplay??"collapsed",$=!!n.description&&!W,j=$||!!n.parameters;if(D!=="hidden"&&j){let z=Zp(t.id,e),C=m("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");C.type="button",C.setAttribute("data-expand-header","true"),C.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(C.style.color=o.descriptionColor);let V=m("span");V.setAttribute("data-approval-details-label","true");let Y=m("span","persona-inline-flex persona-items-center");Y.setAttribute("data-approval-details-chevron","true"),C.append(V,Y),eu(C,z,e),u.appendChild(C);let F=m("div");if(F.setAttribute("data-approval-details","true"),F.style.display=z?"":"none",$){let U=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,F.appendChild(U)}if(n.parameters){let U=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(U.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=no(n.parameters),F.appendChild(U)}u.appendChild(F)}if(r){let z=m("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let C=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");C.type="button",C.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",C.style.color=o?.approveButtonTextColor??"#ffffff",C.setAttribute("data-approval-action","approve");let V=ie("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",C.appendChild(V));let Y=document.createTextNode(o?.approveLabel??"Approve");C.appendChild(Y);let F=m("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");F.type="button",F.style.backgroundColor=o?.denyButtonColor??"transparent",F.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",F.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,F.setAttribute("data-approval-action","deny");let U=ie("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);U&&(U.style.marginRight="4px",F.appendChild(U));let de=document.createTextNode(o?.denyLabel??"Deny");F.appendChild(de),z.append(C,F),u.appendChild(z)}return a.append(l,u),s.appendChild(a),s};function Th(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function nu(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:l,onDismiss:p}=t,d=t.container??Th(e),c=!1,u=null,w=()=>{if(!c)return;let x=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${x.width}px`);let P=o==="top-start"||o==="top-end"?x.top-r-n.getBoundingClientRect().height:x.bottom+r,W=o==="bottom-end"||o==="top-end"?x.right-n.getBoundingClientRect().width:x.left;n.style.top=`${P}px`,n.style.left=`${W}px`},f=()=>{c&&(c=!1,u&&(u(),u=null),n.remove())},b=()=>{if(c)return;c=!0,a!=null&&(n.style.zIndex=String(a)),d.appendChild(n),w();let x=(e.ownerDocument??document).defaultView??window,P=e.ownerDocument??document,W=()=>{if(!e.isConnected){f(),p?.("anchor-removed");return}w()},M=D=>{let $=typeof D.composedPath=="function"?D.composedPath():[];$.includes(n)||$.includes(e)||(f(),p?.("outside"))},R=x.setTimeout(()=>{P.addEventListener("pointerdown",M,!0)},0);x.addEventListener("scroll",W,!0),x.addEventListener("resize",W),u=()=>{x.clearTimeout(R),P.removeEventListener("pointerdown",M,!0),x.removeEventListener("scroll",W,!0),x.removeEventListener("resize",W)},l?.()};return{get isOpen(){return c},open:b,close:f,toggle:()=>c?f():b(),reposition:w,destroy:f}}function ou(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Mh=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),ru=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},Oo=(t,e)=>{ru(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Eh=t=>t?.approval!==!1?t?.approval:void 0,kh=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return No.get(t)??n==="expanded"},bl=t=>{let e=m("span","persona-approval-kbd");return e.textContent=t,e},Lh=(t,e)=>{let n=m("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Hn)?Vr(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??Ja(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},Ph=t=>{let e=m("div","persona-approval-resolved"),n=ie("ban",15,"currentColor",2);n&&e.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=t.toolName?Ja(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Ih=(t,e,n,o,r,s,a)=>{let l=m("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,w=u&&kh(e.id,o),f=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",x=m("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",w?"true":"false"),x.setAttribute("aria-label",w?b:f)):x.setAttribute("data-static","true");let P=m("span","persona-approval-logo"),W=ie("shield-check",16,"currentColor",2);W&&P.appendChild(W),x.appendChild(P);let M=Lh(n,o);if(u){let C=m("span","persona-approval-toggle");C.setAttribute("aria-hidden","true");let V=ie("chevron-down",14,"currentColor",2);V&&C.appendChild(V),M.append(" "),M.appendChild(C)}x.appendChild(M),l.appendChild(x);let R=m("div","persona-approval-body");if(u){let C=m("div","persona-approval-details");if(C.setAttribute("data-role","params"),C.hidden=!w,d){let V=m("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,C.appendChild(V)}if(c){let V=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=no(n.parameters),C.appendChild(V)}R.appendChild(C)}if(n.reason){let C=m("p","persona-approval-reason");o?.reasonColor?C.style.color=o.reasonColor:o?.descriptionColor&&(C.style.color=o.descriptionColor);let V=m("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,C.append(V,document.createTextNode(n.reason)),R.appendChild(C)}let D=m("div","persona-approval-actions"),$=null,j=C=>{o?.approveButtonColor&&(C.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(C.style.color=o.approveButtonTextColor)},z=m("button","persona-approval-deny");if(z.type="button",z.setAttribute("data-action","deny"),o?.denyButtonColor&&(z.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(z.style.color=o.denyButtonTextColor),z.append(o?.denyLabel??"Deny"),a){let C=m("div","persona-approval-split"),V=m("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),j(V),V.append(o?.approveLabel??"Always allow",bl("\u23CE"));let Y=m("button","persona-approval-caret");Y.type="button",Y.setAttribute("data-action","toggle-menu"),Y.setAttribute("aria-label","More options"),j(Y);let F=ie("chevron-down",15,"currentColor",2);F&&Y.appendChild(F),C.append(V,Y),D.append(C,z),z.append(bl("Esc"));let U=m("div","persona-approval-menu"),de=m("button","persona-approval-menu-item");de.type="button",de.append("Allow once",bl("\u2318\u23CE")),U.appendChild(de),$=nu({anchor:C,content:U,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,$),de.addEventListener("click",()=>{Oo(t,e.id),r()})}else{let C=m("button","persona-approval-primary persona-approval-primary--solo");C.type="button",C.setAttribute("data-action","allow"),j(C),C.append(o?.approveLabel??"Allow"),D.append(C,z)}return R.appendChild(D),l.appendChild(R),l.addEventListener("click",C=>{let V=C.target instanceof Element?C.target.closest("[data-action]"):null;if(!V)return;let Y=V.getAttribute("data-action");if(Y==="toggle-params"){let F=l.querySelector('[data-role="params"]');if(F){let U=F.hidden;F.hidden=!U,x.setAttribute("aria-expanded",U?"true":"false"),x.setAttribute("aria-label",U?b:f),No.set(e.id,U)}return}if(Y==="toggle-menu"){$?.toggle();return}if(Y==="always"){Oo(t,e.id),r({remember:!0});return}if(Y==="allow"){Oo(t,e.id),r();return}if(Y==="deny"){Oo(t,e.id),s();return}}),l},su=()=>{let t=Mh();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let p=Eh(a);if(l.status!=="pending"){if(Oo(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Ph(l)}ru(t,o.id);let d=p?.enableAlwaysAllow===!0,c=Ih(t,o,l,p,r,s,d);if(d){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let u=w=>{ou(w)||o.id===t.latestPendingApprovalId&&(w.key!=="Escape"&&w.key!=="Enter"||(w.preventDefault(),w.stopImmediatePropagation(),Oo(t,o.id),w.key==="Escape"?s():w.metaKey||w.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])Oo(t,o);t.latestPendingApprovalId=null}}};var au=t=>{let e=[],n=null;return{buttons:e,render:(r,s,a,l,p,d)=>{t.innerHTML="",e.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(l??(s?s.getMessages():[])).some(P=>P.role==="user"))return;let u=document.createDocumentFragment(),w=s?s.isStreaming():!1,f=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(b=>{let x=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=b,x.disabled=w,p?.fontFamily&&(x.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(x.style.fontWeight=p.fontWeight),p?.paddingX&&(x.style.paddingLeft=p.paddingX,x.style.paddingRight=p.paddingX),p?.paddingY&&(x.style.paddingTop=p.paddingY,x.style.paddingBottom=p.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(x),e.push(x)}),t.appendChild(u),c){let b=JSON.stringify(r);b!==n&&(n=b,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var bs=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){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),this.store?.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var vs=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var Rh=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Wh=new Set(["step_start","execution_start"]),Bh=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Hh=new Set(["step_complete","agent_turn_complete"]),Dh=new Set(["flow_complete","agent_complete"]),iu=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),cu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),sn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,_o=(t,e)=>{let n=t[e];return cu(n)?n:void 0};function vl(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Za(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Fh(t,e){return typeof e.type=="string"?e.type:t}function Nh(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Oh(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function lu(t){let e=_o(t,"result"),n=[_o(t,"tokens"),_o(t,"totalTokens"),e?_o(e,"tokens"):void 0,_o(t,"usage"),e?_o(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=sn(o.output)??sn(o.outputTokens)??sn(o.completionTokens);if(r!==void 0)return r}return sn(t.outputTokens)??sn(t.completionTokens)??(e?sn(e.outputTokens)??sn(e.completionTokens):void 0)}function _h(t){let e=_o(t,"result");return sn(t.executionTime)??sn(t.executionTimeMs)??sn(t.execution_time)??sn(t.duration)??(e?sn(e.executionTime)??sn(e.executionTimeMs):void 0)}function $h(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ws=class{constructor(e=$h){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:Za(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){if(!cu(n)){iu.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Fh(e,n),r=this.now();if(Rh.has(o)){this.startRun(r);return}if(Wh.has(o)){this.run||this.startRun(r);return}if(Bh.has(o)){if(!Oh(o,n))return;let s=Nh(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+vl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Za(l,p),outputTokens:l,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Hh.has(o)){if(!this.run)return;let s=this.run,a=lu(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+vl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Za(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(Dh.has(o)){if(!this.run)return;let s=this.run,a=lu(n),l=a??s.exactOutputTokens+vl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Za(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(iu.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:_h(n)??o-e.startedAt}};function br(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Uh={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)"}},zh={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},jh=["flowName","stepName","reasoningText","text","name","tool","toolName"],qh=100;function Vh(t,e){let n={...Uh,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return zh}function Kh(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Gh(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Xh(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Qh(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function Jh(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function Yh(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Zh(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function ey(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=m("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function wl(t,e,n,o,r,s,a,l){let p=r.has(t.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");br(d,o.classNames?.eventRow);let c=a.find(w=>w.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let w=c.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(w)return d.appendChild(w),d}return d.appendChild(u()),d;function u(){let w=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",t.id);let b=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),x=ie(p?"chevron-down":"chevron-right","14px","currentColor",2);x&&b.appendChild(x);let P=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=o.timestampFormat??"relative";P.textContent=W==="relative"?Kh(t.timestamp,n):Gh(t.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let R=Vh(t.type,o.badgeColors),D=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");D.style.backgroundColor=R.bg,D.style.color=R.text,D.style.borderColor=R.text+"50",D.textContent=t.type;let $=o.descriptionFields??jh,j=Xh(t.payload,$),z=null;j&&(z=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),z.textContent=j);let C=m("div","persona-flex-1 persona-min-w-0"),V=m("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),Y=ie("clipboard","12px","currentColor",1.5);return Y&&V.appendChild(Y),V.addEventListener("click",async F=>{F.stopPropagation(),await Qh(Jh(t)),V.innerHTML="";let U=ie("check","12px","currentColor",1.5);U&&V.appendChild(U),setTimeout(()=>{V.innerHTML="";let de=ie("clipboard","12px","currentColor",1.5);de&&V.appendChild(de)},1500)}),f.appendChild(b),f.appendChild(P),M&&f.appendChild(M),f.appendChild(D),z&&f.appendChild(z),f.appendChild(C),f.appendChild(V),w.appendChild(f),p&&w.appendChild(ey(t,a,l)),w}}function du(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",u=r?.features?.eventStream??{},w=s.find(b=>b.renderEventStreamView);if(w?.renderEventStreamView&&r){let b=w.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return f();function f(){let b=u.classNames,x=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");br(x,b?.panel);let P=[],W="",M="",R=null,D=[],$={},j=0,z=Ba(),C=0,V=0,Y=!1,F=null,U=!1,de=0,ye=new Set,Ee=new Map,Ae="",ne="",me=null,Z,ce,ee,ve,we=null,ge=null,Me=null;function Se(){let H=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),q=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(br(q,b?.headerBar),a){ge=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ge.style.cursor="help",we=m("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),we.textContent="-- tok/s",Me=m("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Me.style.display="none",Me.style.pointerEvents="none";let Je=ge,co=Me,po=()=>{if(!co.textContent)return;let Ts=Je.getBoundingClientRect(),Jt=H.getBoundingClientRect();co.style.left=`${Ts.left-Jt.left}px`,co.style.top=`${Ts.bottom-Jt.top+4}px`,co.style.display="block"},ni=()=>{co.style.display="none"};ge.addEventListener("mouseenter",po),ge.addEventListener("mouseleave",ni),ge.appendChild(we)}let se=m("div","persona-flex-1");Z=m("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let tt=m("option","");tt.value="",tt.textContent="All events (0)",Z.appendChild(tt),ce=m("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ce.type="button",ce.title="Copy All";let ct=ie("clipboard-copy","12px","currentColor",1.5);ct&&ce.appendChild(ct);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",ce.appendChild(K),ge&&q.appendChild(ge),q.appendChild(se),q.appendChild(Z),q.appendChild(ce);let Ue=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");br(Ue,b?.searchBar);let Ce=ie("search","14px","var(--persona-muted, #9ca3af)",1.5),He=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ce&&He.appendChild(Ce),ee=m("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),br(ee,b?.searchInput),ee.type="text",ee.placeholder="Search event payloads...",ve=m("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ve.type="button",ve.style.display="none";let Pe=ie("x","12px","currentColor",2);return Pe&&ve.appendChild(Pe),Ue.appendChild(He),Ue.appendChild(ee),Ue.appendChild(ve),H.appendChild(q),H.appendChild(Ue),Me&&H.appendChild(Me),H}let je,Ne=s.find(H=>H.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?je=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>Se(),eventCount:e.getSize(),filteredCount:0,onFilterChange:q=>{W=q,Re(),be()},onSearchChange:q=>{M=q,Re(),be()}})??Se():je=Se();let Ie=m("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ie.style.display="none";function Be(){if(!a||!we||!ge)return;let H=a(),q=Yh(H);we.textContent=q;let se=Zh(H);Me&&(Me.textContent=se,se||(Me.style.display="none")),ge.setAttribute("aria-label",se?`Throughput: ${q}, ${se}`:`Throughput: ${q}`)}let it=m("div","persona-flex-1 persona-min-h-0 persona-relative"),_e=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");_e.style.height="100%";let Qe=m("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");br(Qe,b?.scrollIndicator),Qe.style.display="none",Qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let an=ie(d,"14px","currentColor",2);an&&Qe.appendChild(an);let kt=m("span","");kt.textContent=c,Qe.appendChild(kt);let gt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");gt.style.display="none",it.appendChild(_e),it.appendChild(gt),it.appendChild(Qe),x.setAttribute("tabindex","0"),x.appendChild(je),x.appendChild(Ie),x.appendChild(it);function ke(){let H=e.getAll(),q={};for(let Ue of H)q[Ue.type]=(q[Ue.type]||0)+1;let se=Object.keys(q).sort(),tt=se.length!==D.length||!se.every((Ue,Ce)=>Ue===D[Ce]),We=!tt&&se.some(Ue=>q[Ue]!==$[Ue]),ct=H.length!==Object.values($).reduce((Ue,Ce)=>Ue+Ce,0);if(!tt&&!We&&!ct||(D=se,$=q,!Z))return;let K=Z.value;if(Z.options[0].textContent=`All events (${H.length})`,tt){for(;Z.options.length>1;)Z.remove(1);for(let Ue of se){let Ce=m("option","");Ce.value=Ue,Ce.textContent=`${Ue} (${q[Ue]||0})`,Z.appendChild(Ce)}K&&se.includes(K)?Z.value=K:K&&(Z.value="",W="")}else for(let Ue=1;Ue<Z.options.length;Ue++){let Ce=Z.options[Ue];Ce.textContent=`${Ce.value} (${q[Ce.value]||0})`}}function he(){let H=e.getAll();if(W&&(H=H.filter(q=>q.type===W)),M){let q=M.toLowerCase();H=H.filter(se=>se.type.toLowerCase().includes(q)||se.payload.toLowerCase().includes(q))}return H}function lt(){return W!==""||M!==""}function Re(){j=0,C=0,z.resume(),Qe.style.display="none"}function fe(H){ye.has(H)?ye.delete(H):ye.add(H),me=H;let q=_e.scrollTop,se=z.isFollowing();U=!0,z.pause(),be(),_e.scrollTop=q,se&&z.resume(),U=!1}function le(){return io(_e,50)}function be(){V=Date.now(),Y=!1,Be(),ke();let H=e.getEvictedCount();H>0?(Ie.textContent=`${H.toLocaleString()} older events truncated`,Ie.style.display=""):Ie.style.display="none",P=he();let q=P.length,se=e.getSize()>0;q===0&&se&&lt()?(gt.textContent=M?`No events matching '${M}'`:"No events matching filter",gt.style.display="",_e.style.display="none"):(gt.style.display="none",_e.style.display=""),ce&&(ce.title=lt()?`Copy Filtered (${q})`:"Copy All"),p&&!z.isFollowing()&&q>j&&(C+=q-j,kt.textContent=c?`${c}${C>0?` (${C})`:""}`:"",Qe.style.display=""),j=q;let tt=e.getAll(),We=tt.length>0?tt[0].timestamp:0,ct=new Set(P.map(Ce=>Ce.id));for(let Ce of ye)ct.has(Ce)||ye.delete(Ce);let K=W!==Ae||M!==ne,Ue=Ee.size===0&&P.length>0;if(K||Ue||P.length===0){_e.innerHTML="",Ee.clear();let Ce=document.createDocumentFragment();for(let He=0;He<P.length;He++){let Pe=wl(P[He],He,We,u,ye,fe,s,r);Ee.set(P[He].id,Pe),Ce.appendChild(Pe)}_e.appendChild(Ce),Ae=W,ne=M,me=null}else{if(me!==null){let He=Ee.get(me);if(He&&He.parentNode===_e){let Pe=P.findIndex(Je=>Je.id===me);if(Pe>=0){let Je=wl(P[Pe],Pe,We,u,ye,fe,s,r);_e.insertBefore(Je,He),He.remove(),Ee.set(me,Je)}}me=null}let Ce=new Set(P.map(He=>He.id));for(let[He,Pe]of Ee)Ce.has(He)||(Pe.remove(),Ee.delete(He));for(let He=0;He<P.length;He++){let Pe=P[He];if(!Ee.has(Pe.id)){let Je=wl(Pe,He,We,u,ye,fe,s,r);Ee.set(Pe.id,Je),_e.appendChild(Je)}}}z.isFollowing()&&(_e.scrollTop=_e.scrollHeight)}function vt(){if(Date.now()-V>=qh){F!==null&&(cancelAnimationFrame(F),F=null),be();return}Y||(Y=!0,F=requestAnimationFrame(()=>{F=null,be()}))}let N=(H,q)=>{if(!ce)return;ce.innerHTML="";let se=ie(H,"12px","currentColor",1.5);se&&ce.appendChild(se);let tt=m("span","persona-text-xs");tt.textContent="Copy All",ce.appendChild(tt),setTimeout(()=>{ce.innerHTML="";let We=ie("clipboard-copy","12px","currentColor",1.5);We&&ce.appendChild(We);let ct=m("span","persona-text-xs");ct.textContent="Copy All",ce.appendChild(ct),ce.disabled=!1},q)},oe=async()=>{if(ce){ce.disabled=!0;try{let H;lt()?H=P:n?(H=await n(),H.length===0&&(H=e.getAll())):H=e.getAll();let q=H.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(q,null,2)),N("check",1500)}catch{N("x",1500)}}},Fe=()=>{Z&&(W=Z.value,Re(),be())},Le=()=>{!ee||!ve||(ve.style.display=ee.value?"":"none",R&&clearTimeout(R),R=setTimeout(()=>{M=ee.value,Re(),be()},150))},E=()=>{!ee||!ve||(ee.value="",M="",ve.style.display="none",R&&clearTimeout(R),Re(),be())},Q=()=>{if(U)return;let H=_e.scrollTop,{action:q,nextLastScrollTop:se}=Ha({following:z.isFollowing(),currentScrollTop:H,lastScrollTop:de,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});de=se,q==="resume"?(z.resume(),C=0,Qe.style.display="none"):q==="pause"&&(z.pause(),p&&(kt.textContent=c,Qe.style.display=""))},y=H=>{let q=Da({following:z.isFollowing(),deltaY:H.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});q==="pause"?(z.pause(),p&&(kt.textContent=c,Qe.style.display="")):q==="resume"&&(z.resume(),C=0,Qe.style.display="none")},S=()=>{p&&(_e.scrollTop=_e.scrollHeight,z.resume(),C=0,Qe.style.display="none")},k=H=>{let q=H.target;if(!q||q.closest("button"))return;let se=q.closest("[data-event-id]");if(!se)return;let tt=se.getAttribute("data-event-id");tt&&fe(tt)},B=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),ee?.focus(),ee?.select();return}H.key==="Escape"&&(ee&&document.activeElement===ee?(E(),ee.blur(),x.focus()):o&&o())};ce&&ce.addEventListener("click",oe),Z&&Z.addEventListener("change",Fe),ee&&ee.addEventListener("input",Le),ve&&ve.addEventListener("click",E),_e.addEventListener("scroll",Q),_e.addEventListener("wheel",y,{passive:!0}),_e.addEventListener("click",k),Qe.addEventListener("click",S),x.addEventListener("keydown",B);function G(){R&&clearTimeout(R),F!==null&&(cancelAnimationFrame(F),F=null),Y=!1,Ee.clear(),ce&&ce.removeEventListener("click",oe),Z&&Z.removeEventListener("change",Fe),ee&&ee.removeEventListener("input",Le),ve&&ve.removeEventListener("click",E),_e.removeEventListener("scroll",Q),_e.removeEventListener("wheel",y),_e.removeEventListener("click",k),Qe.removeEventListener("click",S),x.removeEventListener("keydown",B)}return{element:x,update:vt,destroy:G}}}function pu(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let w=u;return s.findIndex(f=>f===w||f.contains(w))},d=u=>{let w=p(u.target);if(w<0)return;let f=w;if(u.key===r)f=Math.min(w+1,s.length-1);else if(u.key===o)f=Math.max(w-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==w&&e.onSelect(f)},c=u=>{let w=p(u.target);w>=0&&l(s[w])};return t.addEventListener("keydown",d),t.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(u,w){if(s=u,u.forEach((f,b)=>{f.setAttribute("role","tab");let x=b===w;f.setAttribute("aria-selected",x?"true":"false"),f.tabIndex=x||w<0&&b===0?0:-1}),a){let f=(w>=0?u[w]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",d),t.removeEventListener("focusin",c)}}}function uu(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=N=>({start:N===!1?!1:typeof N=="object"&&N?N.start!==!1:!0,end:N===!1?!1:typeof N=="object"&&N?N.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),w=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{w?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),U?.hide()};w&&w.addEventListener("click",()=>{f(),e.onDismiss?.()});let b=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let x=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");x.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&x.classList.add("persona-artifact-toolbar-document");let P=m("span","persona-text-xs persona-font-medium persona-truncate");P.textContent=s;let W=Bt({icon:"x",label:a});W.addEventListener("click",()=>{f(),e.onDismiss?.()});let M="rendered",R=ka({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:N=>{M=N==="source"?"source":"rendered",le()}}),D=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,j=n?.documentToolbarShowCopyChevron===!0,z=n?.documentToolbarCopyMenuItems,C=!!(j&&z&&z.length>0),V=null,Y,F=null,U=null;if(r&&($||j)&&!C){if(Y=$?Do({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),j){let N=ie("chevron-down",14,"currentColor",2);N&&Y.appendChild(N)}}else r&&C?(V=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=$?Do({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),F=Bt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),V.append(Y,F)):r?Y=Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Y=Bt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Y.classList.add("persona-hidden"));let de=r?Bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"refresh-cw",label:"Refresh"}),ye=r?Bt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):Bt({icon:"x",label:a}),Ee=Bt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Ee.classList.add("persona-hidden");let Ae=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ne=t.features?.artifacts?.toolbarActions??[],me=()=>{let N=Ie.find(E=>E.id===Be)??Ie[Ie.length-1],oe=N?.id??null,Fe=N?.artifactType==="markdown"?N.markdown??"":"",Le=N?JSON.stringify({component:N.component,props:N.props},null,2):"";return{markdown:Fe,jsonPayload:Le,id:oe}},Z=async()=>{let N=Ie.find(oe=>oe.id===Be)??Ie[Ie.length-1];try{await navigator.clipboard.writeText(cs(N))}catch{}};if(Y.addEventListener("click",async()=>{let N=n?.onDocumentToolbarCopyMenuSelect;if(N&&C){let{markdown:oe,jsonPayload:Fe,id:Le}=me();try{await N({actionId:"primary",artifactId:Le,markdown:oe,jsonPayload:Fe})}catch{}return}await Z()}),F&&z?.length){let N=()=>b.closest("[data-persona-root]")??document.body,oe=()=>{U=fr({items:z.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:Le,jsonPayload:E,id:Q}=me(),y=n?.onDocumentToolbarCopyMenuSelect;try{y?await y({actionId:Fe,artifactId:Q,markdown:Le,jsonPayload:E}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(Le):Fe==="json"||Fe==="source"?await navigator.clipboard.writeText(E):await navigator.clipboard.writeText(Le||E)}catch{}},anchor:V??F,position:"bottom-right",portal:N()})};b.isConnected?oe():requestAnimationFrame(oe),F.addEventListener("click",Fe=>{Fe.stopPropagation(),U?.toggle()})}de.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}le()}),ye.addEventListener("click",()=>{f(),e.onDismiss?.()});let ce=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)x.replaceChildren(),V?D.append(V,de,ye):D.append(Y,de,ye),D.insertBefore(Ae,ye),D.insertBefore(Ee,ye),x.append(R.element,ce,D);else{let N=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");N.append(Y,Ae,Ee,W),x.appendChild(P),x.appendChild(N)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let ee=m("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&ee.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=t.features?.artifacts?.renderTabBar,we=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ge=pu(ee,{onSelect:N=>e.onSelect(Ie[N].id)}),Me=N=>{let oe=N.scrollWidth-N.clientWidth,Fe=oe>1,Le=Math.abs(N.scrollLeft);N.classList.toggle("persona-artifact-tab-fade-start",c&&Fe&&Le>1),N.classList.toggle("persona-artifact-tab-fade-end",u&&Fe&&Le<oe-1)},Se=0,je=()=>{if(Se)return;let N=()=>{Se=0,Me(ee)};Se=typeof requestAnimationFrame=="function"?requestAnimationFrame(N):setTimeout(N,0)};ee.addEventListener("scroll",()=>je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Me(ee)).observe(ee);let Ne=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let N of[ee,we])N.style.paddingLeft=l,N.style.paddingRight=l;Ne.style.padding=l}b.appendChild(x),b.appendChild(ee),b.appendChild(we),b.appendChild(Ne);let Ie=[],Be=null,it=!1,_e=!0,Qe=!1,an=null,kt="",gt=null,ke=!1,he=N=>N.artifactType==="markdown"&&!!N.file||r?M:"rendered",lt=N=>{r||(N&&!ke?(x.insertBefore(R.element,P),ke=!0):!N&&ke&&(R.element.remove(),ke=!1))},Re=()=>Be&&Ie.find(N=>N.id===Be)||Ie[Ie.length-1],fe=()=>{let N=is(Re());if(!N){Ae.replaceChildren();return}let oe=ne.filter(Fe=>Fe.visible===void 0||Fe.visible(N)).map(Fe=>gr(Fe,{documentChrome:r,onClick:()=>{let Le=is(Re());if(Le)try{Promise.resolve(Fe.onClick(Le)).catch(()=>{})}catch{}}}));Ae.replaceChildren(...oe)},le=()=>{fe();let N=r&&Ie.length<=1,oe=!!ve;if(ee.classList.toggle("persona-hidden",N||oe),we.classList.toggle("persona-hidden",N||!oe),oe&&ve){let E=Ie.map(Q=>Q.id).join("|")+" "+(Be??"");if(E!==kt){kt=E;let Q=ve({records:Ie,selectedId:Be,onSelect:e.onSelect});we.firstElementChild!==Q&&we.replaceChildren(Q)}}else{ge.beforeRender(),ee.replaceChildren();let E=[],Q=-1;for(let[y,S]of Ie.entries()){let k=m("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");k.type="button";let B=S.artifactType==="markdown"?S.file:void 0,G=B?Mn(B.path):S.title||S.id.slice(0,8),H=B?.path||S.title||G;k.textContent=G,k.title=H,k.setAttribute("aria-label",H),S.id===Be&&(k.classList.add("persona-bg-persona-container","persona-border-persona-border"),Q=y),k.addEventListener("click",()=>e.onSelect(S.id)),ee.appendChild(k),E.push(k)}if(ge.render(E,Q),Q>=0&&Be!==an){an=Be;let y=E[Q];typeof y.scrollIntoView=="function"&&y.scrollIntoView({block:"nearest",inline:"nearest"})}Me(ee)}let Fe=Be&&Ie.find(E=>E.id===Be)||Ie[Ie.length-1];if(!Fe){Ne.replaceChildren(),gt=null,lt(!1);return}let Le=Fe.artifactType==="markdown"?Fe.file:void 0;if(lt(!!Le),r){let E=Le?oo(Le):Fe.artifactType==="markdown"?"MD":Fe.component??"Component",Q=(Fe.title||"Document").trim(),y=Le?Mn(Le.path):Q.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${y} \xB7 ${E}`}else P.textContent=Le?Mn(Le.path):s;gt?(gt.el.parentElement!==Ne&&Ne.replaceChildren(gt.el),gt.update(Fe)):(gt=Ia(Fe,{config:t,resolveViewMode:he}),Ne.replaceChildren(gt.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},be=()=>{let N=Ie.length>0;if(b.classList.toggle("persona-hidden",!N),w){let Le=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;N&&Le&&it?(w.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(w.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},vt=()=>{Qe=!1,le(),be()};return{element:b,backdrop:w,update(N){Ie=N.artifacts,Be=N.selectedId??N.artifacts[N.artifacts.length-1]?.id??null,Ie.length>0&&(it=!0),Qe=!0,_e&&vt()},setMobileOpen(N){it=N,!N&&w?(w.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):be()},setExpanded(N){let oe=ie(N?"minimize":"maximize",16,"currentColor",2);oe&&Ee.replaceChildren(oe);let Fe=N?"Collapse artifacts panel":"Expand artifacts panel";Ee.setAttribute("aria-label",Fe),Ee.title=Fe},setExpandToggleVisible(N){Ee.classList.toggle("persona-hidden",!N)},setCopyButtonVisible(N){r||Y.classList.toggle("persona-hidden",!N)},setCustomActions(N){ne=N,fe()},setTabFade(N){let oe=d(N);oe.start===c&&oe.end===u||(c=oe.start,u=oe.end,Me(ee))},setRenderTabBar(N){N!==ve&&(ve=N,kt="",le())},setVisible(N){N!==_e&&(_e=N,N&&Qe&&vt())}}}function Qt(t){return t?.features?.artifacts?.enabled===!0}function fu(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Qt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function ty(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var gu=["panel","seamless","detached"];function xl(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&gu.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function Cl(t){return!t||!Qt(t)?!1:xl(t)==="detached"}function xs(t,e){if(!Qt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),ty(t),fu(t,e);return}let n=e.features?.artifacts?.layout,o=xl(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),fu(t,e)}function Cs(t,e){for(let l of gu)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Qt(e))return;let n=e.features?.artifacts?.layout,o=xl(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function mu(t,e){return!e||!Qt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function ny(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function oy(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function ry(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function sy(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Al(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function hu(t,e,n,o,r,s){let a=ny(r,200),l=sy(e,n,o,200);l=Math.max(a,l);let p=oy(s);return p!==null&&(l=Math.min(l,p)),ry(t,a,l)}var yu={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"}},Sl=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=yu[a]??yu.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let b=m("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let x=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${e.id}-${a}-${b.name}`;let P=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=b.label,x.appendChild(P);let W=b.type??"text",M;W==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=W),M.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",M.id=`${e.id}-${a}-${b.name}`,M.name=b.name,M.placeholder=b.placeholder??"",b.required&&(M.required=!0),x.appendChild(M),c.appendChild(x)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),w=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(w),u.appendChild(f),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let x=n.formEndpoint??"/form",P=new FormData(c),W={};P.forEach((M,R)=>{W[R]=M}),W.type=a,f.disabled=!0,w.textContent="Submitting\u2026";try{let M=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let R=await M.json();w.textContent=R.message??"Thanks! We'll be in touch soon.",R.success&&R.nextPrompt&&await o.sendMessage(String(R.nextPrompt))}catch(M){w.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Tl=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Ml=new Tl;var bu=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var ay=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},iy=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},kl=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=ay(t),n=iy(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},El=t=>typeof t=="string"?t:t==null?"":String(t),As={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:El(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=El(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:El(n.text)}}},vu=t=>Array.isArray(t)?t.map(e=>String(e)):[],Ll=t=>{let e=new Set(vu(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(vu(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let d of t.handlers)if(d)try{let c=()=>{t.emit("action:resubmit",p)},u=d(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let w=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:w,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var ly=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},cy=t=>t.map(e=>({...e,streaming:!1})),dy=t=>t.map(e=>({...e,status:"complete"})),wu=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?ly(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?cy(n.messages):void 0,artifacts:n.artifacts?dy(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Pl=require("partial-json");function xu(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=On.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Cu(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Il(t){let e=Cu(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Au(t){let e=Cu(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var py=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Su(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=py}=t,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,w=document.createElement("div");w.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,f.appendChild(b);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,f.appendChild(x),w.appendChild(f);let P=document.createElement("div");P.className="persona-feedback-rating persona-feedback-rating-csat",P.setAttribute("role","radiogroup"),P.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let j=1;j<=5;j++){let z=document.createElement("button");z.type="button",z.className="persona-feedback-rating-btn persona-feedback-star-btn",z.setAttribute("role","radio"),z.setAttribute("aria-checked","false"),z.setAttribute("aria-label",`${j} star${j>1?"s":""}: ${d[j-1]}`),z.title=d[j-1],z.dataset.rating=String(j),z.innerHTML=`
31
37
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
32
38
  <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>
33
39
  </svg>
34
- `,P.addEventListener("click",()=>{g=S,W.forEach((z,U)=>{let k=U<S;z.classList.toggle("selected",k),z.setAttribute("aria-checked",U===S-1?"true":"false")})}),W.push(P),T.appendChild(P)}h.appendChild(T);let E=null;if(d){let S=document.createElement("div");S.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"),S.appendChild(E),h.appendChild(S)}let H=document.createElement("div");H.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=l,B.addEventListener("click",()=>{t==null||t(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let S=(E==null?void 0:E.value.trim())||void 0;await e(g,S),u.remove()}catch(S){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),H.appendChild(B),H.appendChild(I),h.appendChild(H),u.appendChild(h),u}function Dg(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:l="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,y.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=o,y.appendChild(T),m.appendChild(y);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let B=document.createElement("span");B.className="persona-feedback-label-high",B.textContent=u,E.appendChild(H),E.appendChild(B);let I=document.createElement("div");I.className="persona-feedback-numbers";let S=[];for(let _=0;_<=10;_++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${_} out of 10`),O.textContent=String(_),O.dataset.rating=String(_),_<=6?O.classList.add("persona-feedback-detractor"):_<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{h=_,S.forEach((Z,ke)=>{Z.classList.toggle("selected",ke===_),Z.setAttribute("aria-checked",ke===_?"true":"false")})}),S.push(O),I.appendChild(O)}W.appendChild(E),W.appendChild(I),m.appendChild(W);let P=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),_.appendChild(P),m.appendChild(_)}let z=document.createElement("div");z.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=l,U.addEventListener("click",()=>{t==null||t(),g.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(h===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let _=(P==null?void 0:P.value.trim())||void 0;await e(h,_),g.remove()}catch(_){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),z.appendChild(U),z.appendChild(k),m.appendChild(z),g.appendChild(m),g}var Ls="persona-chat-history",Lb=30*1e3,Pb={"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 Ib(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 l=a.getAsFile();if(!l)continue;if(l.name){e.push(l);continue}let d=(o=Pb[l.type])!=null?o:"png";e.push(new File([l],`clipboard-image-${Date.now()}.${d}`,{type:l.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 vi(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 Rb(n){var e,t,r,o,s,a,l,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=(l=n.persist)==null?void 0:l.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function Wb(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var Ml=n=>!n||typeof n!="object"?{}:{...n},Ng=n=>n.map(e=>({...e,streaming:!1})),Fg=(n,e,t)=>{let r=n!=null&&n.markdown?ka(n.markdown):null,o=La(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 u,g,h;let a=(u=s.text)!=null?u:"",l=(g=s.message.rawContent)!=null?g:null;if(e){let m=e.process({text:a,raw:l!=null?l:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&t&&t())}let d=$o()!==null,c;if(n!=null&&n.postprocessMessage){let m=n.postprocessMessage({...s,text:a,raw:(h=l!=null?l:s.text)!=null?h:""});c=o?o(m):m}else if(r){let m=s.streaming?Hu(a):a,y=r(m);c=o&&d?o(y):y}else c=ho(a);return c}};function Og(n){var l,d,c,u;let e=v("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=(l=n==null?void 0:n.iconName)!=null?l:"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=(u=n==null?void 0:n.iconStrokeWidth)!=null?u:.5,a=ye(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let g=v("span","persona-drop-overlay-label");g.textContent=n.label,e.appendChild(g)}return e}var _g=(n,e,t)=>{var wc,xc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Rc,Wc,Hc,Bc,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;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=Pm(e),o=xl.getForInstance(r.plugins),{plugin:s,teardown:a}=gg();r.components&&Xo.registerAll(r.components);let l=Lg(),c=r.persistState===!1?null:(wc=r.storageAdapter)!=null?wc:Ig(),u={},g=null,h=!1,m=i=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(i);if(p&&typeof p=="object"&&"state"in p){let{state:f,open:b}=p;return b&&(h=!0),f}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return i};if(c!=null&&c.load)try{let i=c.load();if(i&&typeof i.then=="function")g=i.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return m(f)});else{let p=i!=null?i:{messages:[],metadata:{}},f=m(p);f.metadata&&(u=Ml(f.metadata)),(xc=f.messages)!=null&&xc.length&&(r={...r,initialMessages:f.messages}),(Cc=f.artifacts)!=null&&Cc.length&&(r={...r,initialArtifacts:f.artifacts,initialSelectedArtifactId:(Ac=f.selectedArtifactId)!=null?Ac:null})}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(r.onStateLoaded)try{let i=m({messages:[],metadata:{}});(Sc=i.messages)!=null&&Sc.length&&(r={...r,initialMessages:i.messages})}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let y=()=>u,w=i=>{var f;u=(f=i({...u}))!=null?f:{},kr()},T=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Al],W=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick],E=Sl({parsers:T,handlers:W,getSessionMetadata:y,updateSessionMetadata:w,emit:l.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let H=(Ec=(Tc=r.launcher)==null?void 0:Tc.enabled)!=null?Ec:!0,B=(kc=(Mc=r.launcher)==null?void 0:Mc.autoExpand)!=null?kc:!1,I=(Lc=r.autoFocusInput)!=null?Lc:!1,S=B,P=H,z=(Ic=(Pc=r.layout)==null?void 0:Pc.header)==null?void 0:Ic.layout,U=!1,k=()=>pa(r),_=()=>H||k(),O=k()?!1:H?B:!0,Z=!1,ke=null,pe=()=>{Z=!0,ke&&clearTimeout(ke),ke=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=Fg(r,E,pe),Pe=(Wc=(Rc=r.features)==null?void 0:Rc.showReasoning)!=null?Wc:!0,Ie=(Bc=(Hc=r.features)==null?void 0:Hc.showToolCalls)!=null?Bc:!0,ie=(Nc=(Dc=r.features)==null?void 0:Dc.showEventStreamToggle)!=null?Nc:!1,he=(Oc=(Fc=r.features)==null?void 0:Fc.scrollToBottom)!=null?Oc:{},re=($c=(_c=r.features)==null?void 0:_c.scrollBehavior)!=null?$c:{},de=`${(qc=typeof r.persistState=="object"?(Uc=r.persistState)==null?void 0:Uc.keyPrefix:void 0)!=null?qc:"persona-"}event-stream`,Ae=ie?new fa(de):null,$e=(Vc=(jc=(zc=r.features)==null?void 0:zc.eventStream)==null?void 0:jc.maxEvents)!=null?Vc:2e3,K=ie?new ga($e,Ae):null,J=ie?new ha:null,Se=null,Y=!1,le=null,Te=0;Ae==null||Ae.open().then(()=>K==null?void 0:K.restore()).catch(i=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Ye={onCopy:i=>{var p,f;l.emit("message:copy",i),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(i.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(f=(p=r.messageActions)==null?void 0:p.onCopy)==null||f.call(p,i)},onFeedback:i=>{var p,f;l.emit("message:feedback",i),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(i.messageId,i.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(f=(p=r.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,i)}},tt=(Kc=r.statusIndicator)!=null?Kc:{},Wt=i=>{var p,f,b,C,L,q;return i==="idle"?(p=tt.idleText)!=null?p:tn.idle:i==="connecting"?(f=tt.connectingText)!=null?f:tn.connecting:i==="connected"?(b=tt.connectedText)!=null?b:tn.connected:i==="error"?(C=tt.errorText)!=null?C:tn.error:i==="paused"?(L=tt.pausedText)!=null?L:tn.paused:i==="resuming"?(q=tt.resumingText)!=null?q:tn.resuming:tn[i]};function ht(i,p,f,b){if(b==="idle"&&f.idleLink){i.textContent="";let C=document.createElement("a");C.href=f.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=p,C.style.color="inherit",C.style.textDecoration="none",i.appendChild(C)}else i.textContent=p}let ot=ng({config:r,showClose:_()}),{wrapper:me,panel:X,pillRoot:lt}=ot.shell,Ve=ot.panelElements,{container:Ee,body:xe,messagesWrapper:Ze,suggestions:jt,textarea:be,sendButton:ue,sendButtonWrapper:An,composerForm:At,statusText:yn,introTitle:fr,introSubtitle:hr,closeButton:qe,iconHolder:M,headerTitle:ge,headerSubtitle:Me,header:Le,footer:He,actionsRow:nt,leftActions:Xe,rightActions:yt}=Ve,fe=Ve.setSendButtonMode,D=Ve.micButton,ve=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Ge=Ve.attachmentInput,Pt=Ve.attachmentPreviewsContainer;Ee.classList.add("persona-relative"),xe.classList.add("persona-relative");let kt=12,wt=()=>{var i;return(i=he.label)!=null?i:""},Ht=()=>{var i;return(i=he.iconName)!=null?i:"arrow-down"},Xt=()=>he.enabled!==!1,Ot=()=>{var i;return(i=re.mode)!=null?i:"anchor-top"},Zt=()=>Ot()==="follow"||Ot()==="anchor-top"&&so,yr=()=>{var i;return(i=re.anchorTopOffset)!=null?i:16},Wr=()=>{var i;return(i=re.restorePosition)!=null?i:"bottom"},rr=()=>re.pauseOnInteraction===!0,or=()=>re.showActivityWhilePinned!==!1,Xr=()=>re.announce===!0,Vt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let sr=v("span","persona-flex persona-items-center"),Hr=v("span",""),Bn=v("span","");Bn.setAttribute("data-persona-scroll-to-bottom-count",""),Bn.style.display="none",Vt.append(sr,Hr,Bn),Ee.appendChild(Vt);let In=v("div","persona-stream-anchor-spacer");In.setAttribute("aria-hidden","true"),In.setAttribute("data-persona-anchor-spacer",""),In.style.flexShrink="0",In.style.pointerEvents="none",In.style.height="0px",xe.appendChild(In);let Dn=v("div","persona-sr-only");Dn.setAttribute("aria-live","polite"),Dn.setAttribute("aria-atomic","true"),Dn.setAttribute("role","status"),Dn.setAttribute("data-persona-live-region",""),Object.assign(Dn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Ee.appendChild(Dn);let ar=null,br=null,Jr=i=>{!Xr()||!i||(br=i,ar===null&&(ar=setTimeout(()=>{ar=null,br&&Xr()&&(Dn.textContent=br),br=null},400)))},Vn=()=>{let p=He.style.display==="none"?0:He.offsetHeight;Vt.style.bottom=`${p+kt}px`};Vn();let Yr=()=>{let i=!!wt();Vt.setAttribute("aria-label",wt()||"Jump to latest"),Vt.title=wt(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),sr.innerHTML="";let p=ye(Ht(),"14px","currentColor",2);p?(sr.appendChild(p),sr.style.display=""):sr.style.display="none",Hr.textContent=wt(),Hr.style.display=i?"":"none"};Yr();let St=null,vr=null,wr=o.find(i=>i.renderHeader);if(wr!=null&&wr.renderHeader){let i=wr.renderHeader({config:r,defaultRenderer:()=>{let p=Vo({config:r,showClose:_()});return ua(Ee,p,r),p.header},onClose:()=>$t(!1,"user")});if(i){let p=Ee.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(i),Le=i,ot.header.element=i)}}let Br=()=>{var p,f,b,C;if(!K)return;if(Y=!0,!Se&&K&&(Se=vg({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var L;return(L=J==null?void 0:J.getMetric())!=null?L:{status:"idle"}}})),Se&&(xe.style.display="none",(p=He.parentNode)==null||p.insertBefore(Se.element,He),Se.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${Pn.actionIconColor}`;let L=(C=(b=(f=r.features)==null?void 0:f.eventStream)==null?void 0:b.classNames)==null?void 0:C.toggleButtonActive;L&&L.split(/\s+/).forEach(q=>q&&bt.classList.add(q))}let i=()=>{if(!Y)return;let L=Date.now();L-Te>=200&&(Se==null||Se.update(),Te=L),le=requestAnimationFrame(i)};Te=0,le=requestAnimationFrame(i),_n(),l.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var i,p,f;if(Y){if(Y=!1,Se&&Se.element.remove(),xe.style.display="",bt){bt.style.boxShadow="";let b=(f=(p=(i=r.features)==null?void 0:i.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;b&&b.split(/\s+/).forEach(C=>C&&bt.classList.remove(C))}le!==null&&(cancelAnimationFrame(le),le=null),_n(),l.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(ie){let i=(Qc=(Gc=r.features)==null?void 0:Gc.eventStream)==null?void 0:Qc.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"+(i!=null&&i.toggleButton?" "+i.toggleButton:"");bt=v("button",p),bt.style.width="28px",bt.style.height="28px",bt.style.color=Pn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let f=ye("activity","18px","currentColor",1.5);f&&bt.appendChild(f);let b=Ve.clearChatButtonWrapper,C=Ve.closeButtonWrapper,L=b||C;L&&L.parentNode===Le?Le.insertBefore(bt,L):Le.appendChild(bt),bt.addEventListener("click",()=>{Y?ir():Br()})}let So=i=>{var C,L,q,F,N;let p=r.attachments;if(!(p!=null&&p.enabled))return;let f=(C=i.querySelector("[data-persona-composer-attachment-previews]"))!=null?C:i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let ae=i.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(f,ae):i.insertBefore(f,i.firstChild)}if(!((L=i.querySelector("[data-persona-composer-attachment-input]"))!=null?L:i.querySelector('input[type="file"]'))){let ae=v("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((q=p.allowedTypes)!=null?q:Gr).join(","),ae.multiple=((F=p.maxFiles)!=null?F:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(N=p.buttonTooltipText)!=null?N:"Attach files"),i.appendChild(ae)}},xr=o.find(i=>i.renderComposer);if(xr!=null&&xr.renderComposer){let i=r.composer,p=xr.renderComposer({config:r,defaultRenderer:()=>mi({config:r}).footer,onSubmit:f=>{var q;if(!$||$.isStreaming())return;let b=f.trim(),C=(q=St==null?void 0:St.hasAttachments())!=null?q:!1;if(!b&&!C)return;Ql();let L;C&&(L=[],L.push(...St.getContentParts()),b&&L.push(Qi(b))),$.sendMessage(b,{contentParts:L}),C&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ge==null||Ge.click()},models:i==null?void 0:i.models,selectedModelId:i==null?void 0:i.selectedModelId,onModelChange:f=>{r.composer={...r.composer,selectedModelId:f},r.agent&&(r.agent={...r.agent,model:f})},onVoiceToggle:((Xc=r.voiceRecognition)==null?void 0:Xc.enabled)===!0?()=>{vr==null||vr()}:void 0});p&&(ot.replaceComposer(p),He=ot.composer.footer)}let To=i=>{let p=(...se)=>{for(let te of se){let we=i.querySelector(te);if(we)return we}return null},f=i.querySelector("[data-persona-composer-form]"),b=i.querySelector("[data-persona-composer-input]"),C=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),q=i.querySelector("[data-persona-composer-status]");f&&(At=f),b&&(be=b),C&&(ue=C),L&&(D=L,ve=L.parentElement),q&&(yn=q);let F=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(jt=F);let N=p("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(ce=N,ft=N.parentElement),Ge=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Pt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(nt=ae)};So(He),To(He);let Rn=(td=(Jc=r.layout)==null?void 0:Jc.contentMaxWidth)!=null?td:k()?(ed=(Zc=(Yc=r.launcher)==null?void 0:Yc.composerBar)==null?void 0:Zc.contentMaxWidth)!=null?ed:"720px":void 0;if(Rn&&(Ze.style.maxWidth=Rn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Rn&&At&&!k()&&(At.style.maxWidth=Rn,At.style.marginLeft="auto",At.style.marginRight="auto"),Rn&&jt&&!k()&&(jt.style.maxWidth=Rn,jt.style.marginLeft="auto",jt.style.marginRight="auto"),Rn&&Pt&&!k()&&(Pt.style.maxWidth=Rn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),(nd=r.attachments)!=null&&nd.enabled&&Ge&&Pt){St=oa.fromConfig(r.attachments),St.setPreviewsContainer(Pt),Ge.addEventListener("change",f=>{let b=f.target;St==null||St.handleFileSelect(b.files),b.value=""});let i=r.attachments.dropOverlay,p=Og(i);Ee.appendChild(p)}(()=>{var b,C;let i=(C=(b=r.layout)==null?void 0:b.slots)!=null?C:{},p=L=>{switch(L){case"body-top":return Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return jt;case"composer":return At;case"footer-bottom":return yn;default:return null}},f=(L,q)=>{var F;switch(L){case"header-left":case"header-center":case"header-right":if(L==="header-left")Le.insertBefore(q,Le.firstChild);else if(L==="header-right")Le.appendChild(q);else{let N=Le.querySelector(".persona-flex-col");N?(F=N.parentNode)==null||F.insertBefore(q,N.nextSibling):Le.appendChild(q)}break;case"body-top":{let N=xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(q):xe.insertBefore(q,xe.firstChild);break}case"body-bottom":xe.appendChild(q);break;case"footer-top":jt.replaceWith(q);break;case"footer-bottom":yn.replaceWith(q);break;default:break}};for(let[L,q]of Object.entries(i))if(q)try{let F=q({config:r,defaultContent:()=>p(L)});F&&f(L,F)}catch(F){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${L}":`,F)}})();let Zr=i=>{var q,F;let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let b=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let C=b.getAttribute("data-message-id");if(!C)return;let L=f.getAttribute("data-bubble-type");if(L==="reasoning")Es.has(C)?Es.delete(C):Es.add(C),sg(C,b);else if(L==="tool")Ms.has(C)?Ms.delete(C):Ms.add(C),ag(C,b,r);else if(L==="approval"){let N=r.approval!==!1?r.approval:void 0,ae=((q=N==null?void 0:N.detailsDisplay)!=null?q:"collapsed")==="expanded",se=(F=Ko.get(C))!=null?F:ae;Ko.set(C,!se),dg(C,b,r)}Tr.delete(C)};Ze.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Zr(i))}),Ze.addEventListener("keydown",i=>{let p=i.target;(i.key==="Enter"||i.key===" ")&&p.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Zr(i))}),Ze.addEventListener("copy",i=>{let{clipboardData:p}=i;if(!p)return;let f=Ze.getRootNode(),b=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let C=b.toString(),L=Nm(C);!L||L===C||(p.setData("text/plain",L),i.preventDefault())});let Dr=new Map,eo=null,to="idle",Eo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Mo=(i,p)=>{let{icon:f,label:b}=Eo[p];i.setAttribute("aria-label",b),i.title=b,i.setAttribute("aria-pressed",p==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",p!=="idle"),i.classList.toggle("persona-message-action-loading",p==="loading");let C=ye(f,14,"currentColor",2);C&&(i.innerHTML="",i.appendChild(C))},no=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var L;let f=p.closest("[data-actions-for]"),b=(L=f==null?void 0:f.getAttribute("data-actions-for"))!=null?L:null;Mo(p,b&&b===eo?to:"idle")})};Ze.addEventListener("click",i=>{var q;let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let b=f.closest("[data-actions-for]");if(!b)return;let C=b.getAttribute("data-actions-for");if(!C)return;let L=f.getAttribute("data-action");if(L==="copy"){let N=$.getMessages().find(ae=>ae.id===C);if(N&&Ye.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).then(()=>{f.classList.add("persona-message-action-success");let se=ye("check",14,"currentColor",2);se&&(f.innerHTML="",f.appendChild(se)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let te=ye("copy",14,"currentColor",2);te&&(f.innerHTML="",f.appendChild(te))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),Ye.onCopy(N)}}else if(L==="read-aloud")$.toggleReadAloud(C);else if(L==="upvote"||L==="downvote"){let N=((q=Dr.get(C))!=null?q:null)===L,ae=L==="upvote"?"thumbs-up":"thumbs-down";if(N){Dr.delete(C),f.classList.remove("persona-message-action-active");let se=ye(ae,14,"currentColor",2);se&&(f.innerHTML="",f.appendChild(se))}else{let se=L==="upvote"?"downvote":"upvote",te=b.querySelector(`[data-action="${se}"]`);if(te){te.classList.remove("persona-message-action-active");let ze=ye(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(te.innerHTML="",te.appendChild(ze))}Dr.set(C,L),f.classList.add("persona-message-action-active");let we=ye(ae,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(we)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Oe=$.getMessages().find(Ue=>Ue.id===C);Oe&&Ye.onFeedback&&Ye.onFeedback({type:L,messageId:Oe.id,message:Oe})}}}),Ze.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let b=f.closest(".persona-approval-bubble");if(!b)return;let C=b.getAttribute("data-message-id");if(!C)return;let L=f.getAttribute("data-approval-action");if(!L)return;let q=L==="approve"?"approved":"denied",N=$.getMessages().find(se=>se.id===C);if(!(N!=null&&N.approval))return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?$.resolveWebMcpApproval(C,q):$.resolveApproval(N.approval,q)});let xt=null,Nn=null,Fn={artifacts:[],selectedId:null},Sn=!1,Tt={current:null};Ze.addEventListener("click",i=>{var te,we,Fe,Oe,Ue;let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let b=f.getAttribute("data-download-artifact");if(!b||((Fe=(we=(te=r.features)==null?void 0:te.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let L=$.getArtifactById(b),q=L==null?void 0:L.markdown,F=(L==null?void 0:L.title)||"artifact";if(!q){let ze=f.closest("[data-open-artifact]"),mt=ze==null?void 0:ze.closest("[data-message-id]"),at=mt==null?void 0:mt.getAttribute("data-message-id");if(at){let Re=$.getMessages().find(je=>je.id===at);if(Re!=null&&Re.rawContent)try{let je=JSON.parse(Re.rawContent);q=(Oe=je==null?void 0:je.props)==null?void 0:Oe.markdown,F=((Ue=je==null?void 0:je.props)==null?void 0:Ue.title)||F}catch{}}}if(!q)return;let N=new Blob([q],{type:"text/markdown"}),ae=URL.createObjectURL(N),se=document.createElement("a");se.href=ae,se.download=`${F}.md`,se.click(),URL.revokeObjectURL(ae)}),Ze.addEventListener("click",i=>{var L,q,F;let f=i.target.closest("[data-open-artifact]");if(!f)return;let b=f.getAttribute("data-open-artifact");!b||((F=(q=(L=r.features)==null?void 0:L.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:F.call(q,{type:"open",artifactId:b}))===!0||(i.preventDefault(),i.stopPropagation(),Sn=!1,$.selectArtifact(b),Cr())}),Ze.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let p=i.target;p.hasAttribute("data-open-artifact")&&(i.preventDefault(),p.click())});let Kn=Ve.composerOverlay,Gn=(i,p,f)=>{var F,N,ae,se;let b=p.trim();if(!b||!Tt.current)return;let C=(F=i.getAttribute("data-tool-call-id"))!=null?F:"",L=f.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:b,answers:f.structured,values:(N=f.values)!=null?N:f.source==="multi"?b.split(", "):[b],isFreeText:L,source:f.source},bubbles:!0,composed:!0})),hs(Kn,C);let q=Tt.current.getMessages().find(te=>{var we;return((we=te.toolCall)==null?void 0:we.id)===C});(ae=q==null?void 0:q.agentMetadata)!=null&&ae.awaitingLocalTool?Tt.current.resolveAskUserQuestion(q,(se=f.structured)!=null?se:b):Tt.current.sendMessage(b)},On=i=>{var C;let p=Tt.current;if(!p)return;let f=(C=i.getAttribute("data-tool-call-id"))!=null?C:"",b=p.getMessages().find(L=>{var q;return((q=L.toolCall)==null?void 0:q.id)===f});b&&p.persistAskUserQuestionProgress(b,{answers:Ra(i,b),currentIndex:tr(i)})},ro=i=>Object.entries(i).map(([p,f])=>`${p}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),Ce=i=>{var C,L,q;if(((L=(C=r.features)==null?void 0:C.askUserQuestion)==null?void 0:L.groupedAutoAdvance)===!1)return;let p=tr(i),f=fs(i);if(p>=f-1)return;let b=(q=Tt.current)==null?void 0:q.getMessages().find(F=>{var N;return((N=F.toolCall)==null?void 0:N.id)===i.getAttribute("data-tool-call-id")});b&&(Ha(i,b,r,p+1),On(i))};Kn.addEventListener("click",i=>{var L,q,F,N,ae,se,te,we,Fe,Oe,Ue,ze,mt,at;let f=i.target.closest("[data-ask-user-action]");if(!f)return;let b=f.closest("[data-persona-ask-sheet-for]");if(!b)return;let C=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),C==="dismiss"){let Be=(L=b.getAttribute("data-tool-call-id"))!=null?L:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),hs(Kn,Be);let Re=(q=Tt.current)==null?void 0:q.getMessages().find(je=>{var Qe;return((Qe=je.toolCall)==null?void 0:Qe.id)===Be});(F=Re==null?void 0:Re.agentMetadata)!=null&&F.awaitingLocalTool&&((N=Tt.current)==null||N.markAskUserQuestionResolved(Re),(ae=Tt.current)==null||ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(C==="pick"){let Be=f.getAttribute("data-option-label");if(!Be)return;let Re=b.getAttribute("data-multi-select")==="true",je=bo(b);if(je&&Re){let Qe=qo(b)[tr(b)],vt=new Set(Array.isArray(Qe)?Qe:[]);vt.has(Be)?vt.delete(Be):vt.add(Be),vo(b,Array.from(vt)),On(b);return}if(je){vo(b,Be),On(b),Ce(b);return}if(Re){let Qe=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Qe?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Qe);let vt=b.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=zi(b).length===0);return}Gn(b,Be,{source:"pick",values:[Be]});return}if(C==="submit-multi"){let Be=zi(b);if(Be.length===0)return;Gn(b,Be.join(", "),{source:"multi",values:Be});return}if(C==="open-free-text"){let Be=b.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Re=Be.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(C==="focus-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(C==="submit-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]'),Re=(se=Be==null?void 0:Be.value)!=null?se:"";if(!Re.trim())return;if(bo(b)){vo(b,Re.trim()),On(b),Ce(b);return}Gn(b,Re,{source:"free-text"});return}if(C==="next"||C==="back"){if(!Tt.current)return;let Be=(te=b.getAttribute("data-tool-call-id"))!=null?te:"",Re=Tt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(Fe=(we=je==null?void 0:je.value)==null?void 0:we.trim())!=null?Fe:"";if(Qe){let De=qo(b)[tr(b)];(typeof De!="string"||De!==Qe)&&vo(b,Qe)}let vt=C==="next"?1:-1,R=tr(b)+vt;Ha(b,Re,r,R),On(b);return}if(C==="submit-all"){if(!Tt.current)return;let Be=(Oe=b.getAttribute("data-tool-call-id"))!=null?Oe:"",Re=Tt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(Ue=je==null?void 0:je.value)==null?void 0:Ue.trim())!=null?ze:"";Qe&&vo(b,Qe);let vt=Ra(b,Re);Tt.current.persistAskUserQuestionProgress(Re,{answers:vt,currentIndex:tr(b)});let R=ro(vt);Gn(b,R||"(submitted)",{source:"submit-all",structured:vt});return}if(C==="skip"){if(!Tt.current)return;let Be=(mt=b.getAttribute("data-tool-call-id"))!=null?mt:"",Re=Tt.current.getMessages().find(We=>{var Je;return((Je=We.toolCall)==null?void 0:Je.id)===Be});if(!Re)return;let je=bo(b),Qe=tr(b),vt=fs(b),R=Qe>=vt-1;if(!je){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),hs(Kn,Be),(at=Re.agentMetadata)!=null&&at.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(Re),Tt.current.resolveAskUserQuestion(Re,"(dismissed)"));return}vo(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),R){let We=Ra(b,Re),Je=ro(We);Gn(b,Je||"(skipped)",{source:"submit-all",structured:We});return}Ha(b,Re,r,Qe+1),On(b);return}}),Kn.addEventListener("keydown",i=>{var L;if(i.key!=="Enter")return;let f=i.target;if(!((L=f.matches)!=null&&L.call(f,'[data-ask-free-text-input="true"]')))return;let b=f.closest("[data-persona-ask-sheet-for]");if(!b)return;i.preventDefault();let C=f.value;if(C.trim()){if(bo(b)){vo(b,C.trim()),On(b),Ce(b);return}Gn(b,C,{source:"free-text"})}});let Nr=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let p=i.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let f=Kn.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let b=Number(i.key),L=f.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];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",Nr);let Qn=null,_t=null,Xn=null,Fr=null,Is=()=>{};function Yo(){Fr==null||Fr(),Fr=null}let Rs=()=>{var q;if(!Qn||!_t)return;let i=n.classList.contains("persona-artifact-appearance-seamless"),f=((q=n.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!i||n.classList.contains("persona-artifact-narrow-host")||f){_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 C=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${C}px`,_t.style.zIndex="5";let L=b.offsetWidth-C/2;_t.style.left=`${Math.max(0,L)}px`},ko=()=>{},Cr=()=>{var f,b,C,L,q;if(!xt||!nr(r))return;yi(n,r),bi(n,r),ko();let i=(L=(C=(b=(f=r.features)==null?void 0:f.artifacts)==null?void 0:b.layout)==null?void 0:C.narrowHostMaxWidth)!=null?L:520,p=X.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",p>0&&p<=i),xt.update(Fn),Sn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(q=xt.backdrop)==null||q.classList.add("persona-hidden")):Fn.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),Is()};if(nr(r)){X.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Ee),xt=Cg(r,{onSelect:f=>{var b;return(b=Tt.current)==null?void 0:b.selectArtifact(f)},onDismiss:()=>{Sn=!0,Cr()}}),xt.element.classList.add("persona-hidden"),Qn=p,p.appendChild(i),p.appendChild(xt.element),xt.backdrop&&X.appendChild(xt.backdrop),X.appendChild(p),Is=()=>{var b,C,L,q;if(!Qn||!xt)return;if(!(((L=(C=(b=r.features)==null?void 0:b.artifacts)==null?void 0:C.layout)==null?void 0:L.resizable)===!0)){Xn==null||Xn(),Xn=null,Yo(),_t&&(_t.remove(),_t=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!_t){let F=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");F.setAttribute("role","separator"),F.setAttribute("aria-orientation","vertical"),F.setAttribute("aria-label","Resize artifacts panel"),F.tabIndex=0;let N=n.ownerDocument,ae=(q=N.defaultView)!=null?q:window,se=te=>{var mt,at;if(!xt||te.button!==0||n.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;te.preventDefault(),Yo();let we=te.clientX,Fe=xt.element.getBoundingClientRect().width,Oe=(at=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:at.layout,Ue=Be=>{let Re=Qn.getBoundingClientRect().width,je=n.classList.contains("persona-artifact-appearance-seamless"),Qe=je?0:Eg(Qn,ae),vt=je?0:F.getBoundingClientRect().width||6,R=Fe-(Be.clientX-we),De=Mg(R,Re,Qe,vt,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);xt.element.style.width=`${De}px`,xt.element.style.maxWidth="none",Rs()},ze=()=>{N.removeEventListener("pointermove",Ue),N.removeEventListener("pointerup",ze),N.removeEventListener("pointercancel",ze),Fr=null;try{F.releasePointerCapture(te.pointerId)}catch{}};Fr=ze,N.addEventListener("pointermove",Ue),N.addEventListener("pointerup",ze),N.addEventListener("pointercancel",ze);try{F.setPointerCapture(te.pointerId)}catch{}};F.addEventListener("pointerdown",se),_t=F,Qn.insertBefore(F,xt.element),Xn=()=>{F.removeEventListener("pointerdown",se)}}if(_t){let F=Fn.artifacts.length>0&&!Sn;_t.classList.toggle("persona-hidden",!F),Rs()}},ko=()=>{var ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re,je,Qe;if(!H||!xt||((se=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||hn(r)&&mr(r).reveal==="emerge")return;let b=(te=n.ownerDocument.defaultView)!=null?te:window,C=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,L=(Ue=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?Ue:640;if(C&&b.innerWidth<=L||!Tg(r,H))return;let q=(at=(mt=(ze=r.launcher)==null?void 0:ze.width)!=null?mt:r.launcherWidth)!=null?at:Qr,F=(Qe=(je=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:je.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!Sn?(X.style.width=F,X.style.maxWidth=F):(X.style.width=q,X.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{Cr()}),Nn.observe(X))}else X.appendChild(Ee),k()&&lt&&(Ve.peekBanner&&lt.appendChild(Ve.peekBanner),lt.appendChild(He));n.appendChild(me),lt&&n.appendChild(lt);let oo=()=>{var De,We,Je,It,_e,Gt,Ct,an,Wn,Dt,gn,$n,Ke,Rt,Un,Wo,Ho,Bo,Do,ls,cs,Qt,No,mo,go,jr,Fo,et;if(k()){X.style.width="100%",X.style.maxWidth="100%";let Ft=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Nt=me.dataset.state==="expanded",Kt=(Je=Ft.expandedSize)!=null?Je:"anchored";if(!(Nt&&Kt!=="fullscreen")){Ee.style.background="",Ee.style.border="",Ee.style.borderRadius="",Ee.style.overflow="",Ee.style.boxShadow="";return}let gt=(_e=(It=r.theme)==null?void 0:It.components)==null?void 0:_e.panel,qt=Ga(r),fn=(un,er)=>{var fo;return un==null||un===""?er:(fo=Cs(qt,un))!=null?fo:un},qn="1px solid var(--persona-border)",Pr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",pn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ee.style.background="var(--persona-surface, #ffffff)",Ee.style.border=fn(gt==null?void 0:gt.border,qn),Ee.style.borderRadius=fn(gt==null?void 0:gt.borderRadius,pn),Ee.style.boxShadow=fn(gt==null?void 0:gt.shadow,Pr),Ee.style.overflow="hidden";return}let i=hn(r),p=(Ct=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?Ct:!1,f=i||p||((Wn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Wn:!1),b=((Dt=r.launcher)==null?void 0:Dt.enabled)===!1,C=($n=(gn=r.theme)==null?void 0:gn.components)==null?void 0:$n.panel,L=Ga(r),q=(Ft,Nt)=>{var Kt;return Ft==null||Ft===""?Nt:(Kt=Cs(L,Ft))!=null?Kt:Ft},F=(Ke=n.ownerDocument.defaultView)!=null?Ke:window,N=(Un=(Rt=r.launcher)==null?void 0:Rt.mobileFullscreen)!=null?Un:!0,ae=(Ho=(Wo=r.launcher)==null?void 0:Wo.mobileBreakpoint)!=null?Ho:640,se=F.innerWidth<=ae,te=N&&se&&H,we=(Do=(Bo=r.launcher)==null?void 0:Bo.position)!=null?Do:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Oe=(cs=(ls=r.launcher)==null?void 0:ls.zIndex)!=null?cs:xn,Ue=p||te?"none":"1px solid var(--persona-border)",ze=te?"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))";i&&!te&&(ze="none",Ue="none");let mt=p||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=q(C==null?void 0:C.border,Ue),Be=q(C==null?void 0:C.shadow,ze),Re=q(C==null?void 0:C.borderRadius,mt),je=xe.scrollTop;n.style.cssText="",me.style.cssText="",X.style.cssText="",Ee.style.cssText="",xe.style.cssText="",He.style.cssText="",Y&&(xe.style.display="none");let Qe=()=>{var Nt;if(je<=0)return;((Nt=xe.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(xe.scrollTop===je)return;let Kt=xe.scrollHeight-xe.clientHeight;Kt<=0||(xe.scrollTop=Math.min(je,Kt))})};if(te){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=`
40
+ `,z.addEventListener("click",()=>{u=j,W.forEach((C,V)=>{let Y=V<j;C.classList.toggle("selected",Y),C.setAttribute("aria-checked",V===j-1?"true":"false")})}),W.push(z),P.appendChild(z)}w.appendChild(P);let M=null;if(p){let j=document.createElement("div");j.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),j.appendChild(M),w.appendChild(j)}let R=document.createElement("div");R.className="persona-feedback-actions";let D=document.createElement("button");D.type="button",D.className="persona-feedback-btn persona-feedback-btn-skip",D.textContent=l,D.addEventListener("click",()=>{n?.(),c.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=a,$.addEventListener("click",async()=>{if(u===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let j=M?.value.trim()||void 0;await e(u,j),c.remove()}catch(j){$.disabled=!1,$.textContent=a,console.error("[CSAT Feedback] Failed to submit:",j)}}),R.appendChild(D),R.appendChild($),w.appendChild(R),c.appendChild(w),c}function Tu(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let w=null,f=document.createElement("div");f.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,b.appendChild(x);let P=document.createElement("p");P.className="persona-feedback-subtitle",P.textContent=r,b.appendChild(P),f.appendChild(b);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=d;let D=document.createElement("span");D.className="persona-feedback-label-high",D.textContent=c,M.appendChild(R),M.appendChild(D);let $=document.createElement("div");$.className="persona-feedback-numbers";let j=[];for(let F=0;F<=10;F++){let U=document.createElement("button");U.type="button",U.className="persona-feedback-rating-btn persona-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${F} out of 10`),U.textContent=String(F),U.dataset.rating=String(F),F<=6?U.classList.add("persona-feedback-detractor"):F<=8?U.classList.add("persona-feedback-passive"):U.classList.add("persona-feedback-promoter"),U.addEventListener("click",()=>{w=F,j.forEach((de,ye)=>{de.classList.toggle("selected",ye===F),de.setAttribute("aria-checked",ye===F?"true":"false")})}),j.push(U),$.appendChild(U)}W.appendChild(M),W.appendChild($),f.appendChild(W);let z=null;if(p){let F=document.createElement("div");F.className="persona-feedback-comment-container",z=document.createElement("textarea"),z.className="persona-feedback-comment",z.placeholder=s,z.rows=3,z.setAttribute("aria-label","Additional comments"),F.appendChild(z),f.appendChild(F)}let C=document.createElement("div");C.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),u.remove()});let Y=document.createElement("button");return Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-submit",Y.textContent=a,Y.addEventListener("click",async()=>{if(w===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}Y.disabled=!0,Y.textContent="Submitting...";try{let F=z?.value.trim()||void 0;await e(w,F),u.remove()}catch(F){Y.disabled=!1,Y.textContent=a,console.error("[NPS Feedback] Failed to submit:",F)}}),C.appendChild(V),C.appendChild(Y),f.appendChild(C),u.appendChild(f),u}var vr="persona-chat-history",uy=30*1e3,fy=641,gy={"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 my(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=gy[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function ei(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function hy(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function yy(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Rl=t=>!t||typeof t!="object"?{}:{...t},Mu=t=>t.map(e=>({...e,streaming:!1})),Eu=(t,e,n)=>{let o=t?.markdown?ta(t.markdown):null,r=na(t?.sanitize);return t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(e){let c=e.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Bn()!==null,d;if(t?.postprocessMessage){let c=t.postprocessMessage({...s,text:a,raw:l??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?ad(a):a,u=o(c);d=r&&p?r(u):u}else d=Yn(a);return d}};function ku(t){let e=m("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=ie(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=m("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var Lu=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=op(e),r=Ml.getForInstance(o.plugins),{plugin:s,teardown:a}=su();o.components&&On.registerAll(o.components);let l=bu(),d=o.persistState===!1?null:o.storageAdapter??wu(),c={},u=null,w=!1,f=i=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(i);if(g&&typeof g=="object"&&"state"in g){let{state:h,open:v}=g;return v&&(w=!0),h}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")u=i.then(g=>f(g??{messages:[],metadata:{}}));else{let h=f(i??{messages:[],metadata:{}});h.metadata&&(c=Rl(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=f({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let b=()=>c,x=i=>{c=i({...c})??{},bi()},P=o.actionParsers&&o.actionParsers.length?o.actionParsers:[kl],W=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[As.message,As.messageAndClick],M=Ll({parsers:P,handlers:W,getSessionMetadata:b,updateSessionMetadata:x,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let R=o.launcher?.enabled??!0,D=o.launcher?.autoExpand??!1,$=o.autoFocusInput??!1,j=D,z=R,C=o.layout?.header?.layout,V=!1,Y=()=>ms(o),F=()=>R||Y(),U=Y()?!1:R?D:!0,de=!1,ye=null,Ee=()=>{de=!0,ye&&clearTimeout(ye),ye=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},Ae=Eu(o,M,Ee),ne=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,Z=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},ee=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ge=Z?new vs(we):null,Me=o.features?.eventStream?.maxEvents??2e3,Se=Z?new bs(Me,ge):null,je=Z?new ws:null,Ne=null,Ie=!1,Be=null,it=0;ge?.open().then(()=>Se?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let _e={onCopy:i=>{l.emit("message:copy",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{l.emit("message:feedback",i),O?.isClientTokenMode()&&O.submitMessageFeedback(i.messageId,i.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(i)}},Qe=o.statusIndicator??{},an=i=>i==="idle"?Qe.idleText??Wt.idle:i==="connecting"?Qe.connectingText??Wt.connecting:i==="connected"?Qe.connectedText??Wt.connected:i==="error"?Qe.errorText??Wt.error:i==="paused"?Qe.pausedText??Wt.paused:i==="resuming"?Qe.resumingText??Wt.resuming:Wt[i];function kt(i,g,h,v){if(v==="idle"&&h.idleLink){i.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",i.appendChild(T)}else i.textContent=g}let gt=Kp({config:o,showClose:F()}),{wrapper:ke,panel:he,pillRoot:lt}=gt.shell,Re=gt.panelElements,{container:fe,body:le,messagesWrapper:be,suggestions:vt,textarea:N,sendButton:oe,sendButtonWrapper:Fe,composerForm:Le,statusText:E,introTitle:Q,introSubtitle:y,closeButton:S,iconHolder:k,headerTitle:B,headerSubtitle:G,header:H,footer:q,actionsRow:se,leftActions:tt,rightActions:We}=Re,ct=Re.setSendButtonMode,K=Re.micButton,Ue=Re.micButtonWrapper,Ce=Re.attachmentButton,He=Re.attachmentButtonWrapper,Pe=Re.attachmentInput,Je=Re.attachmentPreviewsContainer;fe.classList.add("persona-relative"),le.classList.add("persona-relative");let co=12,po=()=>ce.label??"",ni=()=>ce.iconName??"arrow-down",Ts=()=>ce.enabled!==!1,Jt=()=>ee.mode??"anchor-top",_n=()=>Jt()==="follow"||Jt()==="anchor-top"&&Lr,Ol=()=>ee.anchorTopOffset??16,Uu=()=>ee.restorePosition??"bottom",_l=()=>ee.pauseOnInteraction===!0,$l=()=>ee.showActivityWhilePinned!==!1,Ul=()=>ee.announce===!0,It=m("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let xr=m("span","persona-flex persona-items-center"),oi=m("span",""),uo=m("span","");uo.setAttribute("data-persona-scroll-to-bottom-count",""),uo.style.display="none",It.append(xr,oi,uo),fe.appendChild(It);let $n=m("div","persona-stream-anchor-spacer");$n.setAttribute("aria-hidden","true"),$n.setAttribute("data-persona-anchor-spacer",""),$n.style.flexShrink="0",$n.style.pointerEvents="none",$n.style.height="0px",le.appendChild($n);let fo=m("div","persona-sr-only");fo.setAttribute("aria-live","polite"),fo.setAttribute("aria-atomic","true"),fo.setAttribute("role","status"),fo.setAttribute("data-persona-live-region",""),Object.assign(fo.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),fe.appendChild(fo);let Cr=null,Ms=null,zl=i=>{!Ul()||!i||(Ms=i,Cr===null&&(Cr=setTimeout(()=>{Cr=null,Ms&&Ul()&&(fo.textContent=Ms),Ms=null},400)))},$o=()=>{let g=q.style.display==="none"?0:q.offsetHeight;It.style.bottom=`${g+co}px`};$o();let jl=()=>{let i=!!po();It.setAttribute("aria-label",po()||"Jump to latest"),It.title=po(),It.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),xr.innerHTML="";let g=ie(ni(),"14px","currentColor",2);g?(xr.appendChild(g),xr.style.display=""):xr.style.display="none",oi.textContent=po(),oi.style.display=i?"":"none"};jl();let Mt=null,ql=null,Vl=r.find(i=>i.renderHeader);if(Vl?.renderHeader){let i=Vl.renderHeader({config:o,defaultRenderer:()=>{let g=Fo({config:o,showClose:F()});return hs(fe,g,o),g.header},onClose:()=>ht(!1,"user")});if(i){let g=fe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(i),H=i,gt.header.element=i)}}let ri=()=>{if(!Se)return;if(Ie=!0,!Ne&&Se&&(Ne=du({buffer:Se,getFullHistory:()=>Se.getAllFromStore(),onClose:()=>Ar(),config:o,plugins:r,getThroughput:()=>je?.getMetric()??{status:"idle"}})),Ne&&(le.style.display="none",q.parentNode?.insertBefore(Ne.element,q),Ne.update()),st){st.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(h=>h&&st.classList.add(h))}let i=()=>{if(!Ie)return;let g=Date.now();g-it>=200&&(Ne?.update(),it=g),Be=requestAnimationFrame(i)};it=0,Be=requestAnimationFrame(i),tn(),l.emit("eventStream:opened",{timestamp:Date.now()})},Ar=()=>{if(Ie){if(Ie=!1,Ne&&Ne.element.remove(),le.style.display="",st){st.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(g=>g&&st.classList.remove(g))}Be!==null&&(cancelAnimationFrame(Be),Be=null),tn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},st=null;if(Z){let i=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");st=m("button",g),st.style.width="28px",st.style.height="28px",st.style.color=Xt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let h=ie("activity","18px","currentColor",1.5);h&&st.appendChild(h);let v=Re.clearChatButtonWrapper,T=Re.closeButtonWrapper,L=v||T;L&&L.parentNode===H?H.insertBefore(st,L):H.appendChild(st),st.addEventListener("click",()=>{Ie?Ar():ri()})}let zu=i=>{let g=o.attachments;if(!g?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let T=i.querySelector("[data-persona-composer-form]");T?.parentNode?T.parentNode.insertBefore(h,T):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let T=m("input");T.type="file",T.setAttribute("data-persona-composer-attachment-input",""),T.accept=(g.allowedTypes??Fn).join(","),T.multiple=(g.maxFiles??4)>1,T.style.display="none",T.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),i.appendChild(T)}},Kl=r.find(i=>i.renderComposer);if(Kl?.renderComposer){let i=o.composer,g=Kl.renderComposer({config:o,defaultRenderer:()=>Qa({config:o}).footer,onSubmit:h=>{if(!O||O.isStreaming())return;let v=h.trim(),T=Mt?.hasAttachments()??!1;if(!v&&!T)return;Cc();let L;T&&(L=[],L.push(...Mt.getContentParts()),v&&L.push(Ki(v))),O.sendMessage(v,{contentParts:L}),T&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{ql?.()}:void 0});g&&(gt.replaceComposer(g),q=gt.composer.footer)}let ju=i=>{let g=(...pe)=>{for(let re of pe){let xe=i.querySelector(re);if(xe)return xe}return null},h=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),T=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");h&&(Le=h),v&&(N=v),T&&(oe=T),L&&(K=L,Ue=L.parentElement),J&&(E=J);let _=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(vt=_);let X=g("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(Ce=X,He=X.parentElement),Pe=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Je=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(se=ae)};zu(q),ju(q);let Un=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Un&&(be.style.maxWidth=Un,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%"),Un&&Le&&!Y()&&(Le.style.maxWidth=Un,Le.style.marginLeft="auto",Le.style.marginRight="auto"),Un&&vt&&!Y()&&(vt.style.maxWidth=Un,vt.style.marginLeft="auto",vt.style.marginRight="auto"),Un&&Je&&!Y()&&(Je.style.maxWidth=Un,Je.style.marginLeft="auto",Je.style.marginRight="auto"),o.attachments?.enabled&&Pe&&Je){Mt=os.fromConfig(o.attachments),Mt.setPreviewsContainer(Je),Pe.addEventListener("change",h=>{let v=h.target;Mt?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,g=ku(i);fe.appendChild(g)}(()=>{let i=o.layout?.slots??{},g=v=>{switch(v){case"body-top":return fe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return vt;case"composer":return Le;case"footer-bottom":return E;default:return null}},h=(v,T)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")H.insertBefore(T,H.firstChild);else if(v==="header-right")H.appendChild(T);else{let L=H.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(T,L.nextSibling):H.appendChild(T)}break;case"body-top":{let L=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");L?L.replaceWith(T):le.insertBefore(T,le.firstChild);break}case"body-bottom":le.appendChild(T);break;case"footer-top":vt.replaceWith(T);break;case"footer-bottom":E.replaceWith(T);break;default:break}};for(let[v,T]of Object.entries(i))if(T)try{let L=T({config:o,defaultContent:()=>g(v)});L&&h(v,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,L)}})();let Gl=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let v=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let L=h.getAttribute("data-bubble-type");if(L==="reasoning")hr.has(T)?hr.delete(T):hr.add(T),Qp(T,v);else if(L==="tool")yr.has(T)?yr.delete(T):yr.add(T),Jp(T,v,o);else if(L==="approval"){let _=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=No.get(T)??_;No.set(T,!X),tu(T,v,o)}yo.delete(T)};be.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Gl(i))}),be.addEventListener("keydown",i=>{let g=i.target;(i.key==="Enter"||i.key===" ")&&g.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Gl(i))}),be.addEventListener("copy",i=>{let{clipboardData:g}=i;if(!g)return;let h=be.getRootNode(),v=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let T=v.toString(),L=Lp(T);!L||L===T||(g.setData("text/plain",L),i.preventDefault())});let si=new Map,Xl=null,Ql="idle",qu={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Vu=(i,g)=>{let{icon:h,label:v}=qu[g];i.setAttribute("aria-label",v),i.title=v,i.setAttribute("aria-pressed",g==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",g!=="idle"),i.classList.toggle("persona-message-action-loading",g==="loading");let T=ie(h,14,"currentColor",2);T&&(i.innerHTML="",i.appendChild(T))},Jl=()=>{be.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let v=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Vu(g,v&&v===Xl?Ql:"idle")})};be.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.closest("[data-actions-for]");if(!v)return;let T=v.getAttribute("data-actions-for");if(!T)return;let L=h.getAttribute("data-action");if(L==="copy"){let _=O.getMessages().find(X=>X.id===T);if(_&&_e.onCopy){let X=_.content||"";navigator.clipboard.writeText(X).then(()=>{h.classList.add("persona-message-action-success");let ae=ie("check",14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let pe=ie("copy",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),_e.onCopy(_)}}else if(L==="read-aloud")O.toggleReadAloud(T);else if(L==="upvote"||L==="downvote"){let _=(si.get(T)??null)===L,X=L==="upvote"?"thumbs-up":"thumbs-down";if(_){si.delete(T),h.classList.remove("persona-message-action-active");let ae=ie(X,14,"currentColor",2);ae&&(h.innerHTML="",h.appendChild(ae))}else{let ae=L==="upvote"?"downvote":"upvote",pe=v.querySelector(`[data-action="${ae}"]`);if(pe){pe.classList.remove("persona-message-action-active");let at=ie(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);at&&(pe.innerHTML="",pe.appendChild(at))}si.set(T,L),h.classList.add("persona-message-action-active");let re=ie(X,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(re)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ke=O.getMessages().find(yt=>yt.id===T);Ke&&_e.onFeedback&&_e.onFeedback({type:L,messageId:Ke.id,message:Ke})}}}),be.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.closest(".persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let L=h.getAttribute("data-approval-action");if(!L)return;let J=L==="approve"?"approved":"denied",X=O.getMessages().find(pe=>pe.id===T);if(!X?.approval)return;let ae=v.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?O.resolveWebMcpApproval(T,J):O.resolveApproval(X.approval,J)});let Ye=null,Sr=null,Tr=()=>{},Mr="none",Es=null,gn={artifacts:[],selectedId:null},kn=!1,mn=!1,Er=!1,Uo=!1,Yl=()=>Uo||gn.artifacts.some(i=>Lo(o.features?.artifacts,i.artifactType)==="panel"),ks=()=>gn.artifacts.length>0&&!kn&&Yl(),mt={current:null},ai=(i,g)=>{let h=O.getArtifactById(g),v=h?.markdown,T=h?.title||"artifact",L=h?.file,J=h?.artifactType??"markdown";if(!v){let ae=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let re=O.getMessages().find(xe=>xe.id===ae);if(re?.rawContent)try{let xe=JSON.parse(re.rawContent);v=xe?.props?.markdown,T=xe?.props?.title||T,xe?.props?.file&&typeof xe.props.file=="object"&&(L=xe.props.file),!h&&typeof xe?.props?.artifactType=="string"&&(J=xe.props.artifactType)}catch{}}}return{markdown:v,title:T,file:L,artifactType:J}};be.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:L,title:J,file:_}=ai(h,v);if(!L)return;let{filename:X,mime:ae,content:pe}=dp({title:J,markdown:L,file:_}),re=new Blob([pe],{type:ae}),xe=URL.createObjectURL(re),Ke=document.createElement("a");Ke.href=xe,Ke.download=X,Ke.click(),URL.revokeObjectURL(xe)}),be.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.getAttribute("data-artifact-custom-action");if(!v)return;let T=h.closest("[data-artifact-inline]"),L=T?null:h.closest("[data-open-artifact]"),J=T?T.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,X=(T?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===v);if(!X)return;let{markdown:ae,title:pe,file:re,artifactType:xe}=ai(h,J??""),Ke={artifactId:J,title:pe,artifactType:xe,markdown:ae,file:re};try{Promise.resolve(X.onClick(Ke)).catch(()=>{})}catch{}}),be.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.getAttribute("data-copy-artifact");if(!v)return;let T=O.getArtifactById(v),L="";if(T)L=cs(T);else{let{markdown:J,file:_,artifactType:X}=ai(h,v);X==="markdown"&&(L=cs({id:v,artifactType:"markdown",status:"complete",markdown:J??"",..._?{file:_}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let J=ie("check",16,"currentColor",2);J&&(h.replaceChildren(J),setTimeout(()=>{let _=ie("copy",16,"currentColor",2);_&&h.replaceChildren(_)},1500))}).catch(()=>{})}),be.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let v=h.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(kn=!1,Uo=!0,mn=!0,Er=!0,O.selectArtifact(v),Ln())}),be.addEventListener("click",i=>{let g=i.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let h=g.closest("[data-open-artifact]");if(!h)return;let v=h.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),kn=!1,Uo=!0,O.selectArtifact(v),Ln())}),be.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let g=i.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),g.click())});let zo=Re.composerOverlay,jo=(i,g,h)=>{let v=g.trim();if(!v||!mt.current)return;let T=i.getAttribute("data-tool-call-id")??"",L=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:v,answers:h.structured,values:h.values??(h.source==="multi"?v.split(", "):[v]),isFreeText:L,source:h.source},bubbles:!0,composed:!0})),rr(zo,T);let J=mt.current.getMessages().find(_=>_.toolCall?.id===T);J?.agentMetadata?.awaitingLocalTool?mt.current.resolveAskUserQuestion(J,h.structured??v):mt.current.sendMessage(v)},go=i=>{let g=mt.current;if(!g)return;let h=i.getAttribute("data-tool-call-id")??"",v=g.getMessages().find(T=>T.toolCall?.id===h);v&&g.persistAskUserQuestionProgress(v,{answers:aa(i,v),currentIndex:un(i)})},Zl=i=>Object.entries(i).map(([g,h])=>`${g}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ii=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=un(i),h=or(i);if(g>=h-1)return;let v=mt.current?.getMessages().find(T=>T.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(la(i,v,o,g+1),go(i))};zo.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;let T=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),T==="dismiss"){let L=v.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),rr(zo,L);let J=mt.current?.getMessages().find(_=>_.toolCall?.id===L);J?.agentMetadata?.awaitingLocalTool&&(mt.current?.markAskUserQuestionResolved(J),mt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(T==="pick"){let L=h.getAttribute("data-option-label");if(!L)return;let J=v.getAttribute("data-multi-select")==="true",_=eo(v);if(_&&J){let X=Ro(v)[un(v)],ae=new Set(Array.isArray(X)?X:[]);ae.has(L)?ae.delete(L):ae.add(L),to(v,Array.from(ae)),go(v);return}if(_){to(v,L),go(v),ii(v);return}if(J){let X=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",X?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!X);let ae=v.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=Ui(v).length===0);return}jo(v,L,{source:"pick",values:[L]});return}if(T==="submit-multi"){let L=Ui(v);if(L.length===0)return;jo(v,L.join(", "),{source:"multi",values:L});return}if(T==="open-free-text"){let L=v.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(T==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(T==="submit-free-text"){let J=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(eo(v)){to(v,J.trim()),go(v),ii(v);return}jo(v,J,{source:"free-text"});return}if(T==="next"||T==="back"){if(!mt.current)return;let L=v.getAttribute("data-tool-call-id")??"",J=mt.current.getMessages().find(re=>re.toolCall?.id===L);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=Ro(v)[un(v)];(typeof re!="string"||re!==X)&&to(v,X)}let ae=T==="next"?1:-1,pe=un(v)+ae;la(v,J,o,pe),go(v);return}if(T==="submit-all"){if(!mt.current)return;let L=v.getAttribute("data-tool-call-id")??"",J=mt.current.getMessages().find(re=>re.toolCall?.id===L);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&to(v,X);let ae=aa(v,J);mt.current.persistAskUserQuestionProgress(J,{answers:ae,currentIndex:un(v)});let pe=Zl(ae);jo(v,pe||"(submitted)",{source:"submit-all",structured:ae});return}if(T==="skip"){if(!mt.current)return;let L=v.getAttribute("data-tool-call-id")??"",J=mt.current.getMessages().find(xe=>xe.toolCall?.id===L);if(!J)return;let _=eo(v),X=un(v),ae=or(v),pe=X>=ae-1;if(!_){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),rr(zo,L),J.agentMetadata?.awaitingLocalTool&&(mt.current.markAskUserQuestionResolved(J),mt.current.resolveAskUserQuestion(J,"(dismissed)"));return}to(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),pe){let xe=aa(v,J),Ke=Zl(xe);jo(v,Ke||"(skipped)",{source:"submit-all",structured:xe});return}la(v,J,o,X+1),go(v);return}}),zo.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let v=h.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let T=h.value;if(T.trim()){if(eo(v)){to(v,T.trim()),go(v),ii(v);return}jo(v,T,{source:"free-text"})}});let ec=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let g=i.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let h=zo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),L=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",ec);let zn=null,wt=null,kr=null,Ls=null,li=()=>{},tc=!1,Ps="",Is="";function ci(){Ls?.(),Ls=null}let nc=()=>{if(!zn||!wt)return;let i=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,h=g.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||h){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let v=zn.firstElementChild;if(!v||v===wt)return;let T=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${T}px`,wt.style.zIndex="5";let L=Al(zn,g),J=v.offsetWidth+L/2-T/2;wt.style.left=`${Math.max(0,J)}px`},Rs=()=>{},Ku=()=>{let i=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!g||i.innerWidth>h?!1:R||Ot(o)},Ws=()=>!Qt(o)||!ks()||t.classList.contains("persona-artifact-narrow-host")||Ku()||(t.ownerDocument.defaultView??window).innerWidth<fy?"none":Cl(o)?"detached":"welded",Ln=()=>{if(!Ye||!Qt(o))return;xs(t,o),Cs(t,o),Rs();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=he.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=i);let h=ks();Ye.setVisible(h),Ye.update(gn),kn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),mn=!1,Er=!1):gn.artifacts.length>0&&Yl()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),mn=!1,Er=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!Er&&(mn=!1),mn!==tc){let L=Ye.element;mn?(Ps=L.style.width,Is=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Ps&&(L.style.width=Ps),Is&&(L.style.maxWidth=Is),Ps="",Is=""),tc=mn}t.classList.toggle("persona-artifact-expanded",mn),Ye.setExpanded(mn);let T=Ws();T!==Mr&&(Mr=T,Tr()),li()};if(Qt(o)){he.style.position="relative";let i=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(fe),Ye=uu(o,{onSelect:h=>mt.current?.selectArtifact(h),onDismiss:()=>{kn=!0,Ln()},onToggleExpand:()=>{let h=!mn,v=gn.selectedId??gn.artifacts[gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:h})!==!0&&(mn=h,h||(Er=!1),Ln())}}),Ye.element.classList.add("persona-hidden"),zn=g,g.appendChild(i),g.appendChild(Ye.element),Ye.backdrop&&he.appendChild(Ye.backdrop),he.appendChild(g),li=()=>{if(!zn||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){kr?.(),kr=null,ci(),wt&&(wt.remove(),wt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!wt){let v=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let T=t.ownerDocument,L=T.defaultView??window,J=_=>{if(!Ye||_.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;_.preventDefault(),ci();let X=_.clientX,ae=Ye.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,re=Ke=>{let yt=zn.getBoundingClientRect().width,at=t.classList.contains("persona-artifact-welded-split"),qt=Al(zn,L),Ht=at?0:v.getBoundingClientRect().width||6,I=ae-(Ke.clientX-X),Oe=hu(I,yt,qt,Ht,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ye.element.style.width=`${Oe}px`,Ye.element.style.maxWidth="none",nc()},xe=()=>{T.removeEventListener("pointermove",re),T.removeEventListener("pointerup",xe),T.removeEventListener("pointercancel",xe),Ls=null;try{v.releasePointerCapture(_.pointerId)}catch{}};Ls=xe,T.addEventListener("pointermove",re),T.addEventListener("pointerup",xe),T.addEventListener("pointercancel",xe);try{v.setPointerCapture(_.pointerId)}catch{}};v.addEventListener("pointerdown",J),wt=v,zn.insertBefore(v,Ye.element),kr=()=>{v.removeEventListener("pointerdown",J)}}if(wt){let v=ks();wt.classList.toggle("persona-hidden",!v),nc()}},Rs=()=>{if(!R||!Ye||(o.launcher?.sidebarMode??!1)||Ot(o)&&fn(o).reveal==="emerge")return;let v=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(T&&v.innerWidth<=L||!mu(o,R))return;let J=o.launcher?.width??o.launcherWidth??Nn,_=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";ks()?(he.style.width=_,he.style.maxWidth=_):(he.style.width=J,he.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Sr=new ResizeObserver(()=>{Ln()}),Sr.observe(he))}else he.appendChild(fe);Y()&&lt&&(Re.peekBanner&&lt.appendChild(Re.peekBanner),lt.appendChild(q)),t.appendChild(ke),lt&&t.appendChild(lt);let Bs=()=>{if(Y()){he.style.width="100%",he.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},Yt=ke.dataset.state==="expanded",Gs=Pt.expandedSize??"anchored";if(!(Yt&&Gs!=="fullscreen")){fe.style.background="",fe.style.border="",fe.style.borderRadius="",fe.style.overflow="",fe.style.boxShadow="";return}let _r=o.theme?.components?.panel,Xs=dr(o),Yo=(Wn,To)=>Wn==null||Wn===""?To:Gt(Xs,Wn)??Wn,$r="1px solid var(--persona-border)",Wi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",So="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";fe.style.background="var(--persona-surface, #ffffff)",fe.style.border=Yo(_r?.border,$r),fe.style.borderRadius=Yo(_r?.borderRadius,So),fe.style.boxShadow=Yo(_r?.shadow,Wi),fe.style.overflow="hidden";return}let i=Ot(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,T=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,J=dr(o),_=(Pt,Yt)=>Pt==null||Pt===""?Yt:Gt(J,Pt)??Pt,X=t.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=pe,xe=ae&&re&&R,Ke=i&&ae&&re,yt=o.launcher?.position??"bottom-left",at=yt==="bottom-left"||yt==="top-left",qt=o.launcher?.zIndex??zt,Ht="var(--persona-panel-border, 1px solid var(--persona-border))",I="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",Oe="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Te=T&&!xe&&!Ke;Te?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let $e=Te?Ht:g||xe?"none":Ht,Tt=Te?I:xe?"none":g?at?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":v?"none":I;i&&!xe&&!Te&&(Tt="none",$e="none");let ut=Te?Oe:g||xe?"0":Oe,Ct=_(L?.border,$e),bt=_(L?.shadow,Tt),$t=_(L?.borderRadius,ut),Co=Ws(),ft=Co==="detached",ue=Co==="welded";t.classList.toggle("persona-artifact-detached-split",ft),t.classList.toggle("persona-artifact-welded-split",ue);let At="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",rt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Qt(o)&&Cl(o)&&v&&!i;t.classList.toggle("persona-artifact-chat-flush",rt);let qe=ft||rt?"none":bt,Ze=ft?Ht:ue?"none":Ct,Lt=ft?Oe:$t;rt&&(Ze="none",Lt="0");let De=L?.borderRadius!=null&&L.borderRadius!=="",et=rt&&!De?"0":$t,nn=le.scrollTop;t.style.cssText="",ke.style.cssText="",he.style.cssText="",fe.style.cssText="",le.style.cssText="",q.style.cssText="",Ie&&(le.style.display="none");let Ao=()=>{if(nn<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===nn)return;let Yt=le.scrollHeight-le.clientHeight;Yt<=0||(le.scrollTop=Math.min(nn,Yt))})};if(xe){ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ke.style.cssText=`
35
41
  position: fixed !important;
36
42
  inset: 0 !important;
37
43
  width: 100% !important;
@@ -41,9 +47,9 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
41
47
  padding: 0 !important;
42
48
  display: flex !important;
43
49
  flex-direction: column !important;
44
- z-index: ${Oe} !important;
50
+ z-index: ${qt} !important;
45
51
  background-color: var(--persona-surface, #ffffff) !important;
46
- `,X.style.cssText=`
52
+ `,he.style.cssText=`
47
53
  position: relative !important;
48
54
  display: flex !important;
49
55
  flex-direction: column !important;
@@ -56,7 +62,7 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
56
62
  padding: 0 !important;
57
63
  box-shadow: none !important;
58
64
  border-radius: 0 !important;
59
- `,Ee.style.cssText=`
65
+ `,fe.style.cssText=`
60
66
  display: flex !important;
61
67
  flex-direction: column !important;
62
68
  flex: 1 1 0% !important;
@@ -67,20 +73,33 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
67
73
  overflow: hidden !important;
68
74
  border-radius: 0 !important;
69
75
  border: none !important;
70
- `,xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",He.style.flexShrink="0",U=!0,Qe();return}let vt=(No=(Qt=r==null?void 0:r.launcher)==null?void 0:Qt.width)!=null?No:r==null?void 0:r.launcherWidth,R=vt!=null?vt:Qr;if(!p&&!i)b&&f?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=R,X.style.maxWidth=R);else if(i)if(mr(r).reveal==="emerge"){let Nt=mr(r).width;X.style.width=Nt,X.style.maxWidth=Nt}else X.style.width="100%",X.style.maxWidth="100%";if(ko(),X.style.boxShadow=Be,X.style.borderRadius=Re,Ee.style.border=at,Ee.style.borderRadius=Re,i&&!te&&(C==null?void 0:C.border)===void 0&&(Ee.style.border="none",mr(r).side==="right"?Ee.style.borderLeft="1px solid var(--persona-border)":Ee.style.borderRight="1px solid var(--persona-border)"),f&&(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"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.style.overflow="hidden",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.overflow="hidden",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",He.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&&!i&&((mo=gr[we])!=null?mo:gr["bottom-right"]).split(" ").forEach(Nt=>me.classList.add(Nt)),p){let Ft=(jr=(go=r.launcher)==null?void 0:go.sidebarWidth)!=null?jr:"420px";me.style.cssText=`
71
- position: fixed !important;
72
- top: 0 !important;
73
- bottom: 0 !important;
74
- width: ${Ft} !important;
75
- height: 100vh !important;
76
- max-height: 100vh !important;
77
- margin: 0 !important;
78
- padding: 0 !important;
79
- display: flex !important;
80
- flex-direction: column !important;
81
- z-index: ${Oe} !important;
82
- ${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
- `,X.style.cssText=`
76
+ `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",q.style.flexShrink="0",V=!0,Ao();return}let Ks=o?.launcher?.width??o?.launcherWidth??Nn;if(!g&&!i)v&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=Ks,he.style.maxWidth=Ks);else if(i)if(fn(o).reveal==="emerge"&&!T){let Yt=fn(o).width;he.style.width=Yt,he.style.maxWidth=Yt}else he.style.width="100%",he.style.maxWidth="100%";if(Rs(),he.style.boxShadow=qe,he.style.borderRadius=et,ft?he.style.border="none":ue&&(he.style.border=Ct),fe.style.border=Ze,fe.style.borderRadius=Lt,fe.style.boxShadow=ft&&!rt?At:"",rt&&(fe.style.background="transparent",le.style.background="transparent",q.style.background="transparent",q.style.borderTop="none"),ue){let Pt=o.features?.artifacts?.layout;Es=Pt?.unifiedSplitOuterRadius?.trim()||Pt?.paneBorderRadius?.trim()||$t}else Es=null;if(i&&!xe&&!Te&&!ft&&!ue&&L?.border===void 0&&(fe.style.border="none",fn(o).side==="right"?fe.style.borderLeft="1px solid var(--persona-border)":fe.style.borderRight="1px solid var(--persona-border)"),i&&!xe&&ue&&L?.border===void 0&&(fn(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),h&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",v&&(t.style.width="100%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",v&&(ke.style.overflow="hidden"),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%",ft||(he.style.overflow="hidden"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",q.style.flexShrink="0"),v&&(Te||ft||rt)&&!i&&(rt||(ke.style.padding="var(--persona-panel-inset)"),ke.style.background="var(--persona-panel-canvas-bg)"),ke.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!v&&!i&&(xn[yt]??xn["bottom-right"]).split(" ").forEach(Yt=>ke.classList.add(Yt)),g){let Pt=o.launcher?.sidebarWidth??"420px";T?ke.style.cssText=`
77
+ position: fixed !important;
78
+ top: var(--persona-panel-inset) !important;
79
+ bottom: var(--persona-panel-inset) !important;
80
+ width: ${Pt} !important;
81
+ height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
82
+ max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
83
+ margin: 0 !important;
84
+ padding: 0 !important;
85
+ display: flex !important;
86
+ flex-direction: column !important;
87
+ z-index: ${qt} !important;
88
+ ${at?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
89
+ `:ke.style.cssText=`
90
+ position: fixed !important;
91
+ top: 0 !important;
92
+ bottom: 0 !important;
93
+ width: ${Pt} !important;
94
+ height: 100vh !important;
95
+ max-height: 100vh !important;
96
+ margin: 0 !important;
97
+ padding: 0 !important;
98
+ display: flex !important;
99
+ flex-direction: column !important;
100
+ z-index: ${qt} !important;
101
+ ${at?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
102
+ `,he.style.cssText=`
84
103
  position: relative !important;
85
104
  display: flex !important;
86
105
  flex-direction: column !important;
@@ -91,9 +110,10 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
91
110
  min-height: 0 !important;
92
111
  margin: 0 !important;
93
112
  padding: 0 !important;
94
- box-shadow: ${Be} !important;
95
- border-radius: ${Re} !important;
96
- `,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),Ee.style.cssText=`
113
+ box-shadow: ${qe} !important;
114
+ border-radius: ${et} !important;
115
+ ${ft?"border: none !important;":ue?`border: ${Ct} !important;`:""}
116
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),fe.style.cssText=`
97
117
  display: flex !important;
98
118
  flex-direction: column !important;
99
119
  flex: 1 1 0% !important;
@@ -102,15 +122,18 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
102
122
  min-height: 0 !important;
103
123
  max-height: 100% !important;
104
124
  overflow: hidden !important;
105
- border-radius: ${Re} !important;
106
- border: ${at} !important;
107
- `,He.style.cssText=`
125
+ border-radius: ${Lt} !important;
126
+ border: ${Ze} !important;
127
+ ${ft&&!rt?`box-shadow: ${At} !important;`:""}
128
+ ${rt?"background: transparent !important;":""}
129
+ `,q.style.cssText=`
108
130
  flex-shrink: 0 !important;
109
131
  border-top: none !important;
110
132
  padding: 8px 16px 12px 16px !important;
111
- `}if(!b&&!i){let Ft="max-height: -moz-available !important; max-height: stretch !important;",Nt=p?"":"padding-top: 1.25em !important;",Kt=p?"":`z-index: ${(et=(Fo=r.launcher)==null?void 0:Fo.zIndex)!=null?et:xn} !important;`;me.style.cssText+=Ft+Nt+Kt}Qe()};oo(),As(n,r),yi(n,r),bi(n,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Nr)}),ct.push(()=>{ar!==null&&clearTimeout(ar)});let nn=null,rn=null;ct.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{Xn==null||Xn(),Xn=null,Yo(),_t&&(_t.remove(),_t=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),ie&&ct.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Se==null||Se.destroy(),Se=null,K==null||K.destroy(),K=null,Ae=null});let Ar=null,Ws=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=Bm(()=>{As(n,r)}))};Ws(),ct.push(()=>{Ar&&(Ar(),Ar=null)}),ct.push(a);let Or=(rd=r.features)==null?void 0:rd.streamAnimation;if(Or!=null&&Or.type&&Or.type!=="none"){let i=Ss(Or.type,Or.plugins);i&&(ri(i,n),ct.push(()=>Qm(n)))}let Lo=fg(jt),Sr=null,$,Zo=i=>{var b,C;if(!$)return;let p=i!=null?i:$.getMessages(),f=((C=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:C.enabled)!==!1?em(p):null;f?Lo.render(f,$,be,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(L=>L.role==="user")?Lo.render([],$,be,p):Lo.render(r.suggestionChips,$,be,p,r.suggestionChipsConfig)},Jn=!1,Tr=_m(),_r=new Map,Er=new Map,lr=new Map,es=0,va=$o()!==null,bn=Ja(),Tn=0,cr=null,En=!1,Po=!1,dr=0,vn=null,Mr=null,ts=!1,Io=!1,ns=null,so=!0,ao=!1,st=null,x=4,V=24,j=80,Q=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(sd=(od=r.voiceRecognition)==null?void 0:od.autoResume)!=null?sd:!1,rt=i=>{l.emit("voice:state",{active:G.active,source:i,timestamp:Date.now()})},dt=()=>{w(i=>({...i,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},xi=()=>{var b,C;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let i=Ml(u.voiceState),p=!!i.active,f=Number((C=i.timestamp)!=null?C:0);G.manuallyDeactivated=!!i.manuallyDeactivated,p&&Date.now()-f<Lb&&setTimeout(()=>{var L,q;G.active||(G.manuallyDeactivated=!1,((q=(L=r.voiceRecognition)==null?void 0:L.provider)==null?void 0:q.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("restore"),$.isVoiceActive()&&as()}):Ca("restore"))},1e3)},io=()=>$?Ng($.getMessages()).filter(i=>!i.__skipPersist):[],Mn=null,dn=(i,p)=>{typeof console!="undefined"&&console.error(i,p)},$r=(i,p)=>{let f=()=>{try{let q=i();return!q||typeof q.then!="function"?null:Promise.resolve(q).catch(F=>{dn(p,F)})}catch(q){return dn(p,q),null}},b=Mn,C=b?b.then(()=>{var q;return(q=f())!=null?q:void 0}):f();if(!C)return;let L=C.finally(()=>{Mn===L&&(Mn=null)});Mn=L};function kr(i){if(!(c!=null&&c.save))return;let f={messages:i?Ng(i):$?io():[],metadata:u,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};$r(()=>c.save(f),"[AgentWidget] Failed to persist state:")}let on=null,kn=()=>me.querySelector("#persona-scroll-container")||xe,mn=()=>{on!==null&&(cancelAnimationFrame(on),on=null),En=!1},Hl=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),Po=!1,mn()},Yg=()=>Jn&&Ai()&&(Ot()!=="anchor-top"||or()),Ci=()=>{let i=wt()||"Jump to latest",p=Yg();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",p),dr>0?(Bn.textContent=String(dr),Bn.style.display="",Vt.setAttribute("aria-label",`${i} (${dr} new)`)):(Bn.textContent="",Bn.style.display="none",Vt.setAttribute("aria-label",p?`${i} (response streaming below)`:i))},Bl=()=>{dr!==0&&(dr=0,Ci())},Ai=()=>Zt()?!bn.isFollowing():!xo(xe,V),_n=()=>{if(!Xt()||Y){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==Ee&&Ee.appendChild(Vt),Vn();let p=Rr(xe)>0&&Ai();p?Ci():Bl(),Vt.style.display=p?"":"none"},Hs=()=>{bn.pause()&&(Hl(),_n())},lo=()=>{bn.resume(),Bl(),_n()},co=(i=!1)=>{Zt()&&bn.isFollowing()&&(!i&&!Jn||(cr!==null&&(cancelAnimationFrame(cr),cr=null),Po=!0,cr=requestAnimationFrame(()=>{cr=null,Po=!1,bn.isFollowing()&&Zg(kn(),i?220:140)})))},Dl=(i,p,f,b=()=>!0)=>{let C=i.scrollTop,L=p(),q=L-C;if(mn(),Math.abs(q)<1){En=!0,i.scrollTop=L,Tn=i.scrollTop,En=!1;return}let F=performance.now();En=!0;let N=se=>1-Math.pow(1-se,3),ae=se=>{if(!b()){mn();return}let te=p();te!==L&&(L=te,q=L-C);let we=se-F,Fe=Math.min(we/f,1),Oe=N(Fe),Ue=C+q*Oe;i.scrollTop=Ue,Tn=i.scrollTop,Fe<1?on=requestAnimationFrame(ae):(i.scrollTop=L,Tn=i.scrollTop,on=null,En=!1)};on=requestAnimationFrame(ae)},Zg=(i,p=500)=>{let f=Rr(i)-i.scrollTop;if(Math.abs(f)<1){Tn=i.scrollTop;return}if(Math.abs(f)>=j){mn(),En=!0,i.scrollTop=Rr(i),Tn=i.scrollTop,En=!1;return}Dl(i,()=>Rr(i),p,()=>bn.isFollowing())},Nl=()=>{let i=kn();En=!0,i.scrollTop=Rr(i),Tn=i.scrollTop,En=!1,_n()},Fl=i=>{let p=0,f=i;for(;f&&f!==xe;)p+=f.offsetTop,f=f.offsetParent;return p},Ol=()=>{var L;if(Wr()!=="last-user-turn")return!1;let i=(L=$==null?void 0:$.getMessages())!=null?L:[];if(i.length<2)return!1;let p=[...i].reverse().find(q=>q.role==="user");if(!p)return!1;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(p.id):p.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=xe.querySelector(`[data-message-id="${f}"]`);if(!b)return!1;let C=Math.min(Math.max(0,Fl(b)-yr()),Rr(xe));return En=!0,xe.scrollTop=C,Tn=xe.scrollTop,En=!1,Ot()==="follow"&&!xo(xe,V)&&bn.pause(),_n(),!0},_l=i=>{In.style.height=`${Math.max(0,Math.round(i))}px`,vn&&(vn.spacerHeight=Math.max(0,i))},Bs=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),mn(),vn=null,In.style.height="0px"},ef=i=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var N;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=xe.querySelector(`[data-message-id="${p}"]`);if(!f)return;let b=Fl(f),C=(N=vn==null?void 0:vn.spacerHeight)!=null?N:0,L=xe.scrollHeight-C,{targetScrollTop:q,spacerHeight:F}=jm({anchorOffsetTop:b,topOffset:yr(),viewportHeight:xe.clientHeight,contentHeight:L});vn={initialSpacerHeight:F,contentHeightAtAnchor:L,spacerHeight:F},_l(F),Dl(xe,()=>q,220)})},tf=()=>{if(Zt()){if(!bn.isFollowing()||xo(xe,1))return;co(!Jn);return}if(vn&&vn.initialSpacerHeight>0){let i=xe.scrollHeight-vn.spacerHeight,p=Vm({initialSpacerHeight:vn.initialSpacerHeight,contentHeightAtAnchor:vn.contentHeightAtAnchor,currentContentHeight:i});p!==vn.spacerHeight&&_l(p)}_n()},nf=i=>{let p=Ot();p==="follow"?(lo(),co(!0)):p==="anchor-top"&&(so=!1,ao=!0,ef(i))},rf=()=>{if(Ot()==="anchor-top"){if(ao){so=!1;return}so=!0,Bs(),lo(),co(!0)}},of=i=>{let p=new Map;i.forEach(f=>{let b=Q.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!b&&f.role==="assistant"&&(l.emit("assistant:message",f),!Io&&(Ot()!=="anchor-top"||or())&&Ai()&&(dr+=1,Ci(),_n(),Jr(dr===1?"1 new message below.":`${dr} new messages below.`))),f.role==="assistant"&&(b!=null&&b.streaming)&&f.streaming===!1&&l.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(b?f.approval.status!=="pending"&&l.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):l.emit("approval:requested",{approval:f.approval,message:f}))}),Q.clear(),p.forEach((f,b)=>{Q.set(b,f)})},sf=(i,p,f)=>{var at,Be,Re,je,Qe,vt;let b=document.createElement("div"),L=(()=>{var De;let R=o.find(We=>We.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(R,De)=>De==null?!1:typeof De=="string"?(R.textContent=De,!0):(R.appendChild(De),!0),F=new Set,N=new Set,ae=o.some(R=>R.renderAskUserQuestion),se=[],te=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,Oe=[];if(p.forEach(R=>{var gn,$n,Ke,Rt,Un,Wo,Ho,Bo,Do,ls,cs,Qt,No,mo,go,jr,Fo;F.add(R.id);let De=ae&&Uo(R),We=Fe&&R.variant==="approval"&&!!R.approval,Je=!De&&R.role==="assistant"&&!R.variant&&we&&El(R);if(!We&&lr.has(R.id)){let et=i.querySelector(`#wrapper-${R.id}`);et==null||et.removeAttribute("data-preserve-runtime"),lr.delete(R.id)}if(!Je&&Er.has(R.id)){let et=i.querySelector(`#wrapper-${R.id}`);et==null||et.removeAttribute("data-preserve-runtime"),Er.delete(R.id)}let It=Uo(R)?`:${(gn=R.agentMetadata)!=null&&gn.askUserQuestionAnswered?"a":"u"}:${($n=R.agentMetadata)!=null&&$n.askUserQuestionAnswers?Object.keys(R.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=Om(R,es)+It,Gt=De||We||Je?null:$m(Tr,R.id,_e);if(Gt){b.appendChild(Gt.cloneNode(!0)),Uo(R)&&((Ke=R.toolCall)!=null&&Ke.id)&&((Rt=R.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((Un=R.agentMetadata)!=null&&Un.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Wa(R,r,Ve.composerOverlay));return}let Ct=null,an=o.find(et=>!!(R.variant==="reasoning"&&et.renderReasoning||R.variant==="tool"&&et.renderToolCall||!R.variant&&et.renderMessage)),Wn=(Wo=r.layout)==null?void 0:Wo.messages;if(Uo(R)&&((Ho=R.agentMetadata)==null?void 0:Ho.askUserQuestionAnswered)===!0){_r.delete(R.id);let et=i.querySelector(`#wrapper-${R.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Vi(R)&&((Do=(Bo=r.features)==null?void 0:Bo.suggestReplies)==null?void 0:Do.enabled)!==!1)return;if(Uo(R)&&((cs=(ls=r.features)==null?void 0:ls.askUserQuestion)==null?void 0:cs.enabled)!==!1){let et=o.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(et&&Tt.current){let Ft=_r.get(R.id),Nt=Ft!==_e,Kt=null;if(Nt){let{payload:qt,complete:fn}=gs(R),qn=R.id,Pr=()=>{var pn;return(pn=Tt.current)==null?void 0:pn.getMessages().find(un=>un.id===qn)};Kt=et.renderAskUserQuestion({message:R,payload:qt,complete:fn,resolve:pn=>{var er;let un=Pr();un&&((er=Tt.current)==null||er.resolveAskUserQuestion(un,pn))},dismiss:()=>{var un,er,fo;let pn=Pr();(un=pn==null?void 0:pn.agentMetadata)!=null&&un.awaitingLocalTool&&((er=Tt.current)==null||er.markAskUserQuestionResolved(pn),(fo=Tt.current)==null||fo.resolveAskUserQuestion(pn,"(dismissed)"))},config:r})}let Ut=Ft!=null;if(Nt&&Kt===null&&!Ut){((Qt=R.agentMetadata)==null?void 0:Qt.awaitingLocalTool)===!0&&!((No=R.agentMetadata)!=null&&No.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Wa(R,r,Ve.composerOverlay));return}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${R.id}`,gt.setAttribute("data-wrapper-id",R.id),gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),se.push({messageId:R.id,fingerprint:_e,bubble:Kt});return}else{((mo=R.agentMetadata)==null?void 0:mo.awaitingLocalTool)===!0&&!((go=R.agentMetadata)!=null&&go.askUserQuestionAnswered)&&(N.add(R.toolCall.id),Wa(R,r,Ve.composerOverlay));return}}else if(We){let et=(jr=o.find(Ut=>typeof Ut.renderApproval=="function"))!=null?jr:s,Nt=lr.get(R.id)!==_e,Kt=null;if(Nt&&(et!=null&&et.renderApproval)){let Ut=R.id,gt=(qt,fn)=>{var Pr,pn,un;let qn=(Pr=Tt.current)==null?void 0:Pr.getMessages().find(er=>er.id===Ut);qn!=null&&qn.approval&&(qn.approval.toolType==="webmcp"?(pn=Tt.current)==null||pn.resolveWebMcpApproval(qn.id,qt):(un=Tt.current)==null||un.resolveApproval(qn.approval,qt,fn))};Kt=et.renderApproval({message:R,defaultRenderer:()=>fi(R,r),config:r,approve:qt=>gt("approved",qt),deny:qt=>gt("denied",qt)})}if(Nt&&Kt===null){let Ut=i.querySelector(`#wrapper-${R.id}`);Ut==null||Ut.removeAttribute("data-preserve-runtime"),lr.delete(R.id),Ct=fi(R,r)}else{let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id=`wrapper-${R.id}`,Ut.setAttribute("data-wrapper-id",R.id),Ut.setAttribute("data-approval-plugin-stub","true"),Ut.setAttribute("data-preserve-runtime","true"),b.appendChild(Ut),Oe.push({messageId:R.id,fingerprint:_e,bubble:Kt});return}}else if(an)if(R.variant==="reasoning"&&R.reasoning&&an.renderReasoning){if(!Pe)return;Ct=an.renderReasoning({message:R,defaultRenderer:()=>ul(R,r),config:r})}else if(R.variant==="tool"&&R.toolCall&&an.renderToolCall){if(!Ie)return;Ct=an.renderToolCall({message:R,defaultRenderer:()=>gl(R,r),config:r})}else an.renderMessage&&(Ct=an.renderMessage({message:R,defaultRenderer:()=>{let et=pl(R,f,Wn,r.messageActions,Ye,{loadingIndicatorRenderer:L,widgetConfig:r});return R.role!=="user"&&vl(et,R,r,$),et},config:r}));if(!Ct&&Je){let et=Hg(R);if(et){let Ft=Er.get(R.id),Nt=Ft!==_e,Kt=r.wrapComponentDirectiveInBubble!==!1,Ut=null;if(Nt){let gt=Rg(et,{config:r,message:R,transform:f});if(gt)if(Kt){let qt=document.createElement("div");if(qt.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(" "),qt.id=`bubble-${R.id}`,qt.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let fn=document.createElement("div");fn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",fn.innerHTML=f({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),qt.appendChild(fn)}qt.appendChild(gt),Ut=qt}else{let qt=document.createElement("div");if(qt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",qt.id=`bubble-${R.id}`,qt.setAttribute("data-message-id",R.id),qt.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let fn=document.createElement("div");fn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",fn.innerHTML=f({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),qt.appendChild(fn)}qt.appendChild(gt),Ut=qt}}if(Ut||Ft!=null){let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${R.id}`,gt.setAttribute("data-wrapper-id",R.id),gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),Kt||gt.classList.add("persona-w-full"),b.appendChild(gt),te.push({messageId:R.id,fingerprint:_e,bubble:Ut});return}}}if(!Ct)if(R.variant==="reasoning"&&R.reasoning){if(!Pe)return;Ct=ul(R,r)}else if(R.variant==="tool"&&R.toolCall){if(!Ie)return;Ct=gl(R,r)}else if(R.variant==="approval"&&R.approval){if(r.approval===!1)return;Ct=fi(R,r)}else{let et=(Fo=r.layout)==null?void 0:Fo.messages;et!=null&&et.renderUserMessage&&R.role==="user"?Ct=et.renderUserMessage({message:R,config:r,streaming:!!R.streaming}):et!=null&&et.renderAssistantMessage&&R.role==="assistant"?Ct=et.renderAssistantMessage({message:R,config:r,streaming:!!R.streaming}):Ct=pl(R,f,et,r.messageActions,Ye,{loadingIndicatorRenderer:L,widgetConfig:r}),R.role!=="user"&&Ct&&vl(Ct,R,r,$)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${R.id}`,Dt.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Dt.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(Ct),Um(Tr,R.id,_e,Dt),b.appendChild(Dt)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!N.has(We)&&hs(Ve.composerOverlay,We)}),(Be=(at=r.features)==null?void 0:at.toolCallDisplay)!=null&&Be.grouped){let R=[],De=[];p.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Ie){De.push(We);return}De.length>1&&R.push(De),De=[]}),De.length>1&&R.push(De),R.forEach((We,Je)=>{var gn,$n;let It=We.map(Ke=>Array.from(b.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Ke.id)).filter(Ke=>!!Ke);if(It.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Je}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Je}-${We[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Wn=($n=(gn=r.toolCall)==null?void 0:gn.renderGroupedSummary)==null?void 0:$n.call(gn,{messages:We,toolCalls:We.map(Ke=>Ke.toolCall).filter(Ke=>!!Ke),defaultSummary:an,config:r});q(Ct,Wn)||(Ct.textContent=an);let Dt=document.createElement("div");Dt.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(Ct,Dt),_e.appendChild(Gt),It[0].before(_e),It.forEach((Ke,Rt)=>{let Un=document.createElement("div");Un.className="persona-tool-group-item persona-relative",Un.setAttribute("data-persona-tool-group-item","true"),Rt<It.length-1&&Un.setAttribute("data-persona-tool-group-connector","true"),Un.appendChild(Ke),Dt.appendChild(Un)})})}qm(Tr,F);let Ue=p.some(R=>R.role==="assistant"&&R.streaming),ze=p[p.length-1],mt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Jn&&p.some(R=>R.role==="user")&&!Ue&&!mt){let R={config:r,streaming:!0,location:"standalone",defaultRenderer:ma},De=o.find(Je=>Je.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(R)),We===null&&((Re=r.loadingIndicator)!=null&&Re.render)&&(We=r.loadingIndicator.render(R)),We===null&&(We=ma()),We){let Je=document.createElement("div"),It=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;Je.className=It?["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(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.appendChild(We);let _e=document.createElement("div");_e.className="persona-flex",_e.id="wrapper-typing-indicator",_e.setAttribute("data-wrapper-id","typing-indicator"),_e.appendChild(Je),b.appendChild(_e)}}if(!Jn&&p.length>0){let R=p[p.length-1],De={config:r,lastMessage:R,messageCount:p.length},We=o.find(It=>It.renderIdleIndicator),Je=null;if(We!=null&&We.renderIdleIndicator&&(Je=We.renderIdleIndicator(De)),Je===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(Je=r.loadingIndicator.renderIdle(De)),Je){let It=document.createElement("div"),_e=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;It.className=_e?["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(" "),It.setAttribute("data-idle-indicator","true"),It.appendChild(Je);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(It),b.appendChild(Gt)}}if(Qa(i,b),se.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of se){let Je=i.querySelector(`#wrapper-${R}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),_r.set(R,De))}if(_r.size>0)for(let R of _r.keys())F.has(R)||_r.delete(R);if(te.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of te){let Je=i.querySelector(`#wrapper-${R}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),Er.set(R,De))}if(Er.size>0)for(let R of Er.keys())F.has(R)||Er.delete(R);if(Oe.length>0)for(let{messageId:R,fingerprint:De,bubble:We}of Oe){let Je=i.querySelector(`#wrapper-${R}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),lr.set(R,De))}if(lr.size>0)for(let R of lr.keys())F.has(R)||lr.delete(R)},Ds=(i,p,f)=>{sf(i,p,f),no()},Ns=null,af=()=>{var f;if(Ns)return;let i=b=>{let C=b.composedPath();C.includes(me)||lt&&C.includes(lt)||$t(!1,"user")};Ns=i,((f=n.ownerDocument)!=null?f:document).addEventListener("pointerdown",i,!0)},$l=()=>{var p;if(!Ns)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("pointerdown",Ns,!0),Ns=null};ct.push(()=>$l());let Fs=null,lf=()=>{var f;if(Fs)return;let i=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};Fs=i,((f=n.ownerDocument)!=null?f:document).addEventListener("keydown",i,!0)},Ul=()=>{var p;if(!Fs)return;((p=n.ownerDocument)!=null?p:document).removeEventListener("keydown",Fs,!0),Fs=null};ct.push(()=>Ul());let Os=!1,ql=new Set,cf=()=>{var p,f,b,C;let i=(b=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.peek)==null?void 0:b.streamAnimation;return i||((C=r.features)==null?void 0:C.streamAnimation)},rs=()=>{var mt,at,Be,Re;if(!k())return;let i=Ve.peekBanner,p=Ve.peekTextNode;if(!i||!p)return;if(O){i.classList.remove("persona-pill-peek--visible");return}let f=(mt=$==null?void 0:$.getMessages())!=null?mt:[],b;for(let je=f.length-1;je>=0;je--){let Qe=f[je];if(Qe.role==="assistant"&&Qe.content){b=Qe;break}}if(!b){i.classList.remove("persona-pill-peek--visible");return}let C=b.content,L=!!b.streaming,q=cf(),F=ei(q),N=F.type!=="none"?Ss(F.type,q==null?void 0:q.plugins):null,ae=((at=N==null?void 0:N.isAnimating)==null?void 0:at.call(N,b))===!0,se=N!==null&&(L||ae);se&&N&&!ql.has(N.name)&&(ri(N,n),ql.add(N.name));let te=se&&(N!=null&&N.containerClass)?N.containerClass:null,we=(Be=p.dataset.personaPeekStreamClass)!=null?Be:null;we&&we!==te&&(p.classList.remove(we),delete p.dataset.personaPeekStreamClass),te&&we!==te&&(p.classList.add(te),p.dataset.personaPeekStreamClass=te),se?(p.style.setProperty("--persona-stream-step",`${F.speed}ms`),p.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Fe=se?ti(C,F.buffer,N,b,L):C;if(se&&F.placeholder==="skeleton"&&L&&(!Fe||!Fe.trim())){let je=document.createElement("div"),Qe=la();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),Qa(p,je)}else{let je=Math.max(0,Fe.length-100),Qe=Fe.length>100?Fe.slice(-100):Fe,vt=ho(Qe);if(!se||!N){let R=Fe.length>100?`\u2026${Qe}`:Qe;p.textContent!==R&&(p.textContent=R)}else{let R=vt;(N.wrap==="char"||N.wrap==="word")&&(R=ia(vt,N.wrap,`peek-${b.id}`,{skipTags:N.skipTags,startIndex:je}));let De=document.createElement("div");if(De.innerHTML=R,N.useCaret&&Qe.length>0){let We=ni(),Je=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),It=Je[Je.length-1];It!=null&&It.parentNode?It.parentNode.insertBefore(We,It.nextSibling):De.appendChild(We)}Qa(p,De),(Re=N.onAfterRender)==null||Re.call(N,{container:p,bubble:i,messageId:b.id,message:b,speed:F.speed,duration:F.duration})}}let ze=Jn||Os;i.classList.toggle("persona-pill-peek--visible",ze)};if(k()){let i=Ve.peekBanner;if(i){let b=C=>{C.preventDefault(),C.stopPropagation(),$t(!0,"user")};i.addEventListener("pointerdown",b),ct.push(()=>{i.removeEventListener("pointerdown",b)})}let p=()=>{Os||(Os=!0,rs())},f=()=>{Os&&(Os=!1,rs())};X.addEventListener("pointerenter",p),X.addEventListener("pointerleave",f),ct.push(()=>{X.removeEventListener("pointerenter",p),X.removeEventListener("pointerleave",f)}),lt&&(lt.addEventListener("pointerenter",p),lt.addEventListener("pointerleave",f),ct.push(()=>{lt.removeEventListener("pointerenter",p),lt.removeEventListener("pointerleave",f)}))}let df=i=>{var we,Fe,Oe,Ue,ze,mt,at,Be;let p=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},f=(Oe=p.expandedSize)!=null?Oe:"anchored",b=(Ue=p.bottomOffset)!=null?Ue:"16px",C=p.collapsedMaxWidth,L=(ze=p.expandedMaxWidth)!=null?ze:"880px",q=(mt=p.expandedTopOffset)!=null?mt:"5vh",F=(at=p.modalMaxWidth)!=null?at:"880px",N=(Be=p.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",te=me.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",lt){let Re=lt.style;Re.bottom=b,Re.width=C!=null?C:""}if(i&&f!=="fullscreen"){if(f==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=F,te.maxWidth=ae,te.maxHeight=N,te.height=N;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${b} + ${se})`,te.top=q,te.width=L,te.maxWidth=ae}},_s=()=>{var N,ae,se,te,we,Fe,Oe,Ue;if(!_())return;if(k()){let mt=(se=((ae=(N=r.launcher)==null?void 0:N.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",at=O?"expanded":"collapsed";me.dataset.state=at,me.dataset.expandedSize=mt,lt&&(lt.dataset.state=at,lt.dataset.expandedSize=mt),me.style.removeProperty("display"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),df(O),Ee.style.display=O?"flex":"none",oo(),O?(af(),lf()):($l(),Ul()),rs();return}let i=hn(r),p=(te=n.ownerDocument.defaultView)!=null?te:window,f=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(Ue=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ue:!0,C=p.innerWidth<=f,L=b&&C&&H,q=mr(r).reveal;O?(me.style.removeProperty("display"),me.style.display=i?"flex":"",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":sn&&(sn.style.display="none")):(i?i&&(q==="overlay"||q==="push")&&!L?(me.style.removeProperty("display"),me.style.display="flex",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.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"),X.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"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=i?"none":"":sn&&(sn.style.display=i?"none":""))},$t=(i,p="user")=>{var L,q;if(!_()||O===i)return;let f=O;O=i,_s();let b=(()=>{var Oe,Ue,ze,mt,at,Be,Re,je,Qe,vt;let F=(Ue=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?Ue:!1,N=(ze=n.ownerDocument.defaultView)!=null?ze:window,ae=(at=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?at:!0,se=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,te=N.innerWidth<=se,we=hn(r)&&ae&&te,Fe=k()&&((vt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return F||ae&&te&&H||we||Fe})();if(O&&b){if(!nn){let F=n.getRootNode(),N=F instanceof ShadowRoot?F.host:n.closest(".persona-host");N&&(nn=ol(N,(q=(L=r.launcher)==null?void 0:L.zIndex)!=null?q:xn))}rn||(rn=sl(n.ownerDocument))}else O||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);O&&($s(),Ol()||(Ot()==="follow"?co(!0):Nl()));let C={open:O,source:p,timestamp:Date.now()};O&&!f?l.emit("widget:opened",C):!O&&f&&l.emit("widget:closed",C),l.emit("widget:state",{open:O,launcherEnabled:H,voiceActive:G.active,streaming:$.isStreaming()})},Si=i=>{fe(i?"stop":"send"),D&&(D.disabled=i),Lo.buttons.forEach(p=>{p.disabled=i}),He.dataset.personaComposerStreaming=i?"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=i)})},Ti=()=>{G.active||be&&be.focus()};l.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ti(),200)});let zl=()=>{var f,b,C,L,q,F,N,ae,se,te,we;fr.textContent=(b=(f=r.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}",hr.textContent=(L=(C=r.copy)==null?void 0:C.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",be.placeholder=(F=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?F:"How can I help...";let i=xe.querySelector("[data-persona-intro-card]");if(i){let Fe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;i.style.display=Fe?"":"none",Fe?(xe.classList.remove("persona-gap-3"),xe.classList.add("persona-gap-6")):(xe.classList.remove("persona-gap-6"),xe.classList.add("persona-gap-3"))}!((se=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!($!=null&&$.isStreaming())&&(ue.textContent=(we=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?we:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{w(p=>({...p,sessionId:i}))}});let Ro=null,pf=()=>{Ro==null&&(Ro=setInterval(()=>{let i=Ze.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Ro),Ro=null;return}let p=Date.now();i.forEach(f=>{let b=Number(f.getAttribute("data-tool-elapsed"));b&&(f.textContent=Da(p-b))})},100))},Ei=(i,p)=>{if(Object.is(i,p))return!0;if(i===null||p===null||typeof i!="object"||typeof p!="object")return!1;if(Array.isArray(i)||Array.isArray(p))return!Array.isArray(i)||!Array.isArray(p)||i.length!==p.length?!1:i.every((q,F)=>Ei(q,p[F]));let f=i,b=p,C=Object.keys(f),L=Object.keys(b);return C.length===L.length&&C.every(q=>Object.prototype.hasOwnProperty.call(b,q)&&Ei(f[q],b[q]))},jl=i=>{let{content:p,rawContent:f,llmContent:b,...C}=i;return C},Mi=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!El(i),uf=(i,p,f)=>{if(i.length!==p.length)return!1;let b=i[f.index],C=p[f.index];return!b||!C||b.id!==f.id||C.id!==f.id?!1:(!Object.is(b.content,C.content)||!Object.is(b.rawContent,C.rawContent)||!Object.is(b.llmContent,C.llmContent))&&Mi(b)&&Mi(C)&&Ei(jl(b),jl(C))},Vl=null,os=null,Ur=null,qr=null,wa=i=>{var C,L;Vl=i;let p,f;os=null;for(let q=i.length-1;q>=0;q-=1){let F=i[q];if(!p&&F.role==="user"&&(p=F),!f&&F.role==="assistant"&&(f=F),!os&&Mi(F)&&(os={index:q,id:F.id}),p&&f&&os)break}Ds(Ze,i,ee),pf(),Zo(i),co(!Jn),of(i),i.length===0&&(Bs(),so=!0,ao=!1),!ts||Io?(ts=!0,ns=(C=p==null?void 0:p.id)!=null?C:null,st=(L=f==null?void 0:f.id)!=null?L:null):p&&p.id!==ns?(ns=p.id,nf(p.id)):f&&f.id!==st&&rf(),f&&(st=f.id);let b=G.lastUserMessageId;p&&p.id!==b&&(G.lastUserMessageId=p.id,l.emit("user:message",p)),G.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),kr(i),rs()},ki=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null);let i=Ur;Ur=null,i&&wa(i)},Kl=()=>{qr!==null&&cancelAnimationFrame(qr),qr=null,Ur=null},mf=i=>{let p=Ur!=null?Ur:Vl;if(Jn&&p&&os&&uf(p,i,os)){Ur=i,qr===null&&(qr=requestAnimationFrame(()=>{qr=null;let f=Ur;Ur=null,f&&wa(f)}));return}if(i.length===0){Kl(),wa(i);return}ki(),wa(i)};$=new Va(r,{onMessagesChanged(i){mf(i)},onStatusChanged(i){var b;let p=(b=r.statusIndicator)!=null?b:{};ht(yn,(C=>{var L,q,F,N,ae,se;return C==="idle"?(L=p.idleText)!=null?L:tn.idle:C==="connecting"?(q=p.connectingText)!=null?q:tn.connecting:C==="connected"?(F=p.connectedText)!=null?F:tn.connected:C==="error"?(N=p.errorText)!=null?N:tn.error:C==="paused"?(ae=p.pausedText)!=null?ae:tn.paused:C==="resuming"?(se=p.resumingText)!=null?se:tn.resuming:tn[C]})(i),p,i)},onStreamingChanged(i){i||(($==null?void 0:$.getMessages().length)===0?Kl():ki()),Jn=i,Si(i),$&&Ds(Ze,$.getMessages(),ee),i||co(!0),_n(),Jr(i?"Responding\u2026":"Response complete."),rs()},onVoiceStatusChanged(i){var p,f;if(l.emit("voice:status",{status:i,timestamp:Date.now()}),((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype")switch(i){case"listening":zr(),as();break;case"processing":zr(),bf();break;case"speaking":zr(),vf();break;default:i==="idle"&&$.isBargeInActive()?(zr(),as(),D==null||D.setAttribute("aria-label","End voice session")):(G.active=!1,zr(),rt("system"),dt());break}},onArtifactsState(i){Fn=i,Cr(),kr()},onReconnect(i){var b;let{executionId:p,lastEventId:f}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:p,after:f}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:p,after:f,attempt:(b=i.attempt)!=null?b:1}):l.emit("stream:resumed",{executionId:p,after:f})}}),Tt.current=$,ct.push(()=>$.cancel());let Li=null;if($.onReadAloudChange((i,p)=>{var C;eo=i,to=p,no();let f=i!=null?i:Li;i&&(Li=i);let b=f&&(C=$.getMessages().find(L=>L.id===f))!=null?C:null;l.emit("message:read-aloud",{messageId:f,message:b,state:p,timestamp:Date.now()}),p==="idle"&&(Li=null)}),ts=!0,((id=(ad=r.voiceRecognition)==null?void 0:ad.provider)==null?void 0:id.type)==="runtype")try{$.setupVoice()}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}r.clientToken&&$.initClientSession().catch(i=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(K||r.onSSEEvent)&&$.setSSEEventCallback((i,p)=>{var f;(f=r.onSSEEvent)==null||f.call(r,i,p),J==null||J.processEvent(i,p),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(p)})});let Gl=()=>{r.resume&&typeof r.reconnectStream=="function"&&$.resumeFromHandle(r.resume)};g?g.then(i=>{var p,f,b;if(i){if(i.metadata&&(u=Ml(i.metadata),E.syncFromMetadata()),(p=i.messages)!=null&&p.length){Io=!0;try{$.hydrateMessages(i.messages)}finally{Io=!1}}(f=i.artifacts)!=null&&f.length&&$.hydrateArtifacts(i.artifacts,(b=i.selectedArtifactId)!=null?b:null)}}).catch(i=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>Gl()):Gl();let Ql=()=>{var p,f,b;!k()||O||!((b=(f=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:f.expandOnSubmit)==null||b)||$t(!0,"auto")},Xl=i=>{var C;if(i.preventDefault(),$.isStreaming()){$.cancel(),J==null||J.reset(),Se==null||Se.update();return}let p=be.value.trim(),f=(C=St==null?void 0:St.hasAttachments())!=null?C:!1;if(!p&&!f)return;Ql();let b;f&&(b=[],b.push(...St.getContentParts()),p&&b.push(Qi(p))),be.value="",be.style.height="auto",xa(),$.sendMessage(p,{contentParts:b}),f&&St.clearAttachments()},gf=()=>{var i;return((i=r.features)==null?void 0:i.composerHistory)!==!1},Pi={...Xa},Ii=!1,xa=()=>{Pi={...Xa}},ff=()=>$.getMessages().filter(i=>i.role==="user").map(i=>{var p;return(p=i.content)!=null?p:""}).filter(i=>i.length>0),hf=i=>{if(!be)return;Ii=!0,be.value=i,be.dispatchEvent(new Event("input",{bubbles:!0})),Ii=!1;let p=be.value.length;be.setSelectionRange(p,p)},Jl=()=>{Ii||xa()},Yl=i=>{if(be){if(gf()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let p=be.selectionStart===0&&be.selectionEnd===0,f=Fm({direction:i.key==="ArrowUp"?"up":"down",history:ff(),currentValue:be.value,atStart:p,state:Pi});if(Pi=f.state,f.handled){i.preventDefault(),f.value!==void 0&&hf(f.value);return}}if(i.key==="Enter"&&!i.shiftKey){if($.isStreaming()){i.preventDefault();return}xa(),i.preventDefault(),ue.click()}}},Zl=i=>{i.key!=="Escape"||i.isComposing||$.isStreaming()&&i.composedPath().includes(Ee)&&($.cancel(),J==null||J.reset(),Se==null||Se.update(),xa(),i.preventDefault(),i.stopImmediatePropagation())},ec=async i=>{var f;if(((f=r.attachments)==null?void 0:f.enabled)!==!0||!St)return;let p=Ib(i.clipboardData);p.length!==0&&(i.preventDefault(),await St.handleFiles(p))},Yn=null,Lr=!1,ss=null,ut=null,tc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ca=(i="user")=>{var L,q,F,N,ae,se,te;if(Lr||$.isStreaming())return;let p=tc();if(!p)return;Yn=new p;let b=(q=((L=r.voiceRecognition)!=null?L:{}).pauseDuration)!=null?q:2e3;Yn.continuous=!0,Yn.interimResults=!0,Yn.lang="en-US";let C=be.value;Yn.onresult=we=>{let Fe="",Oe="";for(let ze=0;ze<we.results.length;ze++){let mt=we.results[ze],at=mt[0].transcript;mt.isFinal?Fe+=at+" ":Oe=at}let Ue=C+Fe+Oe;be.value=Ue,ss&&clearTimeout(ss),(Fe||Oe)&&(ss=window.setTimeout(()=>{let ze=be.value.trim();ze&&Yn&&Lr&&(po(),be.value="",be.style.height="auto",$.sendMessage(ze,{viaVoice:!0}))},b))},Yn.onerror=we=>{we.error!=="no-speech"&&po()},Yn.onend=()=>{if(Lr){let we=be.value.trim();we&&we!==C.trim()&&(be.value="",be.style.height="auto",$.sendMessage(we,{viaVoice:!0})),po()}};try{if(Yn.start(),Lr=!0,G.active=!0,i!=="system"&&(G.manuallyDeactivated=!1),rt(i),dt(),D){let we=(F=r.voiceRecognition)!=null?F:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((te=(se=we.iconSize)!=null?se:(ae=r.sendButton)==null?void 0:ae.size)!=null?te:"40")||24};let Fe=we.recordingBackgroundColor,Oe=we.recordingIconColor,Ue=we.recordingBorderColor;if(D.classList.add("persona-voice-recording"),D.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let ze=D.querySelector("svg");ze&&ze.setAttribute("stroke",Oe)}Ue&&(D.style.borderColor=Ue),D.setAttribute("aria-label","Stop voice recognition")}}catch{po("system")}},po=(i="user")=>{if(Lr){if(Lr=!1,ss&&(clearTimeout(ss),ss=null),Yn){try{Yn.stop()}catch{}Yn=null}if(G.active=!1,rt(i),dt(),D){if(D.classList.remove("persona-voice-recording"),ut){D.style.backgroundColor=ut.backgroundColor,D.style.color=ut.color,D.style.borderColor=ut.borderColor;let p=D.querySelector("svg");p&&p.setAttribute("stroke",ut.color||"currentColor"),ut=null}D.setAttribute("aria-label","Start voice recognition")}}},yf=(i,p)=>{var at,Be,Re,je,Qe,vt,R,De,We;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((at=i==null?void 0:i.provider)==null?void 0:at.type)==="runtype",C=((Be=i==null?void 0:i.provider)==null?void 0:Be.type)==="custom";if(!(f||b||C))return null;let q=v("div","persona-send-button-wrapper"),F=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let N=(Re=i==null?void 0:i.iconName)!=null?Re:"mic",ae=(je=p==null?void 0:p.size)!=null?je:"40px",se=(Qe=i==null?void 0:i.iconSize)!=null?Qe:ae,te=parseFloat(se)||24,we=(vt=i==null?void 0:i.backgroundColor)!=null?vt:p==null?void 0:p.backgroundColor,Fe=(R=i==null?void 0:i.iconColor)!=null?R:p==null?void 0:p.textColor;F.style.width=se,F.style.height=se,F.style.minWidth=se,F.style.minHeight=se,F.style.fontSize="18px",F.style.lineHeight="1",Fe?F.style.color=Fe:F.style.color="var(--persona-text, #111827)";let Ue=ye(N,te,Fe||"currentColor",1.5);Ue?F.appendChild(Ue):F.textContent="\u{1F3A4}",we?F.style.backgroundColor=we:F.style.backgroundColor="",i!=null&&i.borderWidth&&(F.style.borderWidth=i.borderWidth,F.style.borderStyle="solid"),i!=null&&i.borderColor&&(F.style.borderColor=i.borderColor),i!=null&&i.paddingX&&(F.style.paddingLeft=i.paddingX,F.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(F.style.paddingTop=i.paddingY,F.style.paddingBottom=i.paddingY),q.appendChild(F);let ze=(De=i==null?void 0:i.tooltipText)!=null?De:"Start voice recognition";if(((We=i==null?void 0:i.showTooltip)!=null?We:!1)&&ze){let Je=v("div","persona-send-button-tooltip");Je.textContent=ze,q.appendChild(Je)}return{micButton:F,micButtonWrapper:q}},Ri=()=>{var p,f,b,C,L;if(!D||ut)return;let i=(p=r.voiceRecognition)!=null?p:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(f=i.iconName)!=null?f:"mic",iconSize:parseFloat((L=(C=i.iconSize)!=null?C:(b=r.sendButton)==null?void 0:b.size)!=null?L:"40")||24}},Wi=(i,p)=>{var L,q,F,N,ae;if(!D)return;let f=D.querySelector("svg");f&&f.remove();let b=(ae=ut==null?void 0:ut.iconSize)!=null?ae:parseFloat((N=(F=(L=r.voiceRecognition)==null?void 0:L.iconSize)!=null?F:(q=r.sendButton)==null?void 0:q.size)!=null?N:"40")||24,C=ye(i,b,p,1.5);C&&D.appendChild(C)},Aa=()=>{D&&D.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},as=()=>{var C;if(!D)return;Ri();let i=(C=r.voiceRecognition)!=null?C:{},p=i.recordingBackgroundColor,f=i.recordingIconColor,b=i.recordingBorderColor;if(Aa(),D.classList.add("persona-voice-recording"),D.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=f!=null?f:"var(--persona-voice-recording-indicator, #ffffff)",f){let L=D.querySelector("svg");L&&L.setAttribute("stroke",f)}b&&(D.style.borderColor=b),D.setAttribute("aria-label","Stop voice recognition")},bf=()=>{var F,N,ae,se,te,we,Fe,Oe;if(!D)return;Ri();let i=(F=r.voiceRecognition)!=null?F:{},p=$.getVoiceInterruptionMode(),f=(N=i.processingIconName)!=null?N:"loader",b=(se=(ae=i.processingIconColor)!=null?ae:ut==null?void 0:ut.color)!=null?se:"",C=(we=(te=i.processingBackgroundColor)!=null?te:ut==null?void 0:ut.backgroundColor)!=null?we:"",L=(Oe=(Fe=i.processingBorderColor)!=null?Fe:ut==null?void 0:ut.borderColor)!=null?Oe:"";Aa(),D.classList.add("persona-voice-processing"),D.style.backgroundColor=C,D.style.borderColor=L;let q=b||"currentColor";D.style.color=q,Wi(f,q),D.setAttribute("aria-label","Processing voice input"),p==="none"&&(D.style.cursor="default")},vf=()=>{var ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re;if(!D)return;Ri();let i=(ae=r.voiceRecognition)!=null?ae:{},p=$.getVoiceInterruptionMode(),f=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",b=(se=i.speakingIconName)!=null?se:f,C=(Oe=i.speakingIconColor)!=null?Oe:p==="barge-in"?(we=(te=i.recordingIconColor)!=null?te:ut==null?void 0:ut.color)!=null?we:"":(Fe=ut==null?void 0:ut.color)!=null?Fe:"",L=(mt=i.speakingBackgroundColor)!=null?mt:p==="barge-in"?(Ue=i.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=ut==null?void 0:ut.backgroundColor)!=null?ze:"",q=(Re=i.speakingBorderColor)!=null?Re:p==="barge-in"?(at=i.recordingBorderColor)!=null?at:"":(Be=ut==null?void 0:ut.borderColor)!=null?Be:"";Aa(),D.classList.add("persona-voice-speaking"),D.style.backgroundColor=L,D.style.borderColor=q;let F=C||"currentColor";D.style.color=F,Wi(b,F);let N=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";D.setAttribute("aria-label",N),p==="none"&&(D.style.cursor="default"),p==="barge-in"&&D.classList.add("persona-voice-recording")},zr=()=>{var i,p,f;D&&(Aa(),ut&&(D.style.backgroundColor=(i=ut.backgroundColor)!=null?i:"",D.style.color=(p=ut.color)!=null?p:"",D.style.borderColor=(f=ut.borderColor)!=null?f:"",Wi(ut.iconName,ut.color||"currentColor"),ut=null),D.style.cursor="",D.setAttribute("aria-label","Start voice recognition"))},Sa=()=>{var i,p;if(((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"){let f=$.getVoiceStatus(),b=$.getVoiceInterruptionMode();if(b==="none"&&(f==="processing"||f==="speaking"))return;if(b==="cancel"&&(f==="processing"||f==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),rt("user"),zr()});return}$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),G.manuallyDeactivated=!$.isVoiceActive(),dt(),rt("user"),$.isVoiceActive()?as():zr()});return}if(Lr){let f=be.value.trim();G.manuallyDeactivated=!0,dt(),po("user"),f&&(be.value="",be.style.height="auto",$.sendMessage(f))}else G.manuallyDeactivated=!1,dt(),Ca("user")};vr=Sa,D&&(D.addEventListener("click",Sa),ct.push(()=>{var i,p;((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),zr()):po("system"),D&&D.removeEventListener("click",Sa)}));let wf=l.on("assistant:complete",()=>{Ne&&(G.active||G.manuallyDeactivated||Ne==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var i,p;!G.active&&!G.manuallyDeactivated&&(((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("auto"),$.isVoiceActive()&&as()}):Ca("auto"))},600))});ct.push(wf);let xf=l.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ct.push(xf);let nc=()=>{$t(!O,"user")},Yt=null,sn=null;if(H&&!k()){let{instance:i,element:p}=ll({config:r,plugins:o,onToggle:nc});Yt=i,i||(sn=p)}Yt?n.appendChild(Yt.element):sn&&n.appendChild(sn),_s(),Zo(),zl(),Si($.isStreaming()),Ol()||(Ot()==="follow"?co(!0):Nl()),xi(),I&&(!H||k()?setTimeout(()=>Ti(),0):O&&setTimeout(()=>Ti(),200));let $s=()=>{var N,ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re,je,Qe,vt,R,De,We,Je,It,_e;if(k()){Vn(),_s();return}let i=hn(r),p=(ae=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,f=i||p||((te=(se=r.launcher)==null?void 0:se.fullHeight)!=null?te:!1),b=(we=n.ownerDocument.defaultView)!=null?we:window,C=(Oe=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Oe:!0,L=(ze=(Ue=r.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,q=b.innerWidth<=L,F=C&&q&&H;try{if(F){oo(),As(n,r);return}if(U&&(U=!1,oo(),As(n,r)),!H&&!i){X.style.height="",X.style.width="";return}if(!p&&!i){let Gt=(at=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?at:r==null?void 0:r.launcherWidth,Ct=Gt!=null?Gt:Qr;X.style.width=Ct,X.style.maxWidth=Ct}if(ko(),!f){let Gt=b.innerHeight,Ct=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Wn=Math.max(200,Gt-Ct),Dt=Math.min(640,Wn),gn=Math.max(200,Dt-an);X.style.height=`${gn}px`}}finally{if(Vn(),_s(),O&&H){let Ct=((je=n.ownerDocument.defaultView)!=null?je:window).innerWidth<=((vt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),an=(De=(R=r.launcher)==null?void 0:R.sidebarMode)!=null?De:!1,Wn=(Je=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Je:!0,Dt=hn(r)&&Wn&&Ct,gn=an||Wn&&Ct&&H||Dt;if(gn&&!rn){let $n=n.getRootNode(),Ke=$n instanceof ShadowRoot?$n.host:n.closest(".persona-host");Ke&&!nn&&(nn=ol(Ke,(_e=(It=r.launcher)==null?void 0:It.zIndex)!=null?_e:xn)),rn=sl(n.ownerDocument)}else gn||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};$s();let rc=(ld=n.ownerDocument.defaultView)!=null?ld:window;if(rc.addEventListener("resize",$s),ct.push(()=>rc.removeEventListener("resize",$s)),typeof ResizeObserver!="undefined"){let i=new ResizeObserver(()=>{Vn()});i.observe(He),ct.push(()=>i.disconnect())}Tn=xe.scrollTop;let oc=Rr(xe),Cf=()=>{let i=xe.getRootNode(),p=typeof i.getSelection=="function"?i.getSelection():null;return p!=null?p:xe.ownerDocument.getSelection()},Hi=()=>zm(Cf(),xe),sc=()=>{let i=xe.scrollTop,p=Rr(xe),f=p<oc;if(oc=p,!Zt()){Tn=i,_n();return}let{action:b,nextLastScrollTop:C}=Ya({following:bn.isFollowing(),currentScrollTop:i,lastScrollTop:Tn,nearBottom:xo(xe,V),userScrollThreshold:x,isAutoScrolling:En||Po||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Tn=C,b==="resume"){Hi()||lo();return}b==="pause"&&Hs()};if(xe.addEventListener("scroll",sc,{passive:!0}),ct.push(()=>xe.removeEventListener("scroll",sc)),typeof ResizeObserver!="undefined"){let i=new ResizeObserver(()=>{tf()});i.observe(Ze),i.observe(xe),ct.push(()=>i.disconnect())}let ac=()=>{Zt()&&bn.isFollowing()&&Hi()&&Hs()},ic=xe.ownerDocument;ic.addEventListener("selectionchange",ac),ct.push(()=>{ic.removeEventListener("selectionchange",ac)});let Af=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),lc=i=>{rr()&&Zt()&&bn.isFollowing()&&Af.has(i.key)&&Hs()},cc=i=>{if(!rr()||!Zt()||!bn.isFollowing())return;let p=i.target;p&&p.closest("a, button, [tabindex], input, textarea, select")&&Hs()};xe.addEventListener("keydown",lc),xe.addEventListener("focusin",cc),ct.push(()=>{xe.removeEventListener("keydown",lc),xe.removeEventListener("focusin",cc)});let dc=i=>{if(!Zt())return;let p=Za({following:bn.isFollowing(),deltaY:i.deltaY,nearBottom:xo(xe,V),resumeWhenNearBottom:!0});p==="pause"?Hs():p==="resume"&&!Hi()&&lo()};xe.addEventListener("wheel",dc,{passive:!0}),ct.push(()=>xe.removeEventListener("wheel",dc)),Vt.addEventListener("click",()=>{Bs(),xe.scrollTop=xe.scrollHeight,Tn=xe.scrollTop,lo(),co(!0),_n()}),ct.push(()=>Vt.remove()),ct.push(()=>{Hl(),Bs()});let pc=()=>{qe&&(Sr&&(qe.removeEventListener("click",Sr),Sr=null),_()?(qe.style.display="",Sr=()=>{$t(!1,"user")},qe.addEventListener("click",Sr)):qe.style.display="none")};pc(),(()=>{let{clearChatButton:i}=Ve;i&&i.addEventListener("click",()=>{$.clearMessages(),Tr.clear(),lo(),hs(Ve.composerOverlay);try{localStorage.removeItem(Ls),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ls}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ls)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(p),c!=null&&c.clear&&$r(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.update()})})(),At&&At.addEventListener("submit",Xl),be==null||be.addEventListener("keydown",Yl),be==null||be.addEventListener("input",Jl),be==null||be.addEventListener("paste",ec);let uc=(cd=n.ownerDocument)!=null?cd:document;uc.addEventListener("keydown",Zl,!0);let mc="persona-attachment-drop-active",Us=0,Bi=()=>{Us=0,Ee.classList.remove(mc)},is=()=>{var i;return((i=r.attachments)==null?void 0:i.enabled)===!0&&St!==null},gc=i=>{!vi(i.dataTransfer)||!is()||(Us++,Us===1&&Ee.classList.add(mc))},fc=i=>{!vi(i.dataTransfer)||!is()||(Us--,Us<=0&&Bi())},hc=i=>{!vi(i.dataTransfer)||!is()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},yc=i=>{var f;if(!vi(i.dataTransfer)||!is())return;i.preventDefault(),i.stopPropagation(),Bi();let p=Array.from((f=i.dataTransfer.files)!=null?f:[]);p.length!==0&&St.handleFiles(p)},uo=!0;Ee.addEventListener("dragenter",gc,uo),Ee.addEventListener("dragleave",fc,uo),n.addEventListener("dragover",hc,uo),n.addEventListener("drop",yc,uo);let Ta=n.ownerDocument,bc=i=>{is()&&i.preventDefault()},vc=i=>{is()&&i.preventDefault()};Ta.addEventListener("dragover",bc),Ta.addEventListener("drop",vc),ct.push(()=>{At&&At.removeEventListener("submit",Xl),be==null||be.removeEventListener("keydown",Yl),be==null||be.removeEventListener("input",Jl),be==null||be.removeEventListener("paste",ec),uc.removeEventListener("keydown",Zl,!0)}),ct.push(()=>{Ee.removeEventListener("dragenter",gc,uo),Ee.removeEventListener("dragleave",fc,uo),n.removeEventListener("dragover",hc,uo),n.removeEventListener("drop",yc,uo),Ta.removeEventListener("dragover",bc),Ta.removeEventListener("drop",vc),Bi()}),ct.push(()=>{$.cancel()}),Yt?ct.push(()=>{Yt==null||Yt.destroy()}):sn&&ct.push(()=>{sn==null||sn.remove()});let en={update(i){var qn,Pr,pn,un,er,fo,hd,yd,bd,vd,wd,xd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,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,wp,xp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,Up,qp,zp,jp,Vp,Kp,Gp,Qp,Xp,Jp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,vu,wu,xu,Cu;let p=r.toolCall,f=r.messageActions,b=(qn=r.layout)==null?void 0:qn.messages,C=r.colorScheme,L=r.loadingIndicator,q=r.iterationDisplay,F=(Pr=r.features)==null?void 0:Pr.showReasoning,N=(pn=r.features)==null?void 0:pn.showToolCalls,ae=(un=r.features)==null?void 0:un.toolCallDisplay,se=(er=r.features)==null?void 0:er.reasoningDisplay,te=(hd=(fo=r.features)==null?void 0:fo.streamAnimation)==null?void 0:hd.type;r={...r,...i},oo(),As(n,r),yi(n,r),bi(n,r),Cr(),r.colorScheme!==C&&Ws();let we=xl.getForInstance(r.plugins);o.length=0,o.push(...we),H=(bd=(yd=r.launcher)==null?void 0:yd.enabled)!=null?bd:!0,B=(wd=(vd=r.launcher)==null?void 0:vd.autoExpand)!=null?wd:!1,Pe=(Cd=(xd=r.features)==null?void 0:xd.showReasoning)!=null?Cd:!0,Ie=(Sd=(Ad=r.features)==null?void 0:Ad.showToolCalls)!=null?Sd:!0,he=(Ed=(Td=r.features)==null?void 0:Td.scrollToBottom)!=null?Ed:{};let Fe=Ot();re=(kd=(Md=r.features)==null?void 0:Md.scrollBehavior)!=null?kd:{},Fe!==Ot()&&(Bs(),lo()),Yr(),_n();let Oe=ie;if(ie=(Pd=(Ld=r.features)==null?void 0:Ld.showEventStreamToggle)!=null?Pd:!1,ie&&!Oe){if(K||(Ae=new fa(de),K=new ga($e,Ae),J=J!=null?J:new ha,Ae.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),$.setSSEEventCallback((ne,Et)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ne,Et),J==null||J.processEvent(ne,Et),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!bt&&Le){let ne=(Rd=(Id=r.features)==null?void 0:Id.eventStream)==null?void 0:Rd.classNames,Et="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=v("button",Et),bt.style.width="28px",bt.style.height="28px",bt.style.color=Pn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let zt=ye("activity","18px","currentColor",1.5);zt&&bt.appendChild(zt);let it=Ve.clearChatButtonWrapper,Lt=Ve.closeButtonWrapper,ln=it||Lt;ln&&ln.parentNode===Le?Le.insertBefore(bt,ln):Le.appendChild(bt),bt.addEventListener("click",()=>{Y?ir():Br()})}}else!ie&&Oe&&(ir(),bt&&(bt.remove(),bt=null),K==null||K.clear(),Ae==null||Ae.destroy(),K=null,Ae=null,J==null||J.reset(),J=null);if(((Wd=r.launcher)==null?void 0:Wd.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((Hd=r.launcher)==null?void 0:Hd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Bd=r.launcher)==null?void 0:Bd.enabled)!==!1&&!Yt&&!sn){let{instance:ne,element:Et}=ll({config:r,plugins:o,onToggle:nc});Yt=ne,ne||(sn=Et),n.appendChild(Et)}Yt&&Yt.update(r),ge&&((Dd=r.launcher)==null?void 0:Dd.title)!==void 0&&(ge.textContent=r.launcher.title),Me&&((Nd=r.launcher)==null?void 0:Nd.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let Ue=(Fd=r.layout)==null?void 0:Fd.header;if((Ue==null?void 0:Ue.layout)!==z&&Le){let ne=Ue?ai(r,Ue,{showClose:_(),onClose:()=>$t(!1,"user")}):Vo({config:r,showClose:_(),onClose:()=>$t(!1,"user")});ot.replaceHeader(ne),Le=ot.header.element,M=ot.header.iconHolder,ge=ot.header.headerTitle,Me=ot.header.headerSubtitle,qe=ot.header.closeButton,z=Ue==null?void 0:Ue.layout}else if(Ue&&(M&&(M.style.display=Ue.showIcon===!1?"none":""),ge&&(ge.style.display=Ue.showTitle===!1?"none":""),Me&&(Me.style.display=Ue.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ue.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let ne=Ue.showClearChat;if(ne!==void 0){Ve.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Et}=Ve;Et&&!Et.classList.contains("persona-absolute")&&(ne?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let mt=((Od=r.layout)==null?void 0:Od.showHeader)!==!1;Le&&(Le.style.display=mt?"":"none");let at=((_d=r.layout)==null?void 0:_d.showFooter)!==!1;He&&(He.style.display=at?"":"none"),Vn(),_n(),H!==P?H?$t(B,"auto"):(O=!0,_s()):B!==S&&$t(B,"auto"),S=B,P=H,$s(),pc();let je=JSON.stringify(i.toolCall)!==JSON.stringify(p),Qe=JSON.stringify(r.messageActions)!==JSON.stringify(f),vt=JSON.stringify(($d=r.layout)==null?void 0:$d.messages)!==JSON.stringify(b),R=((Ud=r.loadingIndicator)==null?void 0:Ud.render)!==(L==null?void 0:L.render)||((qd=r.loadingIndicator)==null?void 0:qd.renderIdle)!==(L==null?void 0:L.renderIdle)||((zd=r.loadingIndicator)==null?void 0:zd.showBubble)!==(L==null?void 0:L.showBubble),De=r.iterationDisplay!==q,We=((Vd=(jd=r.features)==null?void 0:jd.showReasoning)!=null?Vd:!0)!==(F!=null?F:!0)||((Gd=(Kd=r.features)==null?void 0:Kd.showToolCalls)!=null?Gd:!0)!==(N!=null?N:!0)||JSON.stringify((Qd=r.features)==null?void 0:Qd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((Xd=r.features)==null?void 0:Xd.reasoningDisplay)!==JSON.stringify(se);(je||Qe||vt||R||De||We)&&$&&(es++,Ds(Ze,$.getMessages(),ee));let It=(Yd=(Jd=r.features)==null?void 0:Jd.streamAnimation)==null?void 0:Yd.type;if(It!==te&&It&&It!=="none"){let ne=Ss(It,(ep=(Zd=r.features)==null?void 0:Zd.streamAnimation)==null?void 0:ep.plugins);ne&&ri(ne,n)}let _e=(tp=r.launcher)!=null?tp:{},Gt=(np=_e.headerIconHidden)!=null?np:!1,Ct=(op=(rp=r.layout)==null?void 0:rp.header)==null?void 0:op.showIcon,an=Gt||Ct===!1,Wn=_e.headerIconName,Dt=(sp=_e.headerIconSize)!=null?sp:"48px";if(M){let ne=Ee.querySelector(".persona-border-b-persona-divider"),Et=ne==null?void 0:ne.querySelector(".persona-flex-col");if(an)M.style.display="none",ne&&Et&&!ne.contains(Et)&&ne.insertBefore(Et,ne.firstChild);else{if(M.style.display="",M.style.height=Dt,M.style.width=Dt,ne&&Et&&(ne.contains(M)?M.nextSibling!==Et&&(M.remove(),ne.insertBefore(M,Et)):ne.insertBefore(M,Et)),Wn){let it=parseFloat(Dt)||24,Lt=ye(Wn,it*.6,"currentColor",1);Lt?M.replaceChildren(Lt):M.textContent=(ap=_e.agentIconText)!=null?ap:"\u{1F4AC}"}else if(_e.iconUrl){let it=M.querySelector("img");if(it)it.src=_e.iconUrl,it.style.height=Dt,it.style.width=Dt;else{let Lt=document.createElement("img");Lt.src=_e.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Dt,Lt.style.width=Dt,M.replaceChildren(Lt)}}else{let it=M.querySelector("svg"),Lt=M.querySelector("img");(it||Lt)&&M.replaceChildren(),M.textContent=(ip=_e.agentIconText)!=null?ip:"\u{1F4AC}"}let zt=M.querySelector("img");zt&&(zt.style.height=Dt,zt.style.width=Dt)}}let gn=(cp=(lp=r.layout)==null?void 0:lp.header)==null?void 0:cp.showTitle,$n=(pp=(dp=r.layout)==null?void 0:dp.header)==null?void 0:pp.showSubtitle;if(ge&&(ge.style.display=gn===!1?"none":""),Me&&(Me.style.display=$n===!1?"none":""),qe){((mp=(up=r.layout)==null?void 0:up.header)==null?void 0:mp.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Et=(gp=_e.closeButtonSize)!=null?gp:"32px",zt=(fp=_e.closeButtonPlacement)!=null?fp:"inline";qe.style.height=Et,qe.style.width=Et;let{closeButtonWrapper:it}=Ve,Lt=zt==="top-right",ln=it==null?void 0:it.classList.contains("persona-absolute");if(it&&Lt!==ln)if(it.remove(),Lt)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ee.style.position="relative",Ee.appendChild(it);else{let pt=(yp=(hp=_e.clearChat)==null?void 0:hp.placement)!=null?yp:"inline",cn=(vp=(bp=_e.clearChat)==null?void 0:bp.enabled)!=null?vp:!0;it.className=cn&&pt==="inline"?"":"persona-ml-auto";let Hn=Ee.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(it)}if(qe.style.color=_e.closeButtonColor||Pn.actionIconColor,_e.closeButtonBackgroundColor?(qe.style.backgroundColor=_e.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let pt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${cn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");_e.closeButtonBorderRadius?(qe.style.borderRadius=_e.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(qe.style.paddingLeft=_e.closeButtonPaddingX,qe.style.paddingRight=_e.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),_e.closeButtonPaddingY?(qe.style.paddingTop=_e.closeButtonPaddingY,qe.style.paddingBottom=_e.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let wn=(wp=_e.closeButtonIconName)!=null?wp:"x",pr=(xp=_e.closeButtonIconText)!=null?xp:"\xD7";qe.innerHTML="";let Ln=ye(wn,"28px","currentColor",1);Ln?qe.appendChild(Ln):qe.textContent=pr;let Jt=(Cp=_e.closeButtonTooltipText)!=null?Cp:"Close chat",zn=(Ap=_e.closeButtonShowTooltip)!=null?Ap:!0;if(qe.setAttribute("aria-label",Jt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),zn&&Jt)){let pt=null,cn=()=>{if(pt||!qe)return;let Oo=qe.ownerDocument,qs=Oo.body;if(!qs)return;pt=Ir(Oo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let zs=Ir(Oo,"div");zs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(zs);let _o=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Co),pt.style.left=`${_o.left+_o.width/2}px`,pt.style.top=`${_o.top-8}px`,pt.style.transform="translate(-50%, -100%)",qs.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",cn),it.addEventListener("mouseleave",Hn),qe.addEventListener("focus",cn),qe.addEventListener("blur",Hn),it._cleanupTooltip=()=>{Hn(),it&&(it.removeEventListener("mouseenter",cn),it.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",cn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Rt}=Ve;if(Ke){let ne=(Sp=_e.clearChat)!=null?Sp:{},Et=(Tp=ne.enabled)!=null?Tp:!0,zt=(Mp=(Ep=r.layout)==null?void 0:Ep.header)==null?void 0:Mp.showClearChat,it=zt!==void 0?zt:Et,Lt=(kp=ne.placement)!=null?kp:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:ln}=Ve;!k()&&ln&&!ln.classList.contains("persona-absolute")&&(it?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let wn=Lt==="top-right",pr=Rt.classList.contains("persona-absolute");if(!k()&&wn!==pr&&it){if(Rt.remove(),wn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Ee.style.position="relative",Ee.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Jt=Ee.querySelector(".persona-border-b-persona-divider"),zn=Ve.closeButtonWrapper;Jt&&zn&&zn.parentElement===Jt?Jt.insertBefore(Rt,zn):Jt&&Jt.appendChild(Rt)}let Ln=Ve.closeButtonWrapper;Ln&&!Ln.classList.contains("persona-absolute")&&(wn?Ln.classList.add("persona-ml-auto"):Ln.classList.remove("persona-ml-auto"))}}if(it){if(!k()){let pt=(Lp=ne.size)!=null?Lp:"32px";Ke.style.height=pt,Ke.style.width=pt}let ln=(Pp=ne.iconName)!=null?Pp:"refresh-cw",wn=(Ip=ne.iconColor)!=null?Ip:"";Ke.style.color=wn||Pn.actionIconColor,Ke.innerHTML="";let pr=k()?"14px":"20px",Ln=ye(ln,pr,"currentColor",2);if(Ln&&Ke.appendChild(Ln),ne.backgroundColor?(Ke.style.backgroundColor=ne.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let pt=ne.borderWidth||"0px",cn=ne.borderColor||"transparent";Ke.style.border=`${pt} solid ${cn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ne.borderRadius?(Ke.style.borderRadius=ne.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ne.paddingX?(Ke.style.paddingLeft=ne.paddingX,Ke.style.paddingRight=ne.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ne.paddingY?(Ke.style.paddingTop=ne.paddingY,Ke.style.paddingBottom=ne.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Jt=(Rp=ne.tooltipText)!=null?Rp:"Clear chat",zn=(Wp=ne.showTooltip)!=null?Wp:!0;if(Ke.setAttribute("aria-label",Jt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),zn&&Jt)){let pt=null,cn=()=>{if(pt||!Ke)return;let Oo=Ke.ownerDocument,qs=Oo.body;if(!qs)return;pt=Ir(Oo,"div","persona-clear-chat-tooltip"),pt.textContent=Jt;let zs=Ir(Oo,"div");zs.className="persona-clear-chat-tooltip-arrow",pt.appendChild(zs);let _o=Ke.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(Co),pt.style.left=`${_o.left+_o.width/2}px`,pt.style.top=`${_o.top-8}px`,pt.style.transform="translate(-50%, -100%)",qs.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};Rt.addEventListener("mouseenter",cn),Rt.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",cn),Ke.addEventListener("blur",Hn),Rt._cleanupTooltip=()=>{Hn(),Rt&&(Rt.removeEventListener("mouseenter",cn),Rt.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",cn),Ke.removeEventListener("blur",Hn))}}}}let Un=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Al],Wo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ya.message,ya.messageAndClick];E=Sl({parsers:Un,handlers:Wo,getSessionMetadata:y,updateSessionMetadata:w,emit:l.emit,documentRef:typeof document!="undefined"?document:null}),ee=Fg(r,E,pe),$.updateConfig(r),Ds(Ze,$.getMessages(),ee),Zo(),zl(),Si($.isStreaming());let Ho=((Hp=r.voiceRecognition)==null?void 0:Hp.enabled)===!0,Bo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Do=((Dp=(Bp=r.voiceRecognition)==null?void 0:Bp.provider)==null?void 0:Dp.type)==="runtype";if(Ho&&(Bo||Do))if(!D||!ve){let ne=yf(r.voiceRecognition,r.sendButton);ne&&(D=ne.micButton,ve=ne.micButtonWrapper,yt.insertBefore(ve,An),D.addEventListener("click",Sa),D.disabled=$.isStreaming())}else{let ne=(Np=r.voiceRecognition)!=null?Np:{},Et=(Fp=r.sendButton)!=null?Fp:{},zt=(Op=ne.iconName)!=null?Op:"mic",it=(_p=Et.size)!=null?_p:"40px",Lt=($p=ne.iconSize)!=null?$p:it,ln=parseFloat(Lt)||24;D.style.width=Lt,D.style.height=Lt,D.style.minWidth=Lt,D.style.minHeight=Lt;let wn=(qp=(Up=ne.iconColor)!=null?Up:Et.textColor)!=null?qp:"currentColor";D.innerHTML="";let pr=ye(zt,ln,wn,2);pr?D.appendChild(pr):D.textContent="\u{1F3A4}";let Ln=(zp=ne.backgroundColor)!=null?zp:Et.backgroundColor;Ln?D.style.backgroundColor=Ln:D.style.backgroundColor="",wn?D.style.color=wn:D.style.color="var(--persona-text, #111827)",ne.borderWidth?(D.style.borderWidth=ne.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ne.borderColor?D.style.borderColor=ne.borderColor:D.style.borderColor="",ne.paddingX?(D.style.paddingLeft=ne.paddingX,D.style.paddingRight=ne.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ne.paddingY?(D.style.paddingTop=ne.paddingY,D.style.paddingBottom=ne.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Jt=ve==null?void 0:ve.querySelector(".persona-send-button-tooltip"),zn=(jp=ne.tooltipText)!=null?jp:"Start voice recognition";if(((Vp=ne.showTooltip)!=null?Vp:!1)&&zn)if(Jt)Jt.textContent=zn,Jt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=zn,ve==null||ve.insertBefore(cn,D)}else Jt&&(Jt.style.display="none");ve.style.display="",D.disabled=$.isStreaming()}else D&&ve&&(ve.style.display="none",((Gp=(Kp=r.voiceRecognition)==null?void 0:Kp.provider)==null?void 0:Gp.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Lr&&po());if(((Qp=r.attachments)==null?void 0:Qp.enabled)===!0)if(!ft||!ce){let ne=(Xp=r.attachments)!=null?Xp:{},zt=(Yp=((Jp=r.sendButton)!=null?Jp:{}).size)!=null?Yp:"40px";Pt||(Pt=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pt.style.display="none",At.insertBefore(Pt,be)),Ge||(Ge=document.createElement("input"),Ge.type="file",Ge.accept=((Zp=ne.allowedTypes)!=null?Zp:Gr).join(","),Ge.multiple=((eu=ne.maxFiles)!=null?eu:4)>1,Ge.style.display="none",Ge.setAttribute("aria-label","Attach files"),At.insertBefore(Ge,be)),ft=v("div","persona-send-button-wrapper"),ce=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(tu=ne.buttonTooltipText)!=null?tu:"Attach file");let it=(nu=ne.buttonIconName)!=null?nu:"paperclip",Lt=zt,ln=parseFloat(Lt)||40,wn=Math.round(ln*.6);ce.style.width=Lt,ce.style.height=Lt,ce.style.minWidth=Lt,ce.style.minHeight=Lt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let pr=ye(it,wn,"currentColor",1.5);pr?ce.appendChild(pr):ce.textContent="\u{1F4CE}",ce.addEventListener("click",zn=>{zn.preventDefault(),Ge==null||Ge.click()}),ft.appendChild(ce);let Ln=(ru=ne.buttonTooltipText)!=null?ru:"Attach file",Jt=v("div","persona-send-button-tooltip");Jt.textContent=Ln,ft.appendChild(Jt),Xe.append(ft),!St&&Ge&&Pt&&(St=oa.fromConfig(ne),St.setPreviewsContainer(Pt),Ge.addEventListener("change",async()=>{St&&(Ge!=null&&Ge.files)&&(await St.handleFileSelect(Ge.files),Ge.value="")})),Ee.querySelector(".persona-attachment-drop-overlay")||Ee.appendChild(Og(ne.dropOverlay))}else{ft.style.display="";let ne=(ou=r.attachments)!=null?ou:{};Ge&&(Ge.accept=((su=ne.allowedTypes)!=null?su:Gr).join(","),Ge.multiple=((au=ne.maxFiles)!=null?au:4)>1),St&&St.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else ft&&(ft.style.display="none"),St&&St.clearAttachments(),(iu=Ee.querySelector(".persona-attachment-drop-overlay"))==null||iu.remove();let Qt=(lu=r.sendButton)!=null?lu:{},No=(cu=Qt.useIcon)!=null?cu:!1,mo=(du=Qt.iconText)!=null?du:"\u2191",go=Qt.iconName,jr=(pu=Qt.tooltipText)!=null?pu:"Send message",Fo=(uu=Qt.showTooltip)!=null?uu:!1,et=(mu=Qt.size)!=null?mu:"40px",Ft=Qt.backgroundColor,Nt=Qt.textColor;if(No){if(ue.style.width=et,ue.style.height=et,ue.style.minWidth=et,ue.style.minHeight=et,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.innerHTML="",Nt?ue.style.color=Nt:ue.style.color="var(--persona-button-primary-fg, #ffffff)",go){let ne=parseFloat(et)||24,Et=(Nt==null?void 0:Nt.trim())||"currentColor",zt=ye(go,ne,Et,2);zt?ue.appendChild(zt):ue.textContent=mo}else ue.textContent=mo;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ft?(ue.style.backgroundColor=Ft,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=(fu=(gu=r.copy)==null?void 0:gu.sendButtonLabel)!=null?fu:"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",Ft?(ue.style.backgroundColor=Ft,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),Nt?ue.style.color=Nt:ue.classList.add("persona-text-white");Qt.borderWidth?(ue.style.borderWidth=Qt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Qt.borderColor?ue.style.borderColor=Qt.borderColor:ue.style.borderColor="",Qt.paddingX?(ue.style.paddingLeft=Qt.paddingX,ue.style.paddingRight=Qt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Qt.paddingY?(ue.style.paddingTop=Qt.paddingY,ue.style.paddingBottom=Qt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Kt=An==null?void 0:An.querySelector(".persona-send-button-tooltip");if(Fo&&jr)if(Kt)Kt.textContent=jr,Kt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=jr,An==null||An.insertBefore(ne,ue)}else Kt&&(Kt.style.display="none");let Ut=(wu=(hu=r.layout)==null?void 0:hu.contentMaxWidth)!=null?wu:k()?(vu=(bu=(yu=r.launcher)==null?void 0:yu.composerBar)==null?void 0:bu.contentMaxWidth)!=null?vu:"720px":void 0;Ut?(Ze.style.maxWidth=Ut,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",At&&(At.style.maxWidth=Ut,At.style.marginLeft="auto",At.style.marginRight="auto"),jt&&(jt.style.maxWidth=Ut,jt.style.marginLeft="auto",jt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""),jt&&(jt.style.maxWidth="",jt.style.marginLeft="",jt.style.marginRight=""));let gt=(xu=r.statusIndicator)!=null?xu:{},qt=(Cu=gt.visible)!=null?Cu:!0;if(yn.style.display=qt?"":"none",$){let ne=$.getStatus();ht(yn,(zt=>{var it,Lt,ln,wn;return zt==="idle"?(it=gt.idleText)!=null?it:tn.idle:zt==="connecting"?(Lt=gt.connectingText)!=null?Lt:tn.connecting:zt==="connected"?(ln=gt.connectedText)!=null?ln:tn.connected:zt==="error"?(wn=gt.errorText)!=null?wn:tn.error:tn[zt]})(ne),gt,ne)}yn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let fn=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";yn.classList.add(fn)},open(){_()&&$t(!0,"api")},close(){_()&&$t(!1,"api")},toggle(){_()&&$t(!O,"api")},reconnect(){$.reconnectNow()},clearChat(){Sn=!1,$.clearMessages(),Tr.clear(),lo();try{localStorage.removeItem(Ls),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ls}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ls)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 i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),c!=null&&c.clear&&$r(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},E.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.update()},setMessage(i){return!be||$.isStreaming()?!1:(!O&&_()&&$t(!0,"system"),be.value=i,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if($.isStreaming())return!1;let p=(i==null?void 0:i.trim())||be.value.trim();return p?(!O&&_()&&$t(!0,"system"),be.value="",be.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return $.isStreaming()?!1:((f=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?($.isVoiceActive()||(!O&&_()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("user"),$.isVoiceActive()&&as()})),!0):Lr?!0:tc()?(!O&&_()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),Ca("user"),!0):!1},stopVoiceRecognition(){var i,p;return((p=(i=r.voiceRecognition)==null?void 0:i.provider)==null?void 0:p.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),rt("user"),zr()}),!0):!1:Lr?(G.manuallyDeactivated=!0,dt(),po("user"),!0):!1},injectMessage(i){return!O&&_()&&$t(!0,"system"),$.injectMessage(i)},injectAssistantMessage(i){!O&&_()&&$t(!0,"system");let p=$.injectAssistantMessage(i);return Z&&(Z=!1,ke&&(clearTimeout(ke),ke=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(i){return!O&&_()&&$t(!0,"system"),$.injectUserMessage(i)},injectSystemMessage(i){return!O&&_()&&$t(!0,"system"),$.injectSystemMessage(i)},injectMessageBatch(i){return!O&&_()&&$t(!0,"system"),$.injectMessageBatch(i)},injectComponentDirective(i){return!O&&_()&&$t(!0,"system"),$.injectComponentDirective(i)},injectTestMessage(i){!O&&_()&&$t(!0,"system"),$.injectTestEvent(i)},async connectStream(i,p){return $.connectStream(i,p)},__pushEventStreamEvent(i){K&&(J==null||J.processEvent(i.type,i.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ie||!K||Br()},hideEventStream(){Y&&ir()},isEventStreamVisible(){return Y},showArtifacts(){nr(r)&&(Sn=!1,Cr(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){nr(r)&&(Sn=!0,Cr())},upsertArtifact(i){return nr(r)?(Sn=!1,$.upsertArtifact(i)):null},selectArtifact(i){nr(r)&&$.selectArtifact(i)},clearArtifacts(){nr(r)&&$.clearArtifacts()},getArtifacts(){var i;return(i=$==null?void 0:$.getArtifacts())!=null?i:[]},getSelectedArtifactId(){var i;return(i=$==null?void 0:$.getSelectedArtifactId())!=null?i:null},focusInput(){return H&&!O&&!k()||!be?!1:(be.focus(),!0)},async resolveApproval(i,p,f){let C=$.getMessages().find(L=>{var q;return L.variant==="approval"&&((q=L.approval)==null?void 0:q.id)===i});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${i}`);if(C.approval.toolType==="webmcp"){$.resolveWebMcpApproval(C.id,p);return}return $.resolveApproval(C.approval,p,f)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){w(i)},on(i,p){return l.on(i,p)},off(i,p){l.off(i,p)},isOpen(){return _()&&O},isVoiceActive(){return G.active},toggleReadAloud(i){$.toggleReadAloud(i)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(i){return $.getReadAloudState(i)},onReadAloudChange(i){return $.onReadAloudChange(i)},getState(){return{open:_()&&O,launcherEnabled:H,voiceActive:G.active,streaming:$.isStreaming()}},showCSATFeedback(i){!O&&_()&&$t(!0,"system");let p=Ze.querySelector(".persona-feedback-container");p&&p.remove();let f=Bg({onSubmit:async(b,C)=>{var L;$.isClientTokenMode()&&await $.submitCSATFeedback(b,C),(L=i==null?void 0:i.onSubmit)==null||L.call(i,b,C)},onDismiss:i==null?void 0:i.onDismiss,...i});Ze.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!O&&_()&&$t(!0,"system");let p=Ze.querySelector(".persona-feedback-container");p&&p.remove();let f=Dg({onSubmit:async(b,C)=>{var L;$.isClientTokenMode()&&await $.submitNPSFeedback(b,C),(L=i==null?void 0:i.onSubmit)==null||L.call(i,b,C)},onDismiss:i==null?void 0:i.onDismiss,...i});Ze.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,p){return $.submitCSATFeedback(i,p)},async submitNPSFeedback(i,p){return $.submitNPSFeedback(i,p)},destroy(){ki(),Ro!=null&&(clearInterval(Ro),Ro=null),ct.forEach(i=>i()),me.remove(),lt==null||lt.remove(),Yt==null||Yt.destroy(),sn==null||sn.remove(),Sr&&qe.removeEventListener("click",Sr)}};if((((dd=t==null?void 0:t.debugTools)!=null?dd:!1)||!!r.debug)&&typeof window!="undefined"){let i=window.AgentWidgetBrowser,p={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:f=>f?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=p,ct.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=i)})}if(typeof window!="undefined"){let i=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=F=>{let N=F.detail;(!(N!=null&&N.instanceId)||N.instanceId===i)&&en.focusInput()};if(window.addEventListener("persona:focusInput",p),ct.push(()=>{window.removeEventListener("persona:focusInput",p)}),ie){let F=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===i)&&en.showEventStream()},N=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===i)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",N),ct.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",N)})}let f=F=>{let N=F.detail;(!(N!=null&&N.instanceId)||N.instanceId===i)&&en.showArtifacts()},b=F=>{let N=F.detail;(!(N!=null&&N.instanceId)||N.instanceId===i)&&en.hideArtifacts()},C=F=>{let N=F.detail;N!=null&&N.instanceId&&N.instanceId!==i||N!=null&&N.artifact&&en.upsertArtifact(N.artifact)},L=F=>{let N=F.detail;N!=null&&N.instanceId&&N.instanceId!==i||typeof(N==null?void 0:N.id)=="string"&&en.selectArtifact(N.id)},q=F=>{let N=F.detail;(!(N!=null&&N.instanceId)||N.instanceId===i)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",C),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",q),ct.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",C),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",q)})}let Zn=Rb(r.persistState);if(Zn&&_()){let i=Wb(Zn.storage),p=`${Zn.keyPrefix}widget-open`,f=`${Zn.keyPrefix}widget-voice`,b=`${Zn.keyPrefix}widget-voice-mode`;if(i){let C=((pd=Zn.persist)==null?void 0:pd.openState)&&i.getItem(p)==="true",L=((ud=Zn.persist)==null?void 0:ud.voiceState)&&i.getItem(f)==="true",q=((md=Zn.persist)==null?void 0:md.voiceState)&&i.getItem(b)==="true";if(C&&setTimeout(()=>{en.open(),setTimeout(()=>{var F;if(L||q)en.startVoiceRecognition();else if((F=Zn.persist)!=null&&F.focusInput){let N=n.querySelector("textarea");N&&N.focus()}},100)},0),(gd=Zn.persist)!=null&&gd.openState&&(l.on("widget:opened",()=>{i.setItem(p,"true")}),l.on("widget:closed",()=>{i.setItem(p,"false")})),(fd=Zn.persist)!=null&&fd.voiceState&&(l.on("voice:state",F=>{i.setItem(f,F.active?"true":"false")}),l.on("user:message",F=>{i.setItem(b,F.viaVoice?"true":"false")})),Zn.clearOnChatClear){let F=()=>{i.removeItem(p),i.removeItem(f),i.removeItem(b)},N=()=>F();window.addEventListener("persona:clear-chat",N),ct.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return h&&_()&&setTimeout(()=>{en.open()},0),rs(),va||Pu().then(()=>{$&&(es++,Tr.clear(),Ds(Ze,$.getMessages(),ee))}).catch(()=>{}),en};var Hb=(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},Bb=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},Db=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},Nb=(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.")},$g=(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"},Il=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=""},Ug=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Il(n)},kl=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=""},Pl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},wi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},Fb=(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))},Ob=(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)},qg=(n,e,t,r,o,s,a)=>{var y,w,T,W,E,H;let l=mr(s),d=l.reveal==="push";Fb(n,e,t,r,d),Ob(n,e,t,r,l.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=l.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,u=(w=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?w:!0,g=(W=(T=s==null?void 0:s.launcher)==null?void 0:T.mobileBreakpoint)!=null?W:640,h=c!=null?c.innerWidth<=g:!1;if(u&&h&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),Ll(e),kl(r),Ug(r),Pl(t),wi(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((H=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?H:xn),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"),Ug(r),Bb(r,l.maxHeight),l.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",Ll(e),kl(r),Pl(t),wi(o,r);let B=l.animate?"transform 180ms ease":"none",I=l.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=l.width,r.style.maxWidth=l.width,r.style.minWidth=l.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=B,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",l.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(l.reveal==="push"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",kl(r),Il(r),wi(o,r);let B=Hb(l.width,n.clientWidth),I=Math.max(0,n.clientWidth),S=l.animate?"margin-left 180ms ease":"none",P=l.side==="right"?a?-B:0:a?0:-B;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${I+B}px`,e.style.transition=S,e.style.marginLeft=`${P}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${I}px`,t.style.maxWidth=`${I}px`,t.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=l.width,r.style.minWidth=l.width,r.style.maxWidth=l.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),Il(r),Pl(t),wi(o,r);let B=l.reveal==="emerge";B?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let I=a?l.width:"0px",S=l.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",Db(r,l.maxHeight),r.style.overflow=B||P?"hidden":"visible",r.style.transition=S,B&&(r.style.alignItems=l.side==="right"?"flex-start":"flex-end",o.style.width=l.width,o.style.minWidth=l.width,o.style.maxWidth=l.width,o.style.boxSizing="border-box")}},_b=(n,e)=>{let t=n.ownerDocument.createElement("div");return $g(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){$g(t,r)},destroy(){t.remove()}}},$b=(n,e)=>{var H,B,I,S;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"),l=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),g=(B=(H=e==null?void 0:e.launcher)==null?void 0:H.enabled)==null||B?(S=(I=e==null?void 0:e.launcher)==null?void 0:I.autoExpand)!=null?S:!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,n),d.appendChild(n);let h=null,m=()=>{h==null||h.disconnect(),h=null},y=()=>{m(),mr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{qg(a,l,d,c,u,e,g)}),h.observe(a))},w=!1,T=()=>{qg(a,l,d,c,u,e,g),y(),g&&!w&&a.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,Nb(a,mr(e)))},W=a.ownerDocument.defaultView,E=()=>{T()};return W==null||W.addEventListener("resize",E),mr(e).reveal==="push"?(l.appendChild(d),l.appendChild(c),a.appendChild(l)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:u,shell:a,syncWidgetState(P){let z=P.launcherEnabled?P.open:!0;g!==z&&(g=z,T())},updateConfig(P){var z,U;e=P,((U=(z=e==null?void 0:e.launcher)==null?void 0:z.enabled)!=null?U:!0)===!1&&(g=!0),T()},destroy(){W==null||W.removeEventListener("resize",E),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},zg=(n,e)=>hn(e)?$b(n,e):_b(n,e);var ba={desktop:{w:1280,h:800},mobile:{w:390,h:844}},jg=.15,Vg=1.5,Rl="persona-preview-shell-theme",Ub={load:()=>null,save:()=>{},clear:()=>{}},qb=["How do I get started?","Pricing & plans","Talk to support"];function Wl(n){return n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function zb(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 Kg(n){let e=zb(n);return`* { box-sizing: border-box; }
133
+ ${rt?"background: transparent !important;":""}
134
+ `}if(!v&&!i){let Pt="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",Gs=g?"":`z-index: ${o.launcher?.zIndex??zt} !important;`;ke.style.cssText+=Pt+Yt+Gs}Ao()};Bs(),ss(t,o),xs(t,o),Cs(t,o),Tr=()=>{Bs(),ss(t,o),xs(t,o),Cs(t,o),Es?t.style.setProperty("--persona-artifact-welded-outer-radius",Es):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",ec)}),Ve.push(()=>{Cr!==null&&clearTimeout(Cr)});let Cn=null,An=null;Ve.push(()=>{Cn?.(),Cn=null,An?.(),An=null}),Sr&&Ve.push(()=>{Sr?.disconnect(),Sr=null}),Ve.push(()=>{kr?.(),kr=null,ci(),wt&&(wt.remove(),wt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),Z&&Ve.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),Ne?.destroy(),Ne=null,Se?.destroy(),Se=null,ge=null});let mo=null,oc=()=>{mo&&(mo(),mo=null),o.colorScheme==="auto"&&(mo=Sa(()=>{ss(t,o)}))};oc(),Ve.push(()=>{mo&&(mo(),mo=null)}),Ve.push(a);let Hs=o.features?.streamAnimation;if(Hs?.type&&Hs.type!=="none"){let i=mr(Hs.type,Hs.plugins);i&&(_a(i,t),Ve.push(()=>$p(t)))}let Ds=au(vt),ho=null,O,di=i=>{if(!O)return;let g=i??O.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?Ed(g):null;h?Ds.render(h,O,N,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(v=>v.role==="user")?Ds.render([],O,N,g):Ds.render(o.suggestionChips,O,N,g,o.suggestionChipsConfig)},hn=!1,yo=Rp(),qo=new Map,bo=new Map,jn=new Map,pi=0,Gu=Bn()!==null,en=Ba(),ln=0,qn=null,cn=!1,Fs=!1,Vn=0,yn=null,vo=null,ui=!1,Ns=!1,fi=null,Lr=!0,gi=!1,mi=null,Xu=4,Os=24,Qu=80,hi=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},rc=o.voiceRecognition?.autoResume??!1,Pn=i=>{l.emit("voice:state",{active:Xe.active,source:i,timestamp:Date.now()})},bn=()=>{x(i=>({...i,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},Ju=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Rl(c.voiceState),g=!!i.active,h=Number(i.timestamp??0);Xe.manuallyDeactivated=!!i.manuallyDeactivated,g&&Date.now()-h<uy&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Xe.active=O.isVoiceActive(),Pn("restore"),O.isVoiceActive()&&Qo()}):zs("restore"))},1e3)},Yu=()=>O?Mu(O.getMessages()).filter(i=>!i.__skipPersist):[],_s=null,sc=(i,g)=>{typeof console<"u"&&console.error(i,g)},yi=(i,g)=>{let h=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(_=>{sc(g,_)})}catch(J){return sc(g,J),null}},v=_s,T=v?v.then(()=>h()??void 0):h();if(!T)return;let L=T.finally(()=>{_s===L&&(_s=null)});_s=L};function bi(i){if(!d?.save)return;let h={messages:i?Mu(i):O?Yu():[],metadata:c,artifacts:gn.artifacts,selectedArtifactId:gn.selectedId};yi(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let Vo=null,ac=()=>ke.querySelector("#persona-scroll-container")||le,Pr=()=>{Vo!==null&&(cancelAnimationFrame(Vo),Vo=null),cn=!1},ic=()=>{qn!==null&&(cancelAnimationFrame(qn),qn=null),Fs=!1,Pr()},Zu=()=>hn&&wi()&&(Jt()!=="anchor-top"||$l()),vi=()=>{let i=po()||"Jump to latest",g=Zu();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Vn>0?(uo.textContent=String(Vn),uo.style.display="",It.setAttribute("aria-label",`${i} (${Vn} new)`)):(uo.textContent="",uo.style.display="none",It.setAttribute("aria-label",g?`${i} (response streaming below)`:i))},lc=()=>{Vn!==0&&(Vn=0,vi())},wi=()=>_n()?!en.isFollowing():!io(le,Os),tn=()=>{if(!Ts()||Ie){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==fe&&fe.appendChild(It),$o();let g=En(le)>0&&wi();g?vi():lc(),It.style.display=g?"":"none"},Ir=()=>{en.pause()&&(ic(),tn())},Kn=()=>{en.resume(),lc(),tn()},Gn=(i=!1)=>{_n()&&en.isFollowing()&&(!i&&!hn||(qn!==null&&(cancelAnimationFrame(qn),qn=null),Fs=!0,qn=requestAnimationFrame(()=>{qn=null,Fs=!1,en.isFollowing()&&ef(ac(),i?220:140)})))},cc=(i,g,h,v=()=>!0)=>{let T=i.scrollTop,L=g(),J=L-T;if(Pr(),Math.abs(J)<1){cn=!0,i.scrollTop=L,ln=i.scrollTop,cn=!1;return}let _=performance.now();cn=!0;let X=pe=>1-Math.pow(1-pe,3),ae=pe=>{if(!v()){Pr();return}let re=g();re!==L&&(L=re,J=L-T);let xe=pe-_,Ke=Math.min(xe/h,1),yt=X(Ke),at=T+J*yt;i.scrollTop=at,ln=i.scrollTop,Ke<1?Vo=requestAnimationFrame(ae):(i.scrollTop=L,ln=i.scrollTop,Vo=null,cn=!1)};Vo=requestAnimationFrame(ae)},ef=(i,g=500)=>{let h=En(i)-i.scrollTop;if(Math.abs(h)<1){ln=i.scrollTop;return}if(Math.abs(h)>=Qu){Pr(),cn=!0,i.scrollTop=En(i),ln=i.scrollTop,cn=!1;return}cc(i,()=>En(i),g,()=>en.isFollowing())},dc=()=>{let i=ac();cn=!0,i.scrollTop=En(i),ln=i.scrollTop,cn=!1,tn()},pc=i=>{let g=0,h=i;for(;h&&h!==le;)g+=h.offsetTop,h=h.offsetParent;return g},uc=()=>{if(Uu()!=="last-user-turn")return!1;let i=O?.getMessages()??[];if(i.length<2)return!1;let g=[...i].reverse().find(L=>L.role==="user");if(!g)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=le.querySelector(`[data-message-id="${h}"]`);if(!v)return!1;let T=Math.min(Math.max(0,pc(v)-Ol()),En(le));return cn=!0,le.scrollTop=T,ln=le.scrollTop,cn=!1,Jt()==="follow"&&!io(le,Os)&&en.pause(),tn(),!0},fc=i=>{$n.style.height=`${Math.max(0,Math.round(i))}px`,yn&&(yn.spacerHeight=Math.max(0,i))},Rr=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Pr(),yn=null,$n.style.height="0px"},tf=i=>{vo!==null&&cancelAnimationFrame(vo),vo=requestAnimationFrame(()=>{vo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=le.querySelector(`[data-message-id="${g}"]`);if(!h)return;let v=pc(h),T=yn?.spacerHeight??0,L=le.scrollHeight-T,{targetScrollTop:J,spacerHeight:_}=Fp({anchorOffsetTop:v,topOffset:Ol(),viewportHeight:le.clientHeight,contentHeight:L});yn={initialSpacerHeight:_,contentHeightAtAnchor:L,spacerHeight:_},fc(_),cc(le,()=>J,220)})},nf=()=>{if(_n()){if(!en.isFollowing()||io(le,1))return;Gn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let i=le.scrollHeight-yn.spacerHeight,g=Np({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:i});g!==yn.spacerHeight&&fc(g)}tn()},of=i=>{let g=Jt();g==="follow"?(Kn(),Gn(!0)):g==="anchor-top"&&(Lr=!1,gi=!0,tf(i))},rf=()=>{if(Jt()==="anchor-top"){if(gi){Lr=!1;return}Lr=!0,Rr(),Kn(),Gn(!0)}},sf=i=>{let g=new Map;i.forEach(h=>{let v=hi.get(h.id);g.set(h.id,{streaming:h.streaming,role:h.role}),!v&&h.role==="assistant"&&(l.emit("assistant:message",h),!Ns&&(Jt()!=="anchor-top"||$l())&&wi()&&(Vn+=1,vi(),tn(),zl(Vn===1?"1 new message below.":`${Vn} new messages below.`))),h.role==="assistant"&&v?.streaming&&h.streaming===!1&&l.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(v?h.approval.status!=="pending"&&l.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):l.emit("approval:requested",{approval:h.approval,message:h}))}),hi.clear(),g.forEach((h,v)=>{hi.set(v,h)})},af=(i,g,h)=>{let v=document.createElement("div"),L=(()=>{let I=r.find(Oe=>Oe.renderLoadingIndicator);if(I?.renderLoadingIndicator)return I.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(I,Oe)=>Oe==null?!1:typeof Oe=="string"?(I.textContent=Oe,!0):(I.appendChild(Oe),!0),_=new Set,X=new Set,ae=r.some(I=>I.renderAskUserQuestion),pe=[],re=[],xe=o.enableComponentStreaming!==!1,Ke=o.approval!==!1,yt=[];if(g.forEach(I=>{_.add(I.id);let Oe=ae&&Io(I),Te=Ke&&I.variant==="approval"&&!!I.approval,$e=!Oe&&I.role==="assistant"&&!I.variant&&xe&&Il(I);!Te&&jn.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(I.id)),!$e&&bo.has(I.id)&&(i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(I.id));let Tt=Io(I)?`:${I.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${I.agentMetadata?.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=Ip(I,pi)+Tt,Ct=Oe||Te||$e?null:Wp(yo,I.id,ut);if(Ct){v.appendChild(Ct.cloneNode(!0)),Io(I)&&I.toolCall?.id&&I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(X.add(I.toolCall.id),ia(I,o,Re.composerOverlay));return}let bt=null,$t=r.find(ue=>!!(I.variant==="reasoning"&&ue.renderReasoning||I.variant==="tool"&&ue.renderToolCall||!I.variant&&ue.renderMessage)),Co=o.layout?.messages;if(Io(I)&&I.agentMetadata?.askUserQuestionAnswered===!0){qo.delete(I.id),i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime");return}if(ji(I)&&o.features?.suggestReplies?.enabled!==!1)return;if(Io(I)&&o.features?.askUserQuestion?.enabled!==!1){let ue=r.find(At=>typeof At.renderAskUserQuestion=="function");if(ue&&mt.current){let At=qo.get(I.id),Vt=At!==ut,Dt=null;if(Vt){let{payload:Ze,complete:Lt}=nr(I),De=I.id,et=()=>mt.current?.getMessages().find(nn=>nn.id===De);Dt=ue.renderAskUserQuestion({message:I,payload:Ze,complete:Lt,resolve:nn=>{let Ao=et();Ao&&mt.current?.resolveAskUserQuestion(Ao,nn)},dismiss:()=>{let nn=et();nn?.agentMetadata?.awaitingLocalTool&&(mt.current?.markAskUserQuestionResolved(nn),mt.current?.resolveAskUserQuestion(nn,"(dismissed)"))},config:o})}let rt=At!=null;if(Vt&&Dt===null&&!rt){I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(X.add(I.toolCall.id),ia(I,o,Re.composerOverlay));return}let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${I.id}`,qe.setAttribute("data-wrapper-id",I.id),qe.setAttribute("data-ask-plugin-stub","true"),qe.setAttribute("data-preserve-runtime","true"),v.appendChild(qe),pe.push({messageId:I.id,fingerprint:ut,bubble:Dt});return}else{I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(X.add(I.toolCall.id),ia(I,o,Re.composerOverlay));return}}else if(Te){let ue=r.find(rt=>typeof rt.renderApproval=="function")??s,Vt=jn.get(I.id)!==ut,Dt=null;if(Vt&&ue?.renderApproval){let rt=I.id,qe=(Ze,Lt)=>{let De=mt.current?.getMessages().find(et=>et.id===rt);De?.approval&&(De.approval.toolType==="webmcp"?mt.current?.resolveWebMcpApproval(De.id,Ze):mt.current?.resolveApproval(De.approval,Ze,Lt))};Dt=ue.renderApproval({message:I,defaultRenderer:()=>Ya(I,o),config:o,approve:Ze=>qe("approved",Ze),deny:Ze=>qe("denied",Ze)})}if(Vt&&Dt===null)i.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),jn.delete(I.id),bt=Ya(I,o);else{let rt=document.createElement("div");rt.className="persona-flex",rt.id=`wrapper-${I.id}`,rt.setAttribute("data-wrapper-id",I.id),rt.setAttribute("data-approval-plugin-stub","true"),rt.setAttribute("data-preserve-runtime","true"),v.appendChild(rt),yt.push({messageId:I.id,fingerprint:ut,bubble:Dt});return}}else if($t)if(I.variant==="reasoning"&&I.reasoning&&$t.renderReasoning){if(!ne)return;bt=$t.renderReasoning({message:I,defaultRenderer:()=>ml(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&$t.renderToolCall){if(!me)return;bt=$t.renderToolCall({message:I,defaultRenderer:()=>yl(I,o),config:o})}else $t.renderMessage&&(bt=$t.renderMessage({message:I,defaultRenderer:()=>{let ue=gl(I,h,Co,o.messageActions,_e,{loadingIndicatorRenderer:L,widgetConfig:o});return I.role!=="user"&&Sl(ue,I,o,O),ue},config:o}));if(!bt&&$e){let ue=Au(I);if(ue){let At=bo.get(I.id),Vt=At!==ut,Dt=o.wrapComponentDirectiveInBubble!==!1&&On.getOptions(ue.component)?.bubbleChrome!==!1,rt=null;if(Vt){let qe=xu(ue,{config:o,message:I,transform:h});if(qe&&ue.component==="PersonaArtifactInline"){let Ze=qe.hasAttribute("data-artifact-inline")?qe:qe.querySelector("[data-artifact-inline]"),Lt=Ze?.getAttribute("data-artifact-inline")??"",De=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Lt):Lt,et=Lt?i.querySelector(`#wrapper-${I.id}`)?.querySelector(`[data-artifact-inline="${De}"]`)??null:null;Ze&&et&&et!==Ze&&Tp(et)&&(Ze===qe?qe=et:Ze.replaceWith(et))}if(qe)if(Dt){let Ze=document.createElement("div");if(Ze.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(" "),Ze.id=`bubble-${I.id}`,Ze.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let Lt=document.createElement("div");Lt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Lt.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ze.appendChild(Lt)}Ze.appendChild(qe),rt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${I.id}`,Ze.setAttribute("data-message-id",I.id),Ze.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let Lt=document.createElement("div");Lt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Lt.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ze.appendChild(Lt)}Ze.appendChild(qe),rt=Ze}}if(rt||At!=null){let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${I.id}`,qe.setAttribute("data-wrapper-id",I.id),qe.setAttribute("data-component-directive-stub","true"),qe.setAttribute("data-preserve-runtime","true"),Dt||qe.classList.add("persona-w-full"),v.appendChild(qe),re.push({messageId:I.id,fingerprint:ut,bubble:rt});return}}}if(!bt)if(I.variant==="reasoning"&&I.reasoning){if(!ne)return;bt=ml(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!me)return;bt=yl(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;bt=Ya(I,o)}else{let ue=o.layout?.messages;ue?.renderUserMessage&&I.role==="user"?bt=ue.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):ue?.renderAssistantMessage&&I.role==="assistant"?bt=ue.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):bt=gl(I,h,ue,o.messageActions,_e,{loadingIndicatorRenderer:L,widgetConfig:o}),I.role!=="user"&&bt&&Sl(bt,I,o,O)}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${I.id}`,ft.setAttribute("data-wrapper-id",I.id),I.role==="user"&&ft.classList.add("persona-justify-end"),bt?.getAttribute("data-persona-component-directive")==="true"&&ft.classList.add("persona-w-full"),ft.appendChild(bt),Bp(yo,I.id,ut,ft),v.appendChild(ft)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Oe=>{let Te=Oe.getAttribute("data-persona-ask-sheet-for");Te&&!X.has(Te)&&rr(Re.composerOverlay,Te)}),o.features?.toolCallDisplay?.grouped){let I=[],Oe=[];g.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&me){Oe.push(Te);return}Te.variant==="reasoning"&&!ne||(Oe.length>1&&I.push(Oe),Oe=[])}),Oe.length>1&&I.push(Oe),I.forEach((Te,$e)=>{let Tt=Te.map(At=>Array.from(v.children).find(Vt=>Vt instanceof HTMLElement&&Vt.getAttribute("data-wrapper-id")===At.id)).filter(At=>!!At);if(Tt.length<2)return;let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-tool-group-${$e}-${Te[0].id}`,ut.setAttribute("data-wrapper-id",`tool-group-${$e}-${Te[0].id}`);let Ct=document.createElement("div");Ct.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ct.setAttribute("data-persona-tool-group","true");let bt=document.createElement("div");bt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Te.length} tools`,Co=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(At=>At.toolCall).filter(At=>!!At),defaultSummary:$t,config:o});J(bt,Co)||(bt.textContent=$t);let ft=document.createElement("div");ft.className="persona-tool-group-stack persona-flex persona-flex-col";let ue=o.features?.toolCallDisplay?.groupedMode==="summary";Ct.appendChild(bt),ue||Ct.appendChild(ft),ut.appendChild(Ct),Tt[0].before(ut),Tt.forEach((At,Vt)=>{if(ue){At.remove();return}let Dt=document.createElement("div");Dt.className="persona-tool-group-item persona-relative",Dt.setAttribute("data-persona-tool-group-item","true"),Vt<Tt.length-1&&Dt.setAttribute("data-persona-tool-group-connector","true"),Dt.appendChild(At),ft.appendChild(Dt)})})}Hp(yo,_);let at=g.some(I=>I.role==="assistant"&&I.streaming),qt=g[g.length-1],Ht=qt?.role==="assistant"&&!qt.streaming&&qt.variant!=="approval";if(hn&&g.some(I=>I.role==="user")&&!at&&!Ht){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:ys},Oe=r.find($e=>$e.renderLoadingIndicator),Te=null;if(Oe?.renderLoadingIndicator&&(Te=Oe.renderLoadingIndicator(I)),Te===null&&o.loadingIndicator?.render&&(Te=o.loadingIndicator.render(I)),Te===null&&(Te=ys()),Te){let $e=document.createElement("div"),Tt=o.loadingIndicator?.showBubble!==!1;$e.className=Tt?["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(" "),$e.setAttribute("data-typing-indicator","true"),$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",$e.appendChild(Te);let ut=document.createElement("div");ut.className="persona-flex",ut.id="wrapper-typing-indicator",ut.setAttribute("data-wrapper-id","typing-indicator"),ut.appendChild($e),v.appendChild(ut)}}if(!hn&&g.length>0){let I=g[g.length-1],Oe={config:o,lastMessage:I,messageCount:g.length},Te=r.find(Tt=>Tt.renderIdleIndicator),$e=null;if(Te?.renderIdleIndicator&&($e=Te.renderIdleIndicator(Oe)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(Oe)),$e){let Tt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Tt.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(" "),Tt.setAttribute("data-idle-indicator","true"),Tt.appendChild($e);let Ct=document.createElement("div");Ct.className="persona-flex",Ct.id="wrapper-idle-indicator",Ct.setAttribute("data-wrapper-id","idle-indicator"),Ct.appendChild(Tt),v.appendChild(Ct)}}if(Ra(i,v),pe.length>0)for(let{messageId:I,fingerprint:Oe,bubble:Te}of pe){let $e=i.querySelector(`#wrapper-${I}`);$e&&Te!==null&&($e.replaceChildren(Te),$e.setAttribute("data-bubble-fp",Oe),qo.set(I,Oe))}if(qo.size>0)for(let I of qo.keys())_.has(I)||qo.delete(I);if(re.length>0)for(let{messageId:I,fingerprint:Oe,bubble:Te}of re){let $e=i.querySelector(`#wrapper-${I}`);$e&&Te!==null&&($e.replaceChildren(Te),$e.setAttribute("data-bubble-fp",Oe),bo.set(I,Oe))}if(bo.size>0)for(let I of bo.keys())_.has(I)||bo.delete(I);if(yt.length>0)for(let{messageId:I,fingerprint:Oe,bubble:Te}of yt){let $e=i.querySelector(`#wrapper-${I}`);$e&&Te!==null&&($e.replaceChildren(Te),$e.setAttribute("data-bubble-fp",Oe),jn.set(I,Oe))}if(jn.size>0)for(let I of jn.keys())_.has(I)||jn.delete(I)},Wr=(i,g,h)=>{af(i,g,h),Jl()},Br=null,lf=()=>{if(Br)return;let i=h=>{let v=h.composedPath();v.includes(ke)||lt&&v.includes(lt)||ht(!1,"user")};Br=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},gc=()=>{if(!Br)return;(t.ownerDocument??document).removeEventListener("pointerdown",Br,!0),Br=null};Ve.push(()=>gc());let Hr=null,cf=()=>{if(Hr)return;let i=h=>{h.key==="Escape"&&(h.isComposing||ht(!1,"user"))};Hr=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},mc=()=>{if(!Hr)return;(t.ownerDocument??document).removeEventListener("keydown",Hr,!0),Hr=null};Ve.push(()=>mc());let Dr=!1,hc=new Set,df=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Ko=()=>{if(!Y())return;let i=Re.peekBanner,g=Re.peekTextNode;if(!i||!g)return;if(U){i.classList.remove("persona-pill-peek--visible");return}let h=O?.getMessages()??[],v;for(let Ht=h.length-1;Ht>=0;Ht--){let I=h[Ht];if(I.role==="assistant"&&I.content){v=I;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let T=v.content,L=!!v.streaming,J=df(),_=Fa(J),X=_.type!=="none"?mr(_.type,J?.plugins):null,ae=X?.isAnimating?.(v)===!0,pe=X!==null&&(L||ae);pe&&X&&!hc.has(X.name)&&(_a(X,t),hc.add(X.name));let re=pe&&X?.containerClass?X.containerClass:null,xe=g.dataset.personaPeekStreamClass??null;xe&&xe!==re&&(g.classList.remove(xe),delete g.dataset.personaPeekStreamClass),re&&xe!==re&&(g.classList.add(re),g.dataset.personaPeekStreamClass=re),pe?(g.style.setProperty("--persona-stream-step",`${_.speed}ms`),g.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ke=pe?Na(T,_.buffer,X,v,L):T;if(pe&&_.placeholder==="skeleton"&&L&&(!Ke||!Ke.trim())){let Ht=document.createElement("div"),I=us();I.classList.add("persona-pill-peek__skeleton"),Ht.appendChild(I),Ra(g,Ht)}else{let Ht=Math.max(0,Ke.length-100),I=Ke.length>100?Ke.slice(-100):Ke,Oe=Yn(I);if(!pe||!X){let Te=Ke.length>100?`\u2026${I}`:I;g.textContent!==Te&&(g.textContent=Te)}else{let Te=Oe;(X.wrap==="char"||X.wrap==="word")&&(Te=ps(Oe,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:Ht}));let $e=document.createElement("div");if($e.innerHTML=Te,X.useCaret&&I.length>0){let Tt=Oa(),ut=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ct=ut[ut.length-1];Ct?.parentNode?Ct.parentNode.insertBefore(Tt,Ct.nextSibling):$e.appendChild(Tt)}Ra(g,$e),X.onAfterRender?.({container:g,bubble:i,messageId:v.id,message:v,speed:_.speed,duration:_.duration})}}let qt=hn||Dr;i.classList.toggle("persona-pill-peek--visible",qt)};if(Y()){let i=Re.peekBanner;if(i){let v=T=>{T.preventDefault(),T.stopPropagation(),ht(!0,"user")};i.addEventListener("pointerdown",v),Ve.push(()=>{i.removeEventListener("pointerdown",v)})}let g=()=>{Dr||(Dr=!0,Ko())},h=()=>{Dr&&(Dr=!1,Ko())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",h),Ve.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",h)}),lt&&(lt.addEventListener("pointerenter",g),lt.addEventListener("pointerleave",h),Ve.push(()=>{lt.removeEventListener("pointerenter",g),lt.removeEventListener("pointerleave",h)}))}let pf=i=>{let g=o.launcher?.composerBar??{},h=g.expandedSize??"anchored",v=g.bottomOffset??"16px",T=g.collapsedMaxWidth,L=g.expandedMaxWidth??"880px",J=g.expandedTopOffset??"5vh",_=g.modalMaxWidth??"880px",X=g.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",re=ke.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",lt){let xe=lt.style;xe.bottom=v,xe.width=T??""}if(i&&h!=="fullscreen"){if(h==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=_,re.maxWidth=ae,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${pe})`,re.top=J,re.width=L,re.maxWidth=ae}},Fr=()=>{if(!F())return;if(Y()){let ae=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=U?"expanded":"collapsed";ke.dataset.state=pe,ke.dataset.expandedSize=ae,lt&&(lt.dataset.state=pe,lt.dataset.expandedSize=ae),ke.style.removeProperty("display"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),pf(U),fe.style.display=U?"flex":"none",Bs(),U?(lf(),cf()):(gc(),mc()),Ko();return}let i=Ot(o),g=t.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,T=g.innerWidth<=h,L=v&&T&&R,J=fn(o).reveal;U?(ke.style.removeProperty("display"),ke.style.display=i?"flex":"",ke.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"),_t?_t.element.style.display="none":jt&&(jt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!L?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=i?"none":"":jt&&(jt.style.display=i?"none":""))},ht=(i,g="user")=>{if(!F()||U===i)return;let h=U;U=i,Fr();let v=(()=>{let L=o.launcher?.sidebarMode??!1,J=t.ownerDocument.defaultView??window,_=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,ae=J.innerWidth<=X,pe=Ot(o)&&_&&ae,re=Y()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||_&&ae&&R||pe||re})();if(U&&v){if(!Cn){let L=t.getRootNode(),J=L instanceof ShadowRoot?L.host:t.closest(".persona-host");J&&(Cn=ll(J,o.launcher?.zIndex??zt))}An||(An=cl(t.ownerDocument))}else U||(Cn?.(),Cn=null,An?.(),An=null);U&&(Nr(),uc()||(Jt()==="follow"?Gn(!0):dc()));let T={open:U,source:g,timestamp:Date.now()};U&&!h?l.emit("widget:opened",T):!U&&h&&l.emit("widget:closed",T),l.emit("widget:state",{open:U,launcherEnabled:R,voiceActive:Xe.active,streaming:O.isStreaming()})},xi=i=>{ct(i?"stop":"send"),K&&(K.disabled=i),Ds.buttons.forEach(g=>{g.disabled=i}),q.dataset.personaComposerStreaming=i?"true":"false",q.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=i)})},Ci=()=>{Xe.active||N&&N.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Ci(),200)});let yc=()=>{Q.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",y.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",N.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=le.querySelector("[data-persona-intro-card]");if(i){let h=o.copy?.showWelcomeCard!==!1;i.style.display=h?"":"none",h?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!O?.isStreaming()&&(oe.textContent=o.copy?.sendButtonLabel??"Send"),N.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',N.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=c.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{x(g=>({...g,sessionId:i}))}});let wo=null,uf=()=>{wo==null&&(wo=setInterval(()=>{let i=be.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(wo),wo=null;return}let g=Date.now();i.forEach(h=>{let v=Number(h.getAttribute("data-tool-elapsed"));v&&(h.textContent=da(g-v))})},100))},Ai=(i,g)=>{if(Object.is(i,g))return!0;if(i===null||g===null||typeof i!="object"||typeof g!="object")return!1;if(Array.isArray(i)||Array.isArray(g))return!Array.isArray(i)||!Array.isArray(g)||i.length!==g.length?!1:i.every((J,_)=>Ai(J,g[_]));let h=i,v=g,T=Object.keys(h),L=Object.keys(v);return T.length===L.length&&T.every(J=>Object.prototype.hasOwnProperty.call(v,J)&&Ai(h[J],v[J]))},bc=i=>{let{content:g,rawContent:h,llmContent:v,...T}=i;return T},Si=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Il(i),ff=(i,g,h)=>{if(i.length!==g.length)return!1;let v=i[h.index],T=g[h.index];return!v||!T||v.id!==h.id||T.id!==h.id?!1:(!Object.is(v.content,T.content)||!Object.is(v.rawContent,T.rawContent)||!Object.is(v.llmContent,T.llmContent))&&Si(v)&&Si(T)&&Ai(bc(v),bc(T))},vc=null,Go=null,xo=null,In=null,$s=i=>{vc=i;let g,h;Go=null;for(let T=i.length-1;T>=0;T-=1){let L=i[T];if(!g&&L.role==="user"&&(g=L),!h&&L.role==="assistant"&&(h=L),!Go&&Si(L)&&(Go={index:T,id:L.id}),g&&h&&Go)break}Wr(be,i,Ae),ol(be,gn.artifacts,{suppressTransition:hn}),uf(),di(i),Gn(!hn),sf(i),i.length===0&&(Rr(),Lr=!0,gi=!1),!ui||Ns?(ui=!0,fi=g?.id??null,mi=h?.id??null):g&&g.id!==fi?(fi=g.id,of(g.id)):h&&h.id!==mi&&rf(),h&&(mi=h.id);let v=Xe.lastUserMessageId;g&&g.id!==v&&(Xe.lastUserMessageId=g.id,l.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,bi(i),Ko()},Ti=()=>{In!==null&&(cancelAnimationFrame(In),In=null);let i=xo;xo=null,i&&$s(i)},wc=()=>{In!==null&&cancelAnimationFrame(In),In=null,xo=null},gf=i=>{let g=xo??vc;if(hn&&g&&Go&&ff(g,i,Go)){xo=i,In===null&&(In=requestAnimationFrame(()=>{In=null;let h=xo;xo=null,h&&$s(h)}));return}if(i.length===0){wc(),$s(i);return}Ti(),$s(i)};O=new wa(o,{onMessagesChanged(i){gf(i)},onStatusChanged(i){let g=o.statusIndicator??{};kt(E,(v=>v==="idle"?g.idleText??Wt.idle:v==="connecting"?g.connectingText??Wt.connecting:v==="connected"?g.connectedText??Wt.connected:v==="error"?g.errorText??Wt.error:v==="paused"?g.pausedText??Wt.paused:v==="resuming"?g.resumingText??Wt.resuming:Wt[v])(i),g,i)},onStreamingChanged(i){i||(O?.getMessages().length===0?wc():Ti()),hn=i,xi(i),O&&Wr(be,O.getMessages(),Ae),i||Gn(!0),tn(),zl(i?"Responding\u2026":"Response complete."),Ko()},onVoiceStatusChanged(i){if(l.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":Rn(),Qo();break;case"processing":Rn(),vf();break;case"speaking":Rn(),wf();break;default:i==="idle"&&O.isBargeInActive()?(Rn(),Qo(),K?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Rn(),Pn("system"),bn());break}},onArtifactsState(i){gn=i,i.artifacts.length===0&&(Uo=!1),ol(be,i.artifacts,{suppressTransition:hn}),Ln(),bi()},onReconnect(i){let{executionId:g,lastEventId:h}=i.handle;i.phase==="paused"?l.emit("stream:paused",{executionId:g,after:h}):i.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:h,attempt:i.attempt??1}):l.emit("stream:resumed",{executionId:g,after:h})}}),mt.current=O,Ve.push(()=>O.cancel());let Mi=null;if(O.onReadAloudChange((i,g)=>{Xl=i,Ql=g,Jl();let h=i??Mi;i&&(Mi=i);let v=h?O.getMessages().find(T=>T.id===h)??null:null;l.emit("message:read-aloud",{messageId:h,message:v,state:g,timestamp:Date.now()}),g==="idle"&&(Mi=null)}),ui=!0,o.voiceRecognition?.provider?.type==="runtype")try{O.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&O.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Se||o.onSSEEvent)&&O.setSSEEventCallback((i,g)=>{o.onSSEEvent?.(i,g),je?.processEvent(i,g),Se?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(g)})});let xc=()=>{o.resume&&typeof o.reconnectStream=="function"&&O.resumeFromHandle(o.resume)};u?u.then(i=>{if(i){if(i.metadata&&(c=Rl(i.metadata),M.syncFromMetadata()),i.messages?.length){Ns=!0;try{O.hydrateMessages(i.messages)}finally{Ns=!1}}i.artifacts?.length&&O.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>xc()):xc();let Cc=()=>{!Y()||U||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},Ac=i=>{if(i.preventDefault(),O.isStreaming()){O.cancel(),je?.reset(),Ne?.update();return}let g=N.value.trim(),h=Mt?.hasAttachments()??!1;if(!g&&!h)return;Cc();let v;h&&(v=[],v.push(...Mt.getContentParts()),g&&v.push(Ki(g))),N.value="",N.style.height="auto",Us(),O.sendMessage(g,{contentParts:v}),h&&Mt.clearAttachments()},mf=()=>o.features?.composerHistory!==!1,Ei={...Wa},ki=!1,Us=()=>{Ei={...Wa}},hf=()=>O.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),yf=i=>{if(!N)return;ki=!0,N.value=i,N.dispatchEvent(new Event("input",{bubbles:!0})),ki=!1;let g=N.value.length;N.setSelectionRange(g,g)},Sc=()=>{ki||Us()},Tc=i=>{if(N){if(mf()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let g=N.selectionStart===0&&N.selectionEnd===0,h=Pp({direction:i.key==="ArrowUp"?"up":"down",history:hf(),currentValue:N.value,atStart:g,state:Ei});if(Ei=h.state,h.handled){i.preventDefault(),h.value!==void 0&&yf(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(O.isStreaming()){i.preventDefault();return}Us(),i.preventDefault(),oe.click()}}},Mc=i=>{i.key!=="Escape"||i.isComposing||O.isStreaming()&&i.composedPath().includes(fe)&&(O.cancel(),je?.reset(),Ne?.update(),Us(),i.preventDefault(),i.stopImmediatePropagation())},Ec=async i=>{if(o.attachments?.enabled!==!0||!Mt)return;let g=my(i.clipboardData);g.length!==0&&(i.preventDefault(),await Mt.handleFiles(g))},dn=null,Sn=!1,Xo=null,xt=null,kc=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,zs=(i="user")=>{if(Sn||O.isStreaming())return;let g=kc();if(!g)return;dn=new g;let v=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let T=N.value;dn.onresult=L=>{let J="",_="";for(let ae=0;ae<L.results.length;ae++){let pe=L.results[ae],re=pe[0].transcript;pe.isFinal?J+=re+" ":_=re}let X=T+J+_;N.value=X,Xo&&clearTimeout(Xo),(J||_)&&(Xo=window.setTimeout(()=>{let ae=N.value.trim();ae&&dn&&Sn&&(Xn(),N.value="",N.style.height="auto",O.sendMessage(ae,{viaVoice:!0}))},v))},dn.onerror=L=>{L.error!=="no-speech"&&Xn()},dn.onend=()=>{if(Sn){let L=N.value.trim();L&&L!==T.trim()&&(N.value="",N.style.height="auto",O.sendMessage(L,{viaVoice:!0})),Xn()}};try{if(dn.start(),Sn=!0,Xe.active=!0,i!=="system"&&(Xe.manuallyDeactivated=!1),Pn(i),bn(),K){let L=o.voiceRecognition??{};xt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let J=L.recordingBackgroundColor,_=L.recordingIconColor,X=L.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=_??"var(--persona-voice-recording-indicator, #ffffff)",_){let ae=K.querySelector("svg");ae&&ae.setAttribute("stroke",_)}X&&(K.style.borderColor=X),K.setAttribute("aria-label","Stop voice recognition")}}catch{Xn("system")}},Xn=(i="user")=>{if(Sn){if(Sn=!1,Xo&&(clearTimeout(Xo),Xo=null),dn){try{dn.stop()}catch{}dn=null}if(Xe.active=!1,Pn(i),bn(),K){if(K.classList.remove("persona-voice-recording"),xt){K.style.backgroundColor=xt.backgroundColor,K.style.color=xt.color,K.style.borderColor=xt.borderColor;let g=K.querySelector("svg");g&&g.setAttribute("stroke",xt.color||"currentColor"),xt=null}K.setAttribute("aria-label","Start voice recognition")}}},bf=(i,g)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",T=i?.provider?.type==="custom";if(!(h||v||T))return null;let J=m("div","persona-send-button-wrapper"),_=m("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 X=i?.iconName??"mic",ae=g?.size??"40px",pe=i?.iconSize??ae,re=parseFloat(pe)||24,xe=i?.backgroundColor??g?.backgroundColor,Ke=i?.iconColor??g?.textColor;_.style.width=pe,_.style.height=pe,_.style.minWidth=pe,_.style.minHeight=pe,_.style.fontSize="18px",_.style.lineHeight="1",Ke?_.style.color=Ke:_.style.color="var(--persona-text, #111827)";let at=ie(X,re,Ke||"currentColor",1.5);at?_.appendChild(at):_.textContent="\u{1F3A4}",xe?_.style.backgroundColor=xe:_.style.backgroundColor="",i?.borderWidth&&(_.style.borderWidth=i.borderWidth,_.style.borderStyle="solid"),i?.borderColor&&(_.style.borderColor=i.borderColor),i?.paddingX&&(_.style.paddingLeft=i.paddingX,_.style.paddingRight=i.paddingX),i?.paddingY&&(_.style.paddingTop=i.paddingY,_.style.paddingBottom=i.paddingY),J.appendChild(_);let qt=i?.tooltipText??"Start voice recognition";if((i?.showTooltip??!1)&&qt){let I=m("div","persona-send-button-tooltip");I.textContent=qt,J.appendChild(I)}return{micButton:_,micButtonWrapper:J}},Li=()=>{if(!K||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Pi=(i,g)=>{if(!K)return;let h=K.querySelector("svg");h&&h.remove();let v=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),T=ie(i,v,g,1.5);T&&K.appendChild(T)},js=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Qo=()=>{if(!K)return;Li();let i=o.voiceRecognition??{},g=i.recordingBackgroundColor,h=i.recordingIconColor,v=i.recordingBorderColor;if(js(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let T=K.querySelector("svg");T&&T.setAttribute("stroke",h)}v&&(K.style.borderColor=v),K.setAttribute("aria-label","Stop voice recognition")},vf=()=>{if(!K)return;Li();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),h=i.processingIconName??"loader",v=i.processingIconColor??xt?.color??"",T=i.processingBackgroundColor??xt?.backgroundColor??"",L=i.processingBorderColor??xt?.borderColor??"";js(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=T,K.style.borderColor=L;let J=v||"currentColor";K.style.color=J,Pi(h,J),K.setAttribute("aria-label","Processing voice input"),g==="none"&&(K.style.cursor="default")},wf=()=>{if(!K)return;Li();let i=o.voiceRecognition??{},g=O.getVoiceInterruptionMode(),h=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",v=i.speakingIconName??h,T=i.speakingIconColor??(g==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),L=i.speakingBackgroundColor??(g==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),J=i.speakingBorderColor??(g==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");js(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=L,K.style.borderColor=J;let _=T||"currentColor";K.style.color=_,Pi(v,_);let X=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",X),g==="none"&&(K.style.cursor="default"),g==="barge-in"&&K.classList.add("persona-voice-recording")},Rn=()=>{K&&(js(),xt&&(K.style.backgroundColor=xt.backgroundColor??"",K.style.color=xt.color??"",K.style.borderColor=xt.borderColor??"",Pi(xt.iconName,xt.color||"currentColor"),xt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},qs=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=O.getVoiceStatus(),g=O.getVoiceInterruptionMode();if(g==="none"&&(i==="processing"||i==="speaking"))return;if(g==="cancel"&&(i==="processing"||i==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()});return}O.toggleVoice().then(()=>{Xe.active=O.isVoiceActive(),Xe.manuallyDeactivated=!O.isVoiceActive(),bn(),Pn("user"),O.isVoiceActive()?Qo():Rn()});return}if(Sn){let i=N.value.trim();Xe.manuallyDeactivated=!0,bn(),Xn("user"),i&&(N.value="",N.style.height="auto",O.sendMessage(i))}else Xe.manuallyDeactivated=!1,bn(),zs("user")};ql=qs,K&&(K.addEventListener("click",qs),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Rn()):Xn("system"),K&&K.removeEventListener("click",qs)}));let xf=l.on("assistant:complete",()=>{rc&&(Xe.active||Xe.manuallyDeactivated||rc==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?O.toggleVoice().then(()=>{Xe.active=O.isVoiceActive(),Pn("auto"),O.isVoiceActive()&&Qo()}):zs("auto"))},600))});Ve.push(xf);let Cf=l.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});Ve.push(Cf);let Lc=()=>{ht(!U,"user")},_t=null,jt=null;if(R&&!Y()){let{instance:i,element:g}=pl({config:o,plugins:r,onToggle:Lc});_t=i,i||(jt=g)}_t?t.appendChild(_t.element):jt&&t.appendChild(jt),Fr(),di(),yc(),xi(O.isStreaming()),uc()||(Jt()==="follow"?Gn(!0):dc()),Ju(),$&&(!R||Y()?setTimeout(()=>Ci(),0):U&&setTimeout(()=>Ci(),200));let Nr=()=>{if(Y()){$o(),Fr();return}let i=Ot(o),g=o.launcher?.sidebarMode??!1,h=i||g||(o.launcher?.fullHeight??!1),v=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640,J=v.innerWidth<=L,_=T&&J&&R;try{if(_){Tr(),Mr=Ws();return}let X=!1;V&&(V=!1,Tr(),X=!0);let ae=Ws();if(!X&&ae!==Mr&&(Tr(),X=!0),Mr=ae,X&&li(),!R&&!i){he.style.height="",he.style.width="";return}if(!g&&!i){let re=o?.launcher?.width??o?.launcherWidth??Nn;he.style.width=re,he.style.maxWidth=re}if(Rs(),!h){let pe=v.innerHeight,re=64,xe=o.launcher?.heightOffset??0,Ke=Math.max(200,pe-re),yt=Math.min(640,Ke),at=Math.max(200,yt-xe);he.style.height=`${at}px`}}finally{if($o(),Fr(),U&&R){let ae=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),pe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,xe=Ot(o)&&re&&ae,Ke=pe||re&&ae&&R||xe;if(Ke&&!An){let yt=t.getRootNode(),at=yt instanceof ShadowRoot?yt.host:t.closest(".persona-host");at&&!Cn&&(Cn=ll(at,o.launcher?.zIndex??zt)),An=cl(t.ownerDocument)}else Ke||(Cn?.(),Cn=null,An?.(),An=null)}}};Nr();let Pc=t.ownerDocument.defaultView??window;if(Pc.addEventListener("resize",Nr),Ve.push(()=>Pc.removeEventListener("resize",Nr)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{$o()});i.observe(q),Ve.push(()=>i.disconnect())}ln=le.scrollTop;let Ic=En(le),Af=()=>{let i=le.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??le.ownerDocument.getSelection()},Ii=()=>Dp(Af(),le),Rc=()=>{let i=le.scrollTop,g=En(le),h=g<Ic;if(Ic=g,!_n()){ln=i,tn();return}let{action:v,nextLastScrollTop:T}=Ha({following:en.isFollowing(),currentScrollTop:i,lastScrollTop:ln,nearBottom:io(le,Os),userScrollThreshold:Xu,isAutoScrolling:cn||Fs||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=T,v==="resume"){Ii()||Kn();return}v==="pause"&&Ir()};if(le.addEventListener("scroll",Rc,{passive:!0}),Ve.push(()=>le.removeEventListener("scroll",Rc)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{nf()});i.observe(be),i.observe(le),Ve.push(()=>i.disconnect())}let Wc=()=>{_n()&&en.isFollowing()&&Ii()&&Ir()},Bc=le.ownerDocument;Bc.addEventListener("selectionchange",Wc),Ve.push(()=>{Bc.removeEventListener("selectionchange",Wc)});let Sf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Hc=i=>{_l()&&_n()&&en.isFollowing()&&Sf.has(i.key)&&Ir()},Dc=i=>{if(!_l()||!_n()||!en.isFollowing())return;let g=i.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&Ir()};le.addEventListener("keydown",Hc),le.addEventListener("focusin",Dc),Ve.push(()=>{le.removeEventListener("keydown",Hc),le.removeEventListener("focusin",Dc)});let Fc=i=>{if(!_n())return;let g=Da({following:en.isFollowing(),deltaY:i.deltaY,nearBottom:io(le,Os),resumeWhenNearBottom:!0});g==="pause"?Ir():g==="resume"&&!Ii()&&Kn()};le.addEventListener("wheel",Fc,{passive:!0}),Ve.push(()=>le.removeEventListener("wheel",Fc)),It.addEventListener("click",()=>{Rr(),le.scrollTop=le.scrollHeight,ln=le.scrollTop,Kn(),Gn(!0),tn()}),Ve.push(()=>It.remove()),Ve.push(()=>{ic(),Rr()});let Nc=()=>{S&&(ho&&(S.removeEventListener("click",ho),ho=null),F()?(S.style.display="",ho=()=>{ht(!1,"user")},S.addEventListener("click",ho)):S.style.display="none")};Nc(),(()=>{let{clearChatButton:i}=Re;i&&i.addEventListener("click",()=>{O.clearMessages(),yo.clear(),Kn(),rr(Re.composerOverlay);try{localStorage.removeItem(vr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&yi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Se?.clear(),je?.reset(),Ne?.update()})})(),Le&&Le.addEventListener("submit",Ac),N?.addEventListener("keydown",Tc),N?.addEventListener("input",Sc),N?.addEventListener("paste",Ec);let Oc=t.ownerDocument??document;Oc.addEventListener("keydown",Mc,!0);let _c="persona-attachment-drop-active",Or=0,Ri=()=>{Or=0,fe.classList.remove(_c)},Jo=()=>o.attachments?.enabled===!0&&Mt!==null,$c=i=>{!ei(i.dataTransfer)||!Jo()||(Or++,Or===1&&fe.classList.add(_c))},Uc=i=>{!ei(i.dataTransfer)||!Jo()||(Or--,Or<=0&&Ri())},zc=i=>{!ei(i.dataTransfer)||!Jo()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},jc=i=>{if(!ei(i.dataTransfer)||!Jo())return;i.preventDefault(),i.stopPropagation(),Ri();let g=Array.from(i.dataTransfer.files??[]);g.length!==0&&Mt.handleFiles(g)},Qn=!0;fe.addEventListener("dragenter",$c,Qn),fe.addEventListener("dragleave",Uc,Qn),t.addEventListener("dragover",zc,Qn),t.addEventListener("drop",jc,Qn);let Vs=t.ownerDocument,qc=i=>{Jo()&&i.preventDefault()},Vc=i=>{Jo()&&i.preventDefault()};Vs.addEventListener("dragover",qc),Vs.addEventListener("drop",Vc),Ve.push(()=>{Le&&Le.removeEventListener("submit",Ac),N?.removeEventListener("keydown",Tc),N?.removeEventListener("input",Sc),N?.removeEventListener("paste",Ec),Oc.removeEventListener("keydown",Mc,!0)}),Ve.push(()=>{fe.removeEventListener("dragenter",$c,Qn),fe.removeEventListener("dragleave",Uc,Qn),t.removeEventListener("dragover",zc,Qn),t.removeEventListener("drop",jc,Qn),Vs.removeEventListener("dragover",qc),Vs.removeEventListener("drop",Vc),Ri()}),Ve.push(()=>{O.cancel()}),_t?Ve.push(()=>{_t?.destroy()}):jt&&Ve.push(()=>{jt?.remove()});let Rt={update(i){let g=o.toolCall,h=o.messageActions,v=o.layout?.messages,T=o.colorScheme,L=o.loadingIndicator,J=o.iterationDisplay,_=o.features?.showReasoning,X=o.features?.showToolCalls,ae=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o={...o,...i},Bs(),ss(t,o),xs(t,o),Cs(t,o),Ln(),o.colorScheme!==T&&oc();let xe=Ml.getForInstance(o.plugins);r.length=0,r.push(...xe),R=o.launcher?.enabled??!0,D=o.launcher?.autoExpand??!1,ne=o.features?.showReasoning??!0,me=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Ke=Jt();ee=o.features?.scrollBehavior??{},Ke!==Jt()&&(Rr(),Kn()),jl(),tn();let yt=Z;if(Z=o.features?.showEventStreamToggle??!1,Z&&!yt){if(Se||(ge=new vs(we),Se=new bs(Me,ge),je=je??new ws,ge.open().then(()=>Se?.restore()).catch(()=>{}),O.setSSEEventCallback((te,nt)=>{o.onSSEEvent?.(te,nt),je?.processEvent(te,nt),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(nt)})})),!st&&H){let te=o.features?.eventStream?.classNames,nt="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?.toggleButton?" "+te.toggleButton:"");st=m("button",nt),st.style.width="28px",st.style.height="28px",st.style.color=Xt.actionIconColor,st.type="button",st.setAttribute("aria-label","Event Stream"),st.title="Event Stream";let St=ie("activity","18px","currentColor",1.5);St&&st.appendChild(St);let Ge=Re.clearChatButtonWrapper,dt=Re.closeButtonWrapper,Ut=Ge||dt;Ut&&Ut.parentNode===H?H.insertBefore(st,Ut):H.appendChild(st),st.addEventListener("click",()=>{Ie?Ar():ri()})}}else!Z&&yt&&(Ar(),st&&(st.remove(),st=null),Se?.clear(),ge?.destroy(),Se=null,ge=null,je?.reset(),je=null);if(o.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),o.launcher?.enabled===!1&&jt&&(jt.remove(),jt=null),o.launcher?.enabled!==!1&&!_t&&!jt){let{instance:te,element:nt}=pl({config:o,plugins:r,onToggle:Lc});_t=te,te||(jt=nt),t.appendChild(nt)}_t&&_t.update(o),B&&o.launcher?.title!==void 0&&(B.textContent=o.launcher.title),G&&o.launcher?.subtitle!==void 0&&(G.textContent=o.launcher.subtitle);let at=o.layout?.header;if(at?.layout!==C&&H){let te=at?za(o,at,{showClose:F(),onClose:()=>ht(!1,"user")}):Fo({config:o,showClose:F(),onClose:()=>ht(!1,"user")});gt.replaceHeader(te),H=gt.header.element,k=gt.header.iconHolder,B=gt.header.headerTitle,G=gt.header.headerSubtitle,S=gt.header.closeButton,C=at?.layout}else if(at&&(k&&(k.style.display=at.showIcon===!1?"none":""),B&&(B.style.display=at.showTitle===!1?"none":""),G&&(G.style.display=at.showSubtitle===!1?"none":""),S&&(S.style.display=at.showCloseButton===!1?"none":""),Re.clearChatButtonWrapper)){let te=at.showClearChat;if(te!==void 0){Re.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:nt}=Re;nt&&!nt.classList.contains("persona-absolute")&&(te?nt.classList.remove("persona-ml-auto"):nt.classList.add("persona-ml-auto"))}}let Ht=o.layout?.showHeader!==!1;H&&(H.style.display=Ht?"":"none");let I=o.layout?.showFooter!==!1;q&&(q.style.display=I?"":"none"),$o(),tn(),R!==z?R?ht(D,"auto"):(U=!0,Fr()):D!==j&&ht(D,"auto"),j=D,z=R,Nr(),Nc();let $e=JSON.stringify(i.toolCall)!==JSON.stringify(g),Tt=JSON.stringify(o.messageActions)!==JSON.stringify(h),ut=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),Ct=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,bt=o.iterationDisplay!==J,$t=(o.features?.showReasoning??!0)!==(_??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);($e||Tt||ut||Ct||bt||$t)&&O&&(pi++,Wr(be,O.getMessages(),Ae));let ft=o.features?.streamAnimation?.type;if(ft!==re&&ft&&ft!=="none"){let te=mr(ft,o.features?.streamAnimation?.plugins);te&&_a(te,t)}let ue=o.launcher??{},At=ue.headerIconHidden??!1,Vt=o.layout?.header?.showIcon,Dt=At||Vt===!1,rt=ue.headerIconName,qe=ue.headerIconSize??"48px";if(k){let te=fe.querySelector(".persona-border-b-persona-divider"),nt=te?.querySelector(".persona-flex-col");if(Dt)k.style.display="none",te&&nt&&!te.contains(nt)&&te.insertBefore(nt,te.firstChild);else{if(k.style.display="",k.style.height=qe,k.style.width=qe,te&&nt&&(te.contains(k)?k.nextSibling!==nt&&(k.remove(),te.insertBefore(k,nt)):te.insertBefore(k,nt)),rt){let Ge=parseFloat(qe)||24,dt=ie(rt,Ge*.6,"currentColor",1);dt?k.replaceChildren(dt):k.textContent=ue.agentIconText??"\u{1F4AC}"}else if(ue.iconUrl){let Ge=k.querySelector("img");if(Ge)Ge.src=ue.iconUrl,Ge.style.height=qe,Ge.style.width=qe;else{let dt=document.createElement("img");dt.src=ue.iconUrl,dt.alt="",dt.className="persona-rounded-xl persona-object-cover",dt.style.height=qe,dt.style.width=qe,k.replaceChildren(dt)}}else{let Ge=k.querySelector("svg"),dt=k.querySelector("img");(Ge||dt)&&k.replaceChildren(),k.textContent=ue.agentIconText??"\u{1F4AC}"}let St=k.querySelector("img");St&&(St.style.height=qe,St.style.width=qe)}}let Ze=o.layout?.header?.showTitle,Lt=o.layout?.header?.showSubtitle;if(B&&(B.style.display=Ze===!1?"none":""),G&&(G.style.display=Lt===!1?"none":""),S){o.layout?.header?.showCloseButton===!1?S.style.display="none":S.style.display="";let nt=ue.closeButtonSize??"32px",St=ue.closeButtonPlacement??"inline";S.style.height=nt,S.style.width=nt;let{closeButtonWrapper:Ge}=Re,dt=St==="top-right",Ut=Ge?.classList.contains("persona-absolute");if(Ge&&dt!==Ut)if(Ge.remove(),dt)Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",fe.style.position="relative",fe.appendChild(Ge);else{let ze=ue.clearChat?.placement??"inline",Nt=ue.clearChat?.enabled??!0;Ge.className=Nt&&ze==="inline"?"":"persona-ml-auto";let Zt=fe.querySelector(".persona-border-b-persona-divider");Zt&&Zt.appendChild(Ge)}if(S.style.color=ue.closeButtonColor||Xt.actionIconColor,ue.closeButtonBackgroundColor?(S.style.backgroundColor=ue.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let ze=ue.closeButtonBorderWidth||"0px",Nt=ue.closeButtonBorderColor||"transparent";S.style.border=`${ze} solid ${Nt}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");ue.closeButtonBorderRadius?(S.style.borderRadius=ue.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(S.style.paddingLeft=ue.closeButtonPaddingX,S.style.paddingRight=ue.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),ue.closeButtonPaddingY?(S.style.paddingTop=ue.closeButtonPaddingY,S.style.paddingBottom=ue.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let on=ue.closeButtonIconName??"x",vn=ue.closeButtonIconText??"\xD7";S.innerHTML="";let Kt=ie(on,"28px","currentColor",1);Kt?S.appendChild(Kt):S.textContent=vn;let Et=ue.closeButtonTooltipText??"Close chat",rn=ue.closeButtonShowTooltip??!0;if(S.setAttribute("aria-label",Et),Ge&&(Ge._cleanupTooltip&&(Ge._cleanupTooltip(),delete Ge._cleanupTooltip),rn&&Et)){let ze=null,Nt=()=>{if(ze||!S)return;let Mo=S.ownerDocument,zr=Mo.body;if(!zr)return;ze=Tn(Mo,"div","persona-clear-chat-tooltip"),ze.textContent=Et;let jr=Tn(Mo,"div");jr.className="persona-clear-chat-tooltip-arrow",ze.appendChild(jr);let Eo=S.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(so),ze.style.left=`${Eo.left+Eo.width/2}px`,ze.style.top=`${Eo.top-8}px`,ze.style.transform="translate(-50%, -100%)",zr.appendChild(ze)},Zt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};Ge.addEventListener("mouseenter",Nt),Ge.addEventListener("mouseleave",Zt),S.addEventListener("focus",Nt),S.addEventListener("blur",Zt),Ge._cleanupTooltip=()=>{Zt(),Ge&&(Ge.removeEventListener("mouseenter",Nt),Ge.removeEventListener("mouseleave",Zt)),S&&(S.removeEventListener("focus",Nt),S.removeEventListener("blur",Zt))}}}let{clearChatButton:De,clearChatButtonWrapper:et}=Re;if(De){let te=ue.clearChat??{},nt=te.enabled??!0,St=o.layout?.header?.showClearChat,Ge=St!==void 0?St:nt,dt=te.placement??"inline";if(et){et.style.display=Ge?"":"none";let{closeButtonWrapper:Ut}=Re;!Y()&&Ut&&!Ut.classList.contains("persona-absolute")&&(Ge?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let on=dt==="top-right",vn=et.classList.contains("persona-absolute");if(!Y()&&on!==vn&&Ge){if(et.remove(),on)et.className="persona-absolute persona-top-4 persona-z-50",et.style.right="48px",fe.style.position="relative",fe.appendChild(et);else{et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",et.style.right="";let Et=fe.querySelector(".persona-border-b-persona-divider"),rn=Re.closeButtonWrapper;Et&&rn&&rn.parentElement===Et?Et.insertBefore(et,rn):Et&&Et.appendChild(et)}let Kt=Re.closeButtonWrapper;Kt&&!Kt.classList.contains("persona-absolute")&&(on?Kt.classList.add("persona-ml-auto"):Kt.classList.remove("persona-ml-auto"))}}if(Ge){if(!Y()){let ze=te.size??"32px";De.style.height=ze,De.style.width=ze}let Ut=te.iconName??"refresh-cw",on=te.iconColor??"";De.style.color=on||Xt.actionIconColor,De.innerHTML="";let vn=Y()?"14px":"20px",Kt=ie(Ut,vn,"currentColor",2);if(Kt&&De.appendChild(Kt),te.backgroundColor?(De.style.backgroundColor=te.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let ze=te.borderWidth||"0px",Nt=te.borderColor||"transparent";De.style.border=`${ze} solid ${Nt}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");te.borderRadius?(De.style.borderRadius=te.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),te.paddingX?(De.style.paddingLeft=te.paddingX,De.style.paddingRight=te.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),te.paddingY?(De.style.paddingTop=te.paddingY,De.style.paddingBottom=te.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Et=te.tooltipText??"Clear chat",rn=te.showTooltip??!0;if(De.setAttribute("aria-label",Et),et&&(et._cleanupTooltip&&(et._cleanupTooltip(),delete et._cleanupTooltip),rn&&Et)){let ze=null,Nt=()=>{if(ze||!De)return;let Mo=De.ownerDocument,zr=Mo.body;if(!zr)return;ze=Tn(Mo,"div","persona-clear-chat-tooltip"),ze.textContent=Et;let jr=Tn(Mo,"div");jr.className="persona-clear-chat-tooltip-arrow",ze.appendChild(jr);let Eo=De.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(so),ze.style.left=`${Eo.left+Eo.width/2}px`,ze.style.top=`${Eo.top-8}px`,ze.style.transform="translate(-50%, -100%)",zr.appendChild(ze)},Zt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};et.addEventListener("mouseenter",Nt),et.addEventListener("mouseleave",Zt),De.addEventListener("focus",Nt),De.addEventListener("blur",Zt),et._cleanupTooltip=()=>{Zt(),et&&(et.removeEventListener("mouseenter",Nt),et.removeEventListener("mouseleave",Zt)),De&&(De.removeEventListener("focus",Nt),De.removeEventListener("blur",Zt))}}}}let nn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[kl],Ao=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[As.message,As.messageAndClick];M=Ll({parsers:nn,handlers:Ao,getSessionMetadata:b,updateSessionMetadata:x,emit:l.emit,documentRef:typeof document<"u"?document:null}),Ae=Eu(o,M,Ee),O.updateConfig(o),Wr(be,O.getMessages(),Ae),di(),yc(),xi(O.isStreaming());let Kc=o.voiceRecognition?.enabled===!0,Ks=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(Kc&&(Ks||Pt))if(!K||!Ue){let te=bf(o.voiceRecognition,o.sendButton);te&&(K=te.micButton,Ue=te.micButtonWrapper,We.insertBefore(Ue,Fe),K.addEventListener("click",qs),K.disabled=O.isStreaming())}else{let te=o.voiceRecognition??{},nt=o.sendButton??{},St=te.iconName??"mic",Ge=nt.size??"40px",dt=te.iconSize??Ge,Ut=parseFloat(dt)||24;K.style.width=dt,K.style.height=dt,K.style.minWidth=dt,K.style.minHeight=dt;let on=te.iconColor??nt.textColor??"currentColor";K.innerHTML="";let vn=ie(St,Ut,on,2);vn?K.appendChild(vn):K.textContent="\u{1F3A4}";let Kt=te.backgroundColor??nt.backgroundColor;Kt?K.style.backgroundColor=Kt:K.style.backgroundColor="",on?K.style.color=on:K.style.color="var(--persona-text, #111827)",te.borderWidth?(K.style.borderWidth=te.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),te.borderColor?K.style.borderColor=te.borderColor:K.style.borderColor="",te.paddingX?(K.style.paddingLeft=te.paddingX,K.style.paddingRight=te.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),te.paddingY?(K.style.paddingTop=te.paddingY,K.style.paddingBottom=te.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let Et=Ue?.querySelector(".persona-send-button-tooltip"),rn=te.tooltipText??"Start voice recognition";if((te.showTooltip??!1)&&rn)if(Et)Et.textContent=rn,Et.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=rn,Ue?.insertBefore(Nt,K)}else Et&&(Et.style.display="none");Ue.style.display="",K.disabled=O.isStreaming()}else K&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()&&O.toggleVoice():Sn&&Xn());if(o.attachments?.enabled===!0)if(!He||!Ce){let te=o.attachments??{},St=(o.sendButton??{}).size??"40px";Je||(Je=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Je.style.display="none",Le.insertBefore(Je,N)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=(te.allowedTypes??Fn).join(","),Pe.multiple=(te.maxFiles??4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),Le.insertBefore(Pe,N)),He=m("div","persona-send-button-wrapper"),Ce=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ce.type="button",Ce.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let Ge=te.buttonIconName??"paperclip",dt=St,Ut=parseFloat(dt)||40,on=Math.round(Ut*.6);Ce.style.width=dt,Ce.style.height=dt,Ce.style.minWidth=dt,Ce.style.minHeight=dt,Ce.style.fontSize="18px",Ce.style.lineHeight="1",Ce.style.backgroundColor="transparent",Ce.style.color="var(--persona-primary, #111827)",Ce.style.border="none",Ce.style.borderRadius="6px",Ce.style.transition="background-color 0.15s ease",Ce.addEventListener("mouseenter",()=>{Ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ce.addEventListener("mouseleave",()=>{Ce.style.backgroundColor="transparent"});let vn=ie(Ge,on,"currentColor",1.5);vn?Ce.appendChild(vn):Ce.textContent="\u{1F4CE}",Ce.addEventListener("click",rn=>{rn.preventDefault(),Pe?.click()}),He.appendChild(Ce);let Kt=te.buttonTooltipText??"Attach file",Et=m("div","persona-send-button-tooltip");Et.textContent=Kt,He.appendChild(Et),tt.append(He),!Mt&&Pe&&Je&&(Mt=os.fromConfig(te),Mt.setPreviewsContainer(Je),Pe.addEventListener("change",async()=>{Mt&&Pe?.files&&(await Mt.handleFileSelect(Pe.files),Pe.value="")})),fe.querySelector(".persona-attachment-drop-overlay")||fe.appendChild(ku(te.dropOverlay))}else{He.style.display="";let te=o.attachments??{};Pe&&(Pe.accept=(te.allowedTypes??Fn).join(","),Pe.multiple=(te.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else He&&(He.style.display="none"),Mt&&Mt.clearAttachments(),fe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},_r=Ft.useIcon??!1,Xs=Ft.iconText??"\u2191",Yo=Ft.iconName,$r=Ft.tooltipText??"Send message",Wi=Ft.showTooltip??!1,So=Ft.size??"40px",Wn=Ft.backgroundColor,To=Ft.textColor;if(_r){if(oe.style.width=So,oe.style.height=So,oe.style.minWidth=So,oe.style.minHeight=So,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.innerHTML="",To?oe.style.color=To:oe.style.color="var(--persona-button-primary-fg, #ffffff)",Yo){let te=parseFloat(So)||24,nt=To?.trim()||"currentColor",St=ie(Yo,te,nt,2);St?oe.appendChild(St):oe.textContent=Xs}else oe.textContent=Xs;oe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Wn?(oe.style.backgroundColor=Wn,oe.classList.remove("persona-bg-persona-primary")):(oe.style.backgroundColor="",oe.classList.add("persona-bg-persona-primary"))}else oe.textContent=o.copy?.sendButtonLabel??"Send",oe.style.width="",oe.style.height="",oe.style.minWidth="",oe.style.minHeight="",oe.style.fontSize="",oe.style.lineHeight="",oe.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",Wn?(oe.style.backgroundColor=Wn,oe.classList.remove("persona-bg-persona-accent")):oe.classList.add("persona-bg-persona-accent"),To?oe.style.color=To:oe.classList.add("persona-text-white");Ft.borderWidth?(oe.style.borderWidth=Ft.borderWidth,oe.style.borderStyle="solid"):(oe.style.borderWidth="",oe.style.borderStyle=""),Ft.borderColor?oe.style.borderColor=Ft.borderColor:oe.style.borderColor="",Ft.paddingX?(oe.style.paddingLeft=Ft.paddingX,oe.style.paddingRight=Ft.paddingX):(oe.style.paddingLeft="",oe.style.paddingRight=""),Ft.paddingY?(oe.style.paddingTop=Ft.paddingY,oe.style.paddingBottom=Ft.paddingY):(oe.style.paddingTop="",oe.style.paddingBottom="");let Ur=Fe?.querySelector(".persona-send-button-tooltip");if(Wi&&$r)if(Ur)Ur.textContent=$r,Ur.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=$r,Fe?.insertBefore(te,oe)}else Ur&&(Ur.style.display="none");let Qs=o.layout?.contentMaxWidth??(Y()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);Qs?(be.style.maxWidth=Qs,be.style.marginLeft="auto",be.style.marginRight="auto",be.style.width="100%",Le&&(Le.style.maxWidth=Qs,Le.style.marginLeft="auto",Le.style.marginRight="auto"),vt&&(vt.style.maxWidth=Qs,vt.style.marginLeft="auto",vt.style.marginRight="auto")):(be.style.maxWidth="",be.style.marginLeft="",be.style.marginRight="",be.style.width="",Le&&(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight=""),vt&&(vt.style.maxWidth="",vt.style.marginLeft="",vt.style.marginRight=""));let Jn=o.statusIndicator??{},Tf=Jn.visible??!0;if(E.style.display=Tf?"":"none",O){let te=O.getStatus();kt(E,(St=>St==="idle"?Jn.idleText??Wt.idle:St==="connecting"?Jn.connectingText??Wt.connecting:St==="connected"?Jn.connectedText??Wt.connected:St==="error"?Jn.errorText??Wt.error:Wt[St])(te),Jn,te)}E.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mf=Jn.align==="left"?"persona-text-left":Jn.align==="center"?"persona-text-center":"persona-text-right";E.classList.add(Mf)},open(){F()&&ht(!0,"api")},close(){F()&&ht(!1,"api")},toggle(){F()&&ht(!U,"api")},reconnect(){O.reconnectNow()},clearChat(){kn=!1,O.clearMessages(),yo.clear(),Kn();try{localStorage.removeItem(vr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${vr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==vr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&yi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},M.syncFromMetadata(),Se?.clear(),je?.reset(),Ne?.update()},setMessage(i){return!N||O.isStreaming()?!1:(!U&&F()&&ht(!0,"system"),N.value=i,N.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(O.isStreaming())return!1;let g=i?.trim()||N.value.trim();return g?(!U&&F()&&ht(!0,"system"),N.value="",N.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return O.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(O.isVoiceActive()||(!U&&F()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,bn(),O.toggleVoice().then(()=>{Xe.active=O.isVoiceActive(),Pn("user"),O.isVoiceActive()&&Qo()})),!0):Sn?!0:kc()?(!U&&F()&&ht(!0,"system"),Xe.manuallyDeactivated=!1,bn(),zs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,bn(),Pn("user"),Rn()}),!0):!1:Sn?(Xe.manuallyDeactivated=!0,bn(),Xn("user"),!0):!1},injectMessage(i){return!U&&F()&&ht(!0,"system"),O.injectMessage(i)},injectAssistantMessage(i){!U&&F()&&ht(!0,"system");let g=O.injectAssistantMessage(i);return de&&(de=!1,ye&&(clearTimeout(ye),ye=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(i){return!U&&F()&&ht(!0,"system"),O.injectUserMessage(i)},injectSystemMessage(i){return!U&&F()&&ht(!0,"system"),O.injectSystemMessage(i)},injectMessageBatch(i){return!U&&F()&&ht(!0,"system"),O.injectMessageBatch(i)},injectComponentDirective(i){return!U&&F()&&ht(!0,"system"),O.injectComponentDirective(i)},injectTestMessage(i){!U&&F()&&ht(!0,"system"),O.injectTestEvent(i)},async connectStream(i,g){return O.connectStream(i,g)},__pushEventStreamEvent(i){Se&&(je?.processEvent(i.type,i.payload),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!Z||!Se||ri()},hideEventStream(){Ie&&Ar()},isEventStreamVisible(){return Ie},showArtifacts(){Qt(o)&&(kn=!1,Uo=!0,Ln(),Ye?.setMobileOpen(!0))},hideArtifacts(){Qt(o)&&(kn=!0,Ln())},upsertArtifact(i){return Qt(o)?(Lo(o.features?.artifacts,i.artifactType)==="panel"&&(kn=!1,Uo=!0),O.upsertArtifact(i)):null},selectArtifact(i){Qt(o)&&O.selectArtifact(i)},clearArtifacts(){Qt(o)&&O.clearArtifacts()},getArtifacts(){return O?.getArtifacts()??[]},getSelectedArtifactId(){return O?.getSelectedArtifactId()??null},focusInput(){return R&&!U&&!Y()||!N?!1:(N.focus(),!0)},async resolveApproval(i,g,h){let T=O.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!T?.approval)throw new Error(`Approval not found: ${i}`);if(T.approval.toolType==="webmcp"){O.resolveWebMcpApproval(T.id,g);return}return O.resolveApproval(T.approval,g,h)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(i){x(i)},on(i,g){return l.on(i,g)},off(i,g){l.off(i,g)},isOpen(){return F()&&U},isVoiceActive(){return Xe.active},toggleReadAloud(i){O.toggleReadAloud(i)},stopReadAloud(){O.stopSpeaking()},getReadAloudState(i){return O.getReadAloudState(i)},onReadAloudChange(i){return O.onReadAloudChange(i)},getState(){return{open:F()&&U,launcherEnabled:R,voiceActive:Xe.active,streaming:O.isStreaming()}},showCSATFeedback(i){!U&&F()&&ht(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let h=Su({onSubmit:async(v,T)=>{O.isClientTokenMode()&&await O.submitCSATFeedback(v,T),i?.onSubmit?.(v,T)},onDismiss:i?.onDismiss,...i});be.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!U&&F()&&ht(!0,"system");let g=be.querySelector(".persona-feedback-container");g&&g.remove();let h=Tu({onSubmit:async(v,T)=>{O.isClientTokenMode()&&await O.submitNPSFeedback(v,T),i?.onSubmit?.(v,T)},onDismiss:i?.onDismiss,...i});be.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,g){return O.submitCSATFeedback(i,g)},async submitNPSFeedback(i,g){return O.submitNPSFeedback(i,g)},destroy(){Ti(),wo!=null&&(clearInterval(wo),wo=null),Ve.forEach(i=>i()),ke.remove(),lt?.remove(),_t?.destroy(),jt?.remove(),ho&&S.removeEventListener("click",ho)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,g={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ve.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=_=>{let X=_.detail;(!X?.instanceId||X.instanceId===i)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ve.push(()=>{window.removeEventListener("persona:focusInput",g)}),Z){let _=ae=>{let pe=ae.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.showEventStream()},X=ae=>{let pe=ae.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",X),Ve.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",X)})}let h=_=>{let X=_.detail;(!X?.instanceId||X.instanceId===i)&&Rt.showArtifacts()},v=_=>{let X=_.detail;(!X?.instanceId||X.instanceId===i)&&Rt.hideArtifacts()},T=_=>{let X=_.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Rt.upsertArtifact(X.artifact)},L=_=>{let X=_.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Rt.selectArtifact(X.id)},J=_=>{let X=_.detail;(!X?.instanceId||X.instanceId===i)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",J),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",J)})}let pn=hy(o.persistState);if(pn&&F()){let i=yy(pn.storage),g=`${pn.keyPrefix}widget-open`,h=`${pn.keyPrefix}widget-voice`,v=`${pn.keyPrefix}widget-voice-mode`;if(i){let T=pn.persist?.openState&&i.getItem(g)==="true",L=pn.persist?.voiceState&&i.getItem(h)==="true",J=pn.persist?.voiceState&&i.getItem(v)==="true";if(T&&setTimeout(()=>{Rt.open(),setTimeout(()=>{if(L||J)Rt.startVoiceRecognition();else if(pn.persist?.focusInput){let _=t.querySelector("textarea");_&&_.focus()}},100)},0),pn.persist?.openState&&(l.on("widget:opened",()=>{i.setItem(g,"true")}),l.on("widget:closed",()=>{i.setItem(g,"false")})),pn.persist?.voiceState&&(l.on("voice:state",_=>{i.setItem(h,_.active?"true":"false")}),l.on("user:message",_=>{i.setItem(v,_.viaVoice?"true":"false")})),pn.clearOnChatClear){let _=()=>{i.removeItem(g),i.removeItem(h),i.removeItem(v)},X=()=>_();window.addEventListener("persona:clear-chat",X),Ve.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(w&&F()&&setTimeout(()=>{Rt.open()},0),Ko(),!Gu){let i=ea(()=>{O&&(pi++,yo.clear(),Wr(be,O.getMessages(),Ae))});Ve.push(i)}return Rt};var Pu=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},by=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},vy=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},wy=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},Iu=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},Dl=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},Ru=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Dl(t)},Wl=t=>{t.style.transition=""},Bl=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Hl=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},ti=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},xy=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},Cy=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Ay=t=>{let e=dr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Gt(e,r)??r;return{inset:o(n?.inset,Ca),canvasBackground:o(n?.canvasBackground,Aa)}},Wu=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},Sy=(t,e,n,o,r,s,a,l)=>{let p=fn(s),d=p.reveal==="push",c=l!=null,u=l?.inset??"",w=l?.canvasBackground??"";xy(t,e,n,o,d),Cy(t,e,n,o,p.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,P=f!=null?f.innerWidth<=x:!1;if(b&&P&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Bl(e),Wl(o),Ru(o),Hl(n),ti(r,o),Wu(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??zt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),Ru(o),by(o,p.maxHeight),Wu(o,c&&a,u,w),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Bl(e),Wl(o),Hl(n),ti(r,o);let M=p.animate?"transform 180ms ease":"none",R=p.side==="right"?"translateX(100%)":"translateX(-100%)",D=a?"translateX(0)":R;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=D,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Wl(o),Dl(o),ti(r,o);let M=Pu(p.width,t.clientWidth),R=Math.max(0,t.clientWidth),D=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?a?-M:0:a?0:-M;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+M}px`,e.style.transition=D,e.style.marginLeft=`${$}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Bl(e),Dl(o),Hl(n),ti(r,o);let M=p.reveal==="emerge";M?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let R=a?p.width:"0px",D=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",$=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${R}`,o.style.width=R,o.style.maxWidth=R,o.style.minWidth=R,o.style.minHeight="0",vy(o,p.maxHeight),o.style.overflow=M||$?"hidden":"visible",o.style.transition=D,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let j=c?`calc(${Pu(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=j,r.style.minWidth=j,r.style.maxWidth=j,r.style.boxSizing="border-box"}}},Ty=(t,e)=>{let n=t.ownerDocument.createElement("div");return Iu(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Iu(n,o)},destroy(){n.remove()}}},My=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,t),p.appendChild(t);let w=null,f=()=>{w?.disconnect(),w=null},b=null,x=()=>{b=e?.launcher?.detachedPanel===!0?Ay(e):null};x();let P=()=>{Sy(a,l,p,d,c,e,u,b)},W=null,M=()=>{W?.(),W=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(W=Sa(()=>{x(),P()}))},R=()=>{f(),fn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(w=new ResizeObserver(()=>{P()}),w.observe(a)))},D=!1,$=()=>{P(),R(),u&&!D&&a.dataset.personaDockMobileFullscreen!=="true"&&(D=!0,wy(a,fn(e)))},j=a.ownerDocument.defaultView,z=()=>{$()};return j?.addEventListener("resize",z),fn(e).reveal==="push"?(l.appendChild(p),l.appendChild(d),a.appendChild(l)):(a.appendChild(p),a.appendChild(d)),$(),M(),{mode:"docked",host:c,shell:a,syncWidgetState(C){let V=C.launcherEnabled?C.open:!0;u!==V&&(u=V,$())},updateConfig(C){e=C,(e?.launcher?.enabled??!0)===!1&&(u=!0),x(),$(),M()},destroy(){j?.removeEventListener("resize",z),W?.(),W=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},Bu=(t,e)=>Ot(e)?My(t,e):Ty(t,e);var Ss={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Hu=.15,Du=1.5,Fl="persona-preview-shell-theme",Ey={load:()=>null,save:()=>{},clear:()=>{}},ky=["How do I get started?","Pricing & plans","Talk to support"];function Nl(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ly(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Fu(t){let e=Ly(t);return`* { box-sizing: border-box; }
112
135
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
113
- html { color-scheme: ${n}; }
136
+ html { color-scheme: ${t}; }
114
137
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
115
138
  .preview-iframe-mock { min-height: 100%; }
116
139
  .preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
@@ -132,7 +155,7 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
132
155
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
133
156
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
134
157
  .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 Gg(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(Rl);r||(r=t.createElement("style"),r.id=Rl,t.head.appendChild(r)),r.textContent=Kg(e)}var jb=`
158
+ .preview-workspace-card.short { height: 96px; }`}function Nu(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Fl);o||(o=n.createElement("style"),o.id=Fl,n.head.appendChild(o)),o.textContent=Fu(e)}var Py=`
136
159
  <div class="preview-iframe-mock" aria-hidden="true">
137
160
  <div class="preview-iframe-chrome">
138
161
  <span class="preview-iframe-dot"></span>
@@ -151,7 +174,7 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
151
174
  <div class="preview-iframe-line body"></div>
152
175
  <div class="preview-iframe-line body"></div>
153
176
  </div>
154
- </div>`,Vb=`
177
+ </div>`,Iy=`
155
178
  <div class="preview-workspace-content-shell" aria-hidden="true">
156
179
  <div class="preview-iframe-line hero"></div>
157
180
  <div class="preview-iframe-line body"></div>
@@ -164,9 +187,9 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
164
187
  <div class="preview-workspace-card short"></div>
165
188
  <div class="preview-workspace-card short"></div>
166
189
  </div>
167
- </div>`;function Qg(n,e,t,r){let o=`
168
- ${jb}
169
- <div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
190
+ </div>`;function Ou(t,e,n,o){let r=`
191
+ ${Py}
192
+ <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
170
193
  <div class="preview-workspace-shell">
171
194
  <div class="preview-workspace-topbar">
172
195
  <div class="preview-workspace-topbar-left">
@@ -176,8 +199,8 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
176
199
  <span class="preview-workspace-topbar-pill"></span>
177
200
  </div>
178
201
  <div class="preview-workspace-body">
179
- <div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
180
- ${Vb}
202
+ <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
203
+ ${Iy}
181
204
  </div>
182
205
  </div>
183
206
  </div>`;return`<!DOCTYPE html>
@@ -185,16 +208,16 @@ _Details: ${t.message}_`:r}var ra=n=>({isError:!0,content:[{type:"text",text:n}]
185
208
  <head>
186
209
  <meta charset="UTF-8">
187
210
  <meta name="viewport" content="width=device-width, initial-scale=1">
188
- <link rel="stylesheet" href="${Wl(r)}">
189
- <style id="${Rl}">${Kg(e)}</style>
211
+ <link rel="stylesheet" href="${Nl(o)}">
212
+ <style id="${Fl}">${Fu(e)}</style>
190
213
  </head>
191
214
  <body>
192
- ${t?s:o}
215
+ ${n?s:r}
193
216
  </body>
194
- </html>`}var Kb=()=>[{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()}],Gb=n=>{var e,t,r,o,s,a,l,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=(l=n==null?void 0:n.features)==null?void 0:l.reasoningDisplay)!=null&&d.activePreview)};function Qb(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"&&Gb(e)?[...Kb(),...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 Xb(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:qb:n.suggestionChips,initialMessages:Qb(e,n,t),storageAdapter:Ub};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Jb(n,e){var r,o;let t=n.theme?jo(n.theme,{validate:!1}):jo();return{...Bt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ps(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Xb(Jb(n,e),t,(o=n.appendedMessages)!=null?o:[])}function Xg(n){var r,o,s,a,l;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:Ps(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ps(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:(l=n.baselineDarkTheme)!=null?l:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ps(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:Ps(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:Ps(n,t),shellMode:t}]}function Jg(n,e){let t={...e},r=[],o=[],s=null,a=!1,l=1,d=1,c=0;function u(){var E;return(E=t.device)!=null?E:"desktop"}function g(){var E;return(E=t.zoom)!=null?E:l}function h(){var k,_;let E=getComputedStyle(n),H=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),B=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),I=40,S=((k=t.compareMode)!=null?k:"off")!=="off",P=(n.clientWidth-H-I)/(S?2:1),z=n.clientHeight-B-I;if(P<=0||z<=0)return 1;let U=(_=ba[u()])!=null?_:ba.desktop;return Math.min(P/U.w,z/U.h,1)}function m(){var B,I,S;l=h();let E=Math.max(jg,Math.min(Vg,g()));d=E;let H=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let P of H){let z=(B=P.dataset.device)!=null?B:"desktop",U=(I=ba[z])!=null?I:ba.desktop;P.style.width=`${U.w*E}px`,P.style.height=`${U.h*E}px`,z==="mobile"&&(P.style.borderRadius=`${32*E}px`);let k=P.querySelector("iframe");k&&(k.style.width=`${U.w}px`,k.style.height=`${U.h}px`,k.style.transformOrigin="top left",k.style.transition="none",k.style.transform=`scale(${E})`)}(S=t.onScaleChange)==null||S.call(t,E)}function y(){var E;(E=t.onBeforeDestroy)==null||E.call(t);for(let H of r)H.destroy();for(let H of o)H();r=[],o=[]}function w(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function T(){var ee,Pe,Ie,ie;if(a)return;y();let E=++c,H=Xg(t),B=u(),I=((ee=t.compareMode)!=null?ee:"off")!=="off",S=((Pe=t.scene)!=null?Pe:"conversation")==="minimized",P=(Ie=t.widgetCssPath)!=null?Ie:"/widget-dist/widget.css",z=(ie=t.buildSrcdoc)!=null?ie:Qg,U=B==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",k=he=>`<div class="${U}" data-mount-id="${he.mountId}" data-device="${B}" data-shell-mode="${he.shellMode}">
195
- ${I?`<div class="preview-frame-meta"><span class="preview-frame-label">${Wl(he.label)}</span></div>`:""}
196
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${he.mountId}"></iframe>
197
- </div>`,_=I?`<div class="preview-compare-grid">${H.map(he=>`<div class="preview-compare-cell">${k(he)}</div>`).join("")}</div>`:`<div class="preview-single">${k(H[0])}</div>`;t.morphContainer?t.morphContainer(n,_):n.innerHTML=_,m();let O=w(),Z=0,ke=O.length,pe=()=>{var re,oe,de,Ae,$e;if(a||E!==c)return;for(let K of O){let J=K.dataset.mountId;if(!J||!K.contentDocument)continue;let Se=H.find(tt=>tt.mountId===J);if(!Se)continue;let Y=()=>{},le=hn(Se.config),Te=le?(()=>{var X;let tt=(X=K.contentDocument)==null?void 0:X.getElementById(`preview-content-${J}`);if(!tt)return null;let Wt=zg(tt,Se.config),ht=K.contentDocument.createElement("div");ht.id=J,ht.style.height="100%",ht.style.display="flex",ht.style.flexDirection="column",ht.style.flex="1",ht.style.minHeight="0",Wt.host.appendChild(ht);let ot=()=>Wt.syncWidgetState(Ye.getState()),me=Y;return Y=()=>{Wt.destroy(),me()},ht.__syncDock=ot,ht.__hostLayout=Wt,ht})():K.contentDocument.getElementById(J);if(!Te)continue;let Ye=_g(Te,Se.config);if(r.push(Ye),le&&Te.__syncDock){let tt=Te.__syncDock,Wt=Ye.on("widget:opened",tt),ht=Ye.on("widget:closed",tt),ot=Y;Y=()=>{Wt(),ht(),ot()},tt()}o.push(Y),S&&Ye.close()}if(((re=t.scene)!=null?re:"conversation")==="artifact"||(Ae=(de=(oe=t.config)==null?void 0:oe.features)==null?void 0:de.artifacts)!=null&&Ae.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
217
+ </html>`}var Ry=()=>[{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()}],Wy=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function By(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Wy(e)?[...Ry(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Hy(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:ky:t.suggestionChips,initialMessages:By(e,t,n),storageAdapter:Ey};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Dy(t,e){let n=t.theme?Bo(t.theme,{validate:!1}):Bo();return{...pt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function wr(t,e){let n=t.scene??"conversation";return Hy(Dy(t,e),n,t.appendedMessages??[])}function _u(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:wr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:wr(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:wr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:wr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:wr(t,n),shellMode:n}]}function $u(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,p=1,d=0;function c(){return n.device??"desktop"}function u(){return n.zoom??l}function w(){let M=getComputedStyle(t),R=parseFloat(M.paddingLeft)+parseFloat(M.paddingRight),D=parseFloat(M.paddingTop)+parseFloat(M.paddingBottom),$=40,j=(n.compareMode??"off")!=="off",z=(t.clientWidth-R-$)/(j?2:1),C=t.clientHeight-D-$;if(z<=0||C<=0)return 1;let V=Ss[c()]??Ss.desktop;return Math.min(z/V.w,C/V.h,1)}function f(){l=w();let M=Math.max(Hu,Math.min(Du,u()));p=M;let R=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let D of R){let $=D.dataset.device??"desktop",j=Ss[$]??Ss.desktop;D.style.width=`${j.w*M}px`,D.style.height=`${j.h*M}px`,$==="mobile"&&(D.style.borderRadius=`${32*M}px`);let z=D.querySelector("iframe");z&&(z.style.width=`${j.w}px`,z.style.height=`${j.h}px`,z.style.transformOrigin="top left",z.style.transition="none",z.style.transform=`scale(${M})`)}n.onScaleChange?.(M)}function b(){n.onBeforeDestroy?.();for(let M of o)M.destroy();for(let M of r)M();o=[],r=[]}function x(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function P(){if(a)return;b();let M=++d,R=_u(n),D=c(),$=(n.compareMode??"off")!=="off",j=(n.scene??"conversation")==="minimized",z=n.widgetCssPath??"/widget-dist/widget.css",C=n.buildSrcdoc??Ou,V=D==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",Y=Ae=>`<div class="${V}" data-mount-id="${Ae.mountId}" data-device="${D}" data-shell-mode="${Ae.shellMode}">
218
+ ${$?`<div class="preview-frame-meta"><span class="preview-frame-label">${Nl(Ae.label)}</span></div>`:""}
219
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${Ae.mountId}"></iframe>
220
+ </div>`,F=$?`<div class="preview-compare-grid">${R.map(Ae=>`<div class="preview-compare-cell">${Y(Ae)}</div>`).join("")}</div>`:`<div class="preview-single">${Y(R[0])}</div>`;n.morphContainer?n.morphContainer(t,F):t.innerHTML=F,f();let U=x(),de=0,ye=U.length,Ee=()=>{if(a||M!==d)return;for(let ne of U){let me=ne.dataset.mountId;if(!me||!ne.contentDocument)continue;let Z=R.find(ge=>ge.mountId===me);if(!Z)continue;let ce=()=>{},ee=Ot(Z.config),ve=ee?(()=>{let ge=ne.contentDocument?.getElementById(`preview-content-${me}`);if(!ge)return null;let Me=Bu(ge,Z.config),Se=ne.contentDocument.createElement("div");Se.id=me,Se.style.height="100%",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1",Se.style.minHeight="0",Me.host.appendChild(Se);let je=()=>Me.syncWidgetState(we.getState()),Ne=ce;return ce=()=>{Me.destroy(),Ne()},Se.__syncDock=je,Se.__hostLayout=Me,Se})():ne.contentDocument.getElementById(me);if(!ve)continue;let we=Lu(ve,Z.config);if(o.push(we),ee&&ve.__syncDock){let ge=ve.__syncDock,Me=we.on("widget:opened",ge),Se=we.on("widget:closed",ge),je=ce;ce=()=>{Me(),Se(),je()},ge()}r.push(ce),j&&we.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let ne of o)ne.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
198
221
 
199
222
  This is a preview of the artifact sidebar.
200
223
 
@@ -202,4 +225,4 @@ This is a preview of the artifact sidebar.
202
225
 
203
226
  - Markdown rendering
204
227
  - Document toolbar
205
- - Resizable panes`});($e=t.onAfterMount)==null||$e.call(t,{iframes:O,controllers:[...r]})};for(let he of O){let re=he.dataset.mountId;if(!re)continue;let oe=H.find(de=>de.mountId===re);oe&&(he.addEventListener("load",()=>{Z++,Z>=ke&&pe()},{once:!0}),he.srcdoc=z(re,oe.shellMode,hn(oe.config),P))}ke===0&&pe()}function W(){var B;if(a)return;let E=Xg(t);if(r.length!==E.length){T();return}if(E.some(I=>{let S=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${I.mountId}"]`);return!S||S.dataset.shellMode!==I.shellMode})){T();return}r.forEach((I,S)=>{var P;I.update(E[S].config),((P=t.scene)!=null?P:"conversation")==="minimized"&&I.close()});for(let I of E){let S=n.querySelector(`iframe[data-mount-id="${I.mountId}"]`);S&&Gg(S,I.shellMode)}(B=t.onAfterUpdate)==null||B.call(t,{iframes:w(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),T(),{update(E){if(a)return;let H=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},H?T():W()},destroy(){a||(a=!0,y(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},m())},getIframes(){return w()},getScale(){return d},setZoom(E){a||(t={...t,zoom:E},m())}}}0&&(module.exports={createThemePreview});
228
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:U,controllers:[...o]})};for(let Ae of U){let ne=Ae.dataset.mountId;if(!ne)continue;let me=R.find(Z=>Z.mountId===ne);me&&(Ae.addEventListener("load",()=>{de++,de>=ye&&Ee()},{once:!0}),Ae.srcdoc=C(ne,me.shellMode,Ot(me.config),z))}ye===0&&Ee()}function W(){if(a)return;let M=_u(n);if(o.length!==M.length){P();return}if(M.some(D=>{let $=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${D.mountId}"]`);return!$||$.dataset.shellMode!==D.shellMode})){P();return}o.forEach((D,$)=>{D.update(M[$].config),(n.scene??"conversation")==="minimized"&&D.close()});for(let D of M){let $=t.querySelector(`iframe[data-mount-id="${D.mountId}"]`);$&&Nu($,D.shellMode)}n.onAfterUpdate?.({iframes:x(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||f()}),s.observe(t)),P(),{update(M){if(a)return;let R=M.device!==void 0&&M.device!==n.device||M.scene!==void 0&&M.scene!==n.scene||M.compareMode!==void 0&&M.compareMode!==n.compareMode||M.widgetCssPath!==void 0&&M.widgetCssPath!==n.widgetCssPath;n={...n,...M},R?P():W()},destroy(){a||(a=!0,b(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},f())},getIframes(){return x()},getScale(){return p},setZoom(M){a||(n={...n,zoom:M},f())}}}0&&(module.exports={createThemePreview});