@runtypelabs/persona 4.6.1 → 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 (120) 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 +918 -174
  16. package/dist/index.d.ts +918 -174
  17. package/dist/index.global.js +81 -57
  18. package/dist/index.global.js.map +1 -1
  19. package/dist/index.js +89 -66
  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 +500 -1
  56. package/src/client.ts +285 -93
  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/runtime/persist-state.test.ts +118 -0
  80. package/src/session.ts +76 -22
  81. package/src/styles/widget.css +773 -26
  82. package/src/theme-editor/preview.ts +2 -0
  83. package/src/theme-editor/sections.test.ts +26 -1
  84. package/src/theme-editor/sections.ts +10 -2
  85. package/src/theme-reference.ts +2 -2
  86. package/src/tool-call-display-defaults.test.ts +1 -0
  87. package/src/types/theme.ts +77 -0
  88. package/src/types.ts +516 -17
  89. package/src/ui.artifact-pane-gating.test.ts +636 -0
  90. package/src/ui.component-directive.test.ts +104 -0
  91. package/src/ui.composer-bar.test.ts +60 -2
  92. package/src/ui.detached-panel.test.ts +1049 -0
  93. package/src/ui.scroll-additive.test.ts +1 -1
  94. package/src/ui.streaming-coalescing.test.ts +312 -0
  95. package/src/ui.tool-display.test.ts +51 -0
  96. package/src/ui.ts +933 -214
  97. package/src/utils/artifact-custom-actions.ts +128 -0
  98. package/src/utils/artifact-display.test.ts +42 -0
  99. package/src/utils/artifact-display.ts +84 -0
  100. package/src/utils/artifact-file.test.ts +116 -0
  101. package/src/utils/artifact-file.ts +117 -0
  102. package/src/utils/artifact-gate.test.ts +112 -5
  103. package/src/utils/artifact-gate.ts +39 -14
  104. package/src/utils/artifact-loading-status.ts +55 -0
  105. package/src/utils/artifact-status-label.ts +190 -0
  106. package/src/utils/buttons.ts +7 -1
  107. package/src/utils/code-highlight.test.ts +186 -0
  108. package/src/utils/code-highlight.ts +400 -0
  109. package/src/utils/icons.ts +2 -0
  110. package/src/utils/roving-tablist.test.ts +152 -0
  111. package/src/utils/roving-tablist.ts +111 -0
  112. package/src/utils/spinner.ts +45 -0
  113. package/src/utils/theme.test.ts +48 -0
  114. package/src/utils/theme.ts +7 -0
  115. package/src/utils/tokens.ts +91 -0
  116. package/src/utils/tool-loading-animation.test.ts +32 -0
  117. package/src/utils/tool-loading-animation.ts +24 -0
  118. package/dist/chunk-DFBSCFYN.js +0 -1
  119. package/dist/runtype-tts-entry-HFUV2UF7.js +0 -1
  120. package/dist/session-reconnect-U77QFUR7.js +0 -1
package/dist/index.js CHANGED
@@ -1,22 +1,28 @@
1
- var ih=Object.defineProperty;var ys=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ki=(e,t)=>{for(var n in t)ih(e,n,{get:t[n],enumerable:!0})};var qu={};Ki(qu,{DOMPurify:()=>ch,Marked:()=>lh});import{Marked as lh}from"marked";import ch from"dompurify";var zu=ys(()=>{"use strict"});var Ss,dl=ys(()=>{"use strict";Ss=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Ly(e){return e.replace(/\/+$/,"")}async function Py(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,_m=ys(()=>{"use strict";dl();Xa=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ss(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${Ly(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await Py(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Qa,$m=ys(()=>{"use strict";Qa=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var jm={};Ki(jm,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var Um=ys(()=>{"use strict";_m();$m()});var zm={};Ki(zm,{createReconnectController:()=>Ry});function Ry(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=b=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},b)}),f=()=>{var T;let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,v=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${(T=b==null?void 0:b.executionId)!=null?T:e.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var T,L,P,E,k,C;let b=(L=(T=e.config.reconnect)==null?void 0:T.backoffMs)!=null?L:Iy,v=(E=(P=e.config.reconnect)==null?void 0:P.maxAttempts)!=null?E:b.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let I=e.getResumable(),j=I.lastEventId,$=new AbortController;e.setAbortController($),e.emitReconnect({phase:"resuming",handle:I,attempt:t});let R=null;try{let N=await S({executionId:I.executionId,after:I.lastEventId,signal:$.signal});N&&N.ok&&N.body&&(R=N.body)}catch{R=null}if($.signal.aborted)return;if(R){let N=(k=e.getMessages().find(Z=>Z.id===I.assistantMessageId))==null?void 0:k.content,O=typeof N=="string"?N:"";try{await e.resumeConnect(R,I.assistantMessageId,O)}catch{}if($.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:I});return}e.getResumable().lastEventId!==j&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((C=b[Math.min(t-1,b.length-1)])!=null?C:1e3),$.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var Iy,Vm=ys(()=>{"use strict";Iy=[1e3,2e3,4e3,8e3,8e3]});import{Marked as dh}from"marked";import ph from"dompurify";var Vu=null,xs=null,bs=null;var Ku=e=>{xs=e},Gu=()=>xs?Promise.resolve(xs):bs||(Vu?(bs=Vu().then(e=>(xs=e,e)),bs):(bs=Promise.resolve().then(()=>(zu(),qu)).then(e=>(xs=e,e)),bs)),Vo=()=>xs;Ku({Marked:dh,DOMPurify:ph});var uh=e=>{if(e)return e},Wa=e=>{let t=null;return n=>{var o,s;let r=Vo();if(!r)return Kr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=uh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},vs=e=>e?Wa({markedOptions:e.options,renderer:e.renderer}):Wa(),mh=Wa(),Xu=e=>mh(e),Kr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Qu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ju=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ju(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Ju(t.length);return t.push({token:s,type:o}),s}),n},gh=e=>{let t=vs(e);return n=>{let r=[],o=Yu(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Qu(i)}"></div>`;s=s.replace(d,p)}),s}},fh=e=>{let t=[],n=Yu(e,t),r=Xu(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Qu(s)}"></div>`;r=r.replace(a,d)}),r};var hh={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"]},yh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zu=()=>{let e=null;return t=>{let n=Vo();if(!n)return Kr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!yh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,hh)}},Xs=e=>e===!1?null:typeof e=="function"?e:Zu();var em=/^\s*\|?[\s:|-]*-[\s:|-]*$/,tm=e=>e.includes("|"),nm=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},bh=e=>`| ${e.join(" | ")} |`,xh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),rm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!tm(o)||em.test(o)||!em.test(s))continue;let a=nm(o).length;if(a<1)continue;let i=xh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!tm(c))break;let p=bh(vh(nm(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
- `):e};var Rr="webmcp:",Gi=new Map,om=e=>{var t;Gi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Gi.set(n.name,r)}},Ys=e=>Gi.get(Ji(e)),Ha={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},sm=null;function im(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${wh(t.join(""))}`}function am(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function wh(e){let t=am(e,0).toString(36),n=am(e,2654435761).toString(36);return`${t}.${n}`}var Qs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return Ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}om(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Ah(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return gr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let b=typeof document!="undefined"&&!!document.modelContext;return gr(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=Ji(t),a;try{a=await o.getTools()}catch(b){let v=b instanceof Error?b.message:String(b);return gr(`Failed to read WebMCP registry: ${v}`)}om(a);let i=a.find(b=>b.name===s);if(!i)return gr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return gr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let d=Ys(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return gr("User declined the tool call.");if(r!=null&&r.aborted)return gr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let b=await o.executeTool(i,Mh(n),{signal:p.signal});return Sh(b)}catch(b){if(u)return gr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let v=b instanceof Error?b.message:String(b);return gr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}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}(sm?await sm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Th;try{return await n(t)}catch(o){return Ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Ch(t,r))}},Ji=e=>e.startsWith(Rr)?e.slice(Rr.length):e,Ko=e=>e.startsWith(Rr),Ch=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ah=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Sh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:kh(t)}]}},gr=e=>({isError:!0,content:[{type:"text",text:e}]}),Th=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Eh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var Ag=Object.defineProperty;var dr=(e,t)=>()=>(e&&(t=e(e=0)),t);var Yi=(e,t)=>{for(var n in t)Ag(e,n,{get:t[n],enumerable:!0})};var Md={};Yi(Md,{DOMPurify:()=>Tg,Marked:()=>Sg});import{Marked as Sg}from"marked";import Tg from"dompurify";var kd=dr(()=>{"use strict"});var mr,hl=dr(()=>{"use strict";mr=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let s=new Uint8Array(this.remainder.length+t.length);s.set(this.remainder),s.set(t,this.remainder.length),n=s,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let s=n.createBufferSource();s.buffer=o,s.connect(n.destination);let r=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=r:this.nextStartTime<r&&(this.nextStartTime=r,this.waterlineSamples>0&&(this.buffering=!0)),s.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(s),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}s.onended=()=>{let a=this.activeSources.indexOf(s);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let r=0;r<n;r++){let a=s.getInt16(r*2,!0);o[r]=a/32768}return o}}});function qm(e){return e.replace(/\/+$/,"")}async function Vm(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var La,Tp=dr(()=>{"use strict";hl();La=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new mr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let s=await this.ensurePlayer();if(t!==this.generation)return;s.flush(),s.resume(),s.onStarted(()=>{t===this.generation&&o.onStart?.()}),s.onFinished(()=>{t===this.generation&&o.onEnd?.()});let r=`${qm(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await Vm(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&s.enqueue(d)}s.markStreamEnd()}catch(s){if(t!==this.generation)return;let r=s instanceof Error?s:new Error(String(s));this.opts.onError?.(r),o.onError?.(r)}}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 Pa,Ep=dr(()=>{"use strict";Pa=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:s=>{if(o){n.onError?.(s);return}this.options.onFallback?.(s),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Mp={};Yi(Mp,{FallbackSpeechEngine:()=>Pa,RuntypeSpeechEngine:()=>La});var kp=dr(()=>{"use strict";Tp();Ep()});var Pp={};Yi(Pp,{createReconnectController:()=>Gm});function Gm(e){let t=0,n=null,o=null,s=!1,r=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||r()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{s||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),s=!0)},c=()=>{s&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),s=!1)},u=b=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},b)}),h=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let b=e.config.reconnect?.backoffMs??Km,C=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),P=L.lastEventId,R=new AbortController;e.setAbortController(R),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let D=null;try{let z=await T({executionId:L.executionId,after:L.lastEventId,signal:R.signal});z&&z.ok&&z.body&&(D=z.body)}catch{D=null}if(R.signal.aborted)return;if(D){let z=e.getMessages().find(q=>q.id===L.assistantMessageId)?.content,_=typeof z=="string"?z:"";try{await e.resumeConnect(D,L.assistantMessageId,_)}catch{}if(R.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==P&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(b[Math.min(t-1,b.length-1)]??1e3),R.signal.aborted))return}e.getResumable()&&h()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:r}}var Km,Rp=dr(()=>{"use strict";Km=[1e3,2e3,4e3,8e3,8e3]});import{Marked as Eg}from"marked";import Mg from"dompurify";var Ld=null,es=null,Do=null,pa=new Set,Zi=e=>{es=e;let t=[...pa];pa.clear();for(let n of t)try{n()}catch{}return e};var ts=e=>es?()=>{}:(pa.add(e),Id().catch(()=>{}),()=>{pa.delete(e)}),Rd=e=>{Zi(e)},Pd=e=>{throw Do=null,e},Id=()=>es?Promise.resolve(es):Do||(Ld?(Do=Ld().then(Zi,Pd),Do):(Do=Promise.resolve().then(()=>(kd(),Md)).then(Zi,Pd),Do)),Fn=()=>es;Rd({Marked:Eg,DOMPurify:Mg});var kg=e=>{if(e)return e},ua=e=>{let t=null;return n=>{let o=Fn();if(!o)return _n(n);if(!t){let{Marked:s}=o,r=e?.markedOptions;t=new s({gfm:r?.gfm??!0,breaks:r?.breaks??!0,pedantic:r?.pedantic,silent:r?.silent});let a=kg(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},pr=e=>e?ua({markedOptions:e.options,renderer:e.renderer}):ua(),Lg=ua(),Hd=e=>Lg(e),_n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Bd=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Wd=e=>`%%FORM_PLACEHOLDER_${e}%%`,Dd=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,s)=>{try{let r=JSON.parse(s.trim());if(r&&typeof r=="object"&&r.component==="form"&&r.type){let a=Wd(t.length);return t.push({token:a,type:String(r.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,s)=>{let r=Wd(t.length);return t.push({token:r,type:s}),r}),n},Pg=e=>{let t=pr(e);return n=>{let o=[],s=Dd(n,o),r=t(s);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${Bd(i)}"></div>`;r=r.replace(p,c)}),r}},Rg=e=>{let t=[],n=Dd(e,t),o=Hd(n);return t.forEach(({token:s,type:r})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Bd(r)}"></div>`;o=o.replace(a,p)}),o};var Ig={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"]},Wg=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Od=()=>{let e=null;return t=>{let n=Fn();if(!n)return _n(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(s,r)=>{if(r.attrName==="src"||r.attrName==="href"){let a=r.attrValue;a.toLowerCase().startsWith("data:")&&!Wg.test(a)&&(r.attrValue="",r.keepAttr=!1)}})}return e.sanitize(t,Ig)}},ns=e=>e===!1?null:typeof e=="function"?e:Od();var Nd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Fd=e=>e.includes("|"),_d=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},Hg=e=>`| ${e.join(" | ")} |`,Bg=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Dg=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),$d=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let s=t[o],r=t[o+1];if(!Fd(s)||Nd.test(s)||!Nd.test(r))continue;let a=_d(s).length;if(a<1)continue;let i=Bg(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Fd(d))break;let c=Hg(Dg(_d(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var En="webmcp:",el=new Map,jd=e=>{el.clear();for(let t of e){let n=t.title?.trim();n&&el.set(t.name,n)}},rs=e=>el.get(tl(e)),fa={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ud=null;function qd(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${Og(t.join(""))}`}function zd(e,t){let n=3735928559^t,o=1103547991^t;for(let s=0;s<e.length;s++){let r=e.charCodeAt(s);n=Math.imul(n^r,2654435761),o=Math.imul(o^r,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 Og(e){let t=zd(e,0).toString(36),n=zd(e,2654435761).toString(36);return`${t}.${n}`}var os=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(s){return fa.warn("getTools() threw: shipping an empty WebMCP snapshot.",s),[]}jd(n);let o=typeof location<"u"?location.origin:"";return n.filter(s=>this.passesClientAllowlist(s.name)).map(s=>{let r={name:s.name,description:s.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=Fg(s.inputSchema);return a&&(r.parametersSchema=a),r})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return xn("WebMCP is not enabled on this widget.");let s=this.getModelContext();if(!s){let b=typeof document<"u"&&!!document.modelContext;return xn(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 r=tl(t),a;try{a=await s.getTools()}catch(b){let C=b instanceof Error?b.message:String(b);return xn(`Failed to read WebMCP registry: ${C}`)}jd(a);let i=a.find(b=>b.name===r);if(!i)return xn(`WebMCP tool not registered on this page: ${r}`);if(!this.passesClientAllowlist(r))return xn(`WebMCP tool not allowed by client allowlist: ${r}`);if(o?.aborted)return xn("Aborted by cancel()");let p=rs(r),d={toolName:r,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return xn("User declined the tool call.");if(o?.aborted)return xn("Aborted by cancel()");let c=new AbortController,u=!1,h=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 s.executeTool(i,Ug(n),{signal:c.signal});return _g(b)}catch(b){if(u)return xn(`WebMCP tool '${r}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return xn("Aborted by cancel()");let C=b instanceof Error?b.message:String(b);return xn(C)}finally{clearTimeout(h),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}(Ud?await Ud():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){fa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,fa.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){let n=this.confirmHandler??$g;try{return await n(t)}catch(o){return fa.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Ng(t,o))}},tl=e=>e.startsWith(En)?e.slice(En.length):e,Oo=e=>e.startsWith(En),Ng=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Fg=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},_g=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:zg(t)}]}},xn=e=>({isError:!0,content:[{type:"text",text:e}]}),$g=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=jg(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},Eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Mh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},kh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Lh="agent_",Ph="flow_";function lm(e){return e.startsWith(Lh)?{kind:"agentId",agentId:e}:e.startsWith(Ph)?{kind:"flowId",flowId:e}:null}function cm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=lm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=lm(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Ih,ARR as Rh,OBJ as Wh,STR as Hh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Zs=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",ea=8,ws="data-persona-ask-sheet-for",Bh="Other",Dh="Other\u2026",pm="Type your own answer here",um="Send",Nh="Next",Oh="Back",Fh="Submit all",_h="Skip",$h=3,Xi="data-ask-current-index",Qi="data-ask-question-count",mm="data-ask-answers",Yi="data-ask-grouped",gm="data-ask-layout",jh=e=>e.layout==="pills"?"pills":"rows",Uh=e=>e.getAttribute(gm)==="pills"?"pills":"rows",dm=!1,fm=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},bo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Ih(o,Hh|Wh|Rh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ta=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!dm&&(dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},qh=e=>{var t;return(t=ta(e)[0])!=null?t:null},zh=(e,t)=>{var n;return(n=ta(e)[t])!=null?n:null},hm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ym=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Vh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=ym(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Kh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Gh=(e,t,n,r)=>{var p,u,f;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<$h;g++)s.appendChild(Kh(r));return s}if(d.forEach((g,b)=>{s.appendChild(Vh(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Bh:Dh;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=t.freeTextPlaceholder)!=null?p:pm,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(S),b.appendChild(v);let T=ym(r,a,d.length);T&&b.appendChild(T),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},bm=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:pm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:um,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Jh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Xh=(e,t,n)=>{var c,p,u,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Oh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:_h,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Fh:(f=n.nextLabel)!=null?f:Nh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(mm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(mm,JSON.stringify(t))},er=e=>{var n;let t=Number((n=e.getAttribute(Xi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Qh=(e,t)=>{e.setAttribute(Xi,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(Qi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(Yi)==="true",Yh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Zh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=bo(t),r=ta(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},vm=e=>{let t=Go(e),n=er(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},wm=e=>{if(!xo(e))return;let t=Go(e),n=er(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Zi=(e,t,n)=>{let r=Da(n),o=Uh(e),{payload:s,complete:a}=bo(t),i=xo(e),d=er(e),c=Cs(e),p=i?zh(s,d):qh(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=L,b.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=Gh(p,r,a,o);v.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(bm(r,o))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?e.appendChild(Jh(r)):(!u||i)&&S&&S.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Xh(d,c,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();vm(e),wm(e)},ey=(e,t,n)=>{let r=Da(t),o=jh(r),s=e.toolCall.id,a=ta(n),i=Math.max(1,a.length),d=i>1,c=Yh(e,a),p=d?Zh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Qi,String(i)),u.setAttribute(Xi,String(p)),u.setAttribute(Yi,d?"true":"false"),u.setAttribute(gm,o),xm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),hm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let S=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),u.appendChild(S),o!=="rows"&&u.appendChild(bm(r,o)),Zi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ty=(e,t,n)=>{let{payload:r}=bo(t),o=Math.max(1,ta(r).length);o>Cs(e)&&(e.setAttribute(Qi,String(o)),o>1&&!xo(e)&&e.setAttribute(Yi,"true")),Zi(e,t,n)},ny=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Da(t);hm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=bo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},na=(e,t,n)=>{if(!n||!yo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(c=>{c.getAttribute(ws)!==o&&c.remove()});let a=n.querySelector(`[${ws}="${fm(o)}"]`);if(a){ty(a,e,t);return}let{payload:i}=bo(e),d=ey(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${fm(t)}"]`:`[${ws}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},el=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),vo=(e,t)=>{let n=Go(e),r=er(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,xm(e,n),vm(e),wm(e)},Oa=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Qh(e,s),Zi(e,t,n)};var Hr="suggest_replies";var Cm={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},tl={name:Hr,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:Cm,origin:"sdk",annotations:{readOnlyHint:!0}},nl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Am=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},rl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=Am((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Sm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Tm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,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},Em={name:Ba,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:Tm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Em),Sm(e)&&t.push(tl),t};import{parse as Mm,STR as km,OBJ as Lm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},ry=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Pm=e=>e.status==="complete"?ry(e):e.status==="pending"?"Waiting":"",oy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Im=e=>e.status==="complete"?oy(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},oa=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},Ua=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},ol=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=oa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ra(r,n.slice(s,a.index),[]),a[1]!==void 0?ra(r,a[1],["bold"]):a[2]!==void 0?ra(r,a[2],["italic"]):a[3]!==void 0&&ra(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ra(r,n.slice(s),[]),r},ra=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},sy=()=>{let e=null,t=0,n=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*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},al=()=>{var t;let e=sy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},il=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Mm(n,km|Lm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ay=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Mm(s,km|Lm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ll=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Rm="4.6.1";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var cl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(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(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...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=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),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(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
8
+ ${e.description}`:"");return window.confirm(n)},jg=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Ug=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},zg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function No(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function ga(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var qg="agent_",Vg="flow_";function Vd(e){return e.startsWith(qg)?{kind:"agentId",agentId:e}:e.startsWith(Vg)?{kind:"flowId",flowId:e}:null}function Kd(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=Vd(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let s=Vd(n);if(s)return s;let r=t?.default;if(r)return{kind:"payload",payload:r(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Kg,ARR as Gg,OBJ as Jg,STR as Xg}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Mn=(e,t,n)=>{let o=e.createElement(t);return n&&(o.className=n),o},Gd=()=>document.createDocumentFragment(),nt=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[r,a]of Object.entries(t.attrs))o.setAttribute(r,a);if(t.style){let r=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(r[i]=p)}}let s=n.filter(r=>r!=null);return s.length>0&&o.append(...s),o},Fo=(...e)=>e.filter(Boolean).join(" ");var ma="ask_user_question",ss=8,ur="data-persona-ask-sheet-for",Qg="Other",Yg="Other\u2026",Xd="Type your own answer here",Qd="Send",Zg="Next",em="Back",tm="Submit all",nm="Skip",om=3,nl="data-ask-current-index",ol="data-ask-question-count",Yd="data-ask-answers",rl="data-ask-grouped",Zd="data-ask-layout",rm=e=>e.layout==="pills"?"pills":"rows",sm=e=>e.getAttribute(Zd)==="pills"?"pills":"rows",Jd=!1,ep=e=>e.replace(/["\\]/g,"\\$&"),to=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ma,ha=e=>e?.features?.askUserQuestion??{},no=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let s=o.join(""),r=Kg(s,Xg|Jg|Gg);if(r&&typeof r=="object")return{payload:r,complete:n}}catch{}return{payload:null,complete:n}},as=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ss&&!Jd&&(Jd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ss}.`)),t.slice(0,ss)},am=e=>as(e)[0]??null,im=(e,t)=>as(e)[t]??null,tp=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},np=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let s=m("span","persona-ask-row-check");o.appendChild(s)}else{let s=m("span","persona-ask-row-badge");s.textContent=String(n+1),o.appendChild(s)}return o},lm=(e,t,n,o)=>{let r=m("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(r.type="button",r.setAttribute("role",o?"checkbox":"button"),r.setAttribute("aria-pressed","false"),r.setAttribute("data-ask-user-action","pick"),r.setAttribute("data-option-index",String(t)),r.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}r.appendChild(a);let p=np(n,o,t);p&&r.appendChild(p)}else r.textContent=e.label,e.description&&(r.title=e.description);return r},cm=e=>{let n=m("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},dm=(e,t,n,o)=>{let r=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");r.setAttribute("role","group"),r.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<om;c++)r.appendChild(cm(o));return r}if(p.forEach((c,u)=>{r.appendChild(lm(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Qg:Yg;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 h=m("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Xd,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),h.appendChild(f),u.appendChild(h);let b=np(o,a,p.length);b&&u.appendChild(b),r.appendChild(u)}else{let u=m("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??c,r.appendChild(u)}}return r},op=(e,t)=>{let o=m("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=e.freeTextPlaceholder??Xd,s.setAttribute("data-ask-free-text-input","true"),o.appendChild(s),t!=="rows"){let r=m("button","persona-ask-free-text-submit persona-pointer-events-auto");r.type="button",r.textContent=e.submitLabel??Qd,r.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(r)}return o},pm=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Qd,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},um=(e,t,n)=>{let o=m("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let s=m("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=n.backLabel??em,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,o.appendChild(s);let r=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??nm,a.setAttribute("data-ask-user-action","skip"),r.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??tm:n.nextLabel??Zg,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,r.appendChild(i),o.appendChild(r),o},_o=e=>{let t=e.getAttribute(Yd);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},rp=(e,t)=>{e.setAttribute(Yd,JSON.stringify(t))},un=e=>{let t=Number(e.getAttribute(nl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},fm=(e,t)=>{e.setAttribute(nl,String(Math.max(0,Math.floor(t))))},fr=e=>{let t=Number(e.getAttribute(ol)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},oo=e=>e.getAttribute(rl)==="true",gm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((s,r)=>{let a=typeof s?.question=="string"?s.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[r]=i)}}),o},mm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ya=(e,t)=>{let{payload:n}=no(t),o=as(n),s=_o(e),r={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(s,p)&&(r[d]=s[p]))}),r},sp=e=>{let t=_o(e),n=un(e),o=t[n],s=new Set;typeof o=="string"?s.add(o):Array.isArray(o)&&o.forEach(p=>s.add(p));let r=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');r.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=s.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(r).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},ap=e=>{if(!oo(e))return;let t=_o(e),n=un(e),o=t[n],s=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,r=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');r&&(r.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},sl=(e,t,n)=>{let o=ha(n),s=sm(e),{payload:r,complete:a}=no(t),i=oo(e),p=un(e),d=fr(e),c=i?im(r,p):am(r),u=!!c?.multiSelect,h=e.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let P=typeof c?.question=="string"?c.question:"";b.textContent=P,b.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let P=dm(c,o,a,s);C.replaceWith(P)}if(s!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(op(o,s))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!T?e.appendChild(pm(o)):(!u||i)&&T&&T.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=um(p,d,o);L?L.replaceWith(P):e.appendChild(P)}else L&&L.remove();sp(e),ap(e)},hm=(e,t,n)=>{let o=ha(t),s=rm(o),r=e.toolCall.id,a=as(n),i=Math.max(1,a.length),p=i>1,d=gm(e,a),c=p?mm(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ur,r),u.setAttribute("data-tool-call-id",r),u.setAttribute("data-message-id",e.id),u.setAttribute(ol,String(i)),u.setAttribute(nl,String(c)),u.setAttribute(rl,p?"true":"false"),u.setAttribute(Zd,s),rp(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`),tp(u,o);let h=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="",h.appendChild(f);let b=m("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",h.appendChild(b),u.appendChild(h);let T=m("div",s==="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"),u.appendChild(T),s!=="rows"&&u.appendChild(op(o,s)),sl(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ym=(e,t,n)=>{let{payload:o}=no(t),s=Math.max(1,as(o).length);s>fr(e)&&(e.setAttribute(ol,String(s)),s>1&&!oo(e)&&e.setAttribute(rl,"true")),sl(e,t,n)},bm=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ha(t);tp(n,o);let s=m("span","persona-ask-stub-label"),{complete:r}=no(e);return s.textContent=r?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},is=(e,t,n)=>{if(!n||!to(e)||ha(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ur}]`).forEach(d=>{d.getAttribute(ur)!==s&&d.remove()});let a=n.querySelector(`[${ur}="${ep(s)}"]`);if(a){ym(a,e,t);return}let{payload:i}=no(e),p=hm(e,t,i);n.appendChild(p)},$o=(e,t)=>{if(!e)return;let n=t?`[${ur}="${ep(t)}"]`:`[${ur}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let r=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(r)?r:180)})},al=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ro=(e,t)=>{let n=_o(e),o=un(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,rp(e,n),sp(e),ap(e)},ba=(e,t,n,o)=>{let s=fr(e),r=Math.max(0,Math.min(s-1,o));fm(e,r),sl(e,t,n)};var kn="suggest_replies";var ip={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},il={name:kn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ip,origin:"sdk",annotations:{readOnlyHint:!0}},ll=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),va=e=>e.variant==="tool"&&e.toolCall?.name===kn,lp=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.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},cl=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!va(n))continue;let o=lp(n.toolCall?.args);return o.length>0?o:null}return null},cp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var dp={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ss,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},pp={name:ma,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:dp,origin:"sdk",annotations:{readOnlyHint:!0}},ls=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(pp),cp(e)&&t.push(il),t};import{parse as up,STR as fp,OBJ as gp}from"partial-json";var xa=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),so=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},vm=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},mp=e=>e.status==="complete"?vm(e):e.status==="pending"?"Waiting":"",xm=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var hp=e=>e.status==="complete"?xm(e):"Using tool...",Ca=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ds=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Ca(t)},wa=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Ca(t)},dl=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",s=ds(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,s)},Aa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,r=0,a;for(;(a=s.exec(n))!==null;)a.index>r&&cs(o,n.slice(r,a.index),[]),a[1]!==void 0?cs(o,a[1],["bold"]):a[2]!==void 0?cs(o,a[2],["italic"]):a[3]!==void 0&&cs(o,a[3],["dim"]),r=a.index+a[0].length;return r<n.length&&cs(o,n.slice(r),[]),o},cs=(e,t,n)=>{let o=t.split("{duration}");for(let s=0;s<o.length;s++)o[s]&&e.push({text:o[s],styles:n}),s<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Cm=()=>{let e=null,t=0,n=o=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,r=o.match(s);if(r&&r[1])try{return r[1].replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return r[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let s=o.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let r=n(o);return r!==null&&(e=r),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ps=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},pl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ul=()=>{let e=Cm();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},fl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=up(n,fp|gp);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xa(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xa(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},wm=e=>{let t=null,n=0,s=e||(r=>{if(!r||typeof r!="object")return null;let a=i=>typeof i=="string"?xa(i):null;if(r.component&&typeof r.component=="string")return typeof r.text=="string"?xa(r.text):"";if(r.type==="init"&&r.form)return"";if(r.action)switch(r.action){case"nav_then_click":return a(r.on_load_text)||a(r.text)||null;case"message":case"message_and_click":case"checkout":return a(r.text)||null;default:return a(r.text)||a(r.display_text)||a(r.message)||null}return a(r.text)||a(r.display_text)||a(r.message)||a(r.content)||null});return{getExtractedText:()=>t,processChunk:r=>{let a=r.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(r.length<=n)return t!==null?{text:t,raw:r}:null;try{let i=up(r,fp|gp),p=s(i);p!==null&&(t=p)}catch{}return n=r.length,{text:t||"",raw:r}},close:()=>{}}},gl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var yp="4.8.0";var Cn=yp;var Sm="https://api.runtype.com/v1/dispatch",Sa="https://api.runtype.com";function Tm(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let s=t.indexOf("/");if(s>0){let r=t.slice(s+1).split(";")[0]?.trim()??"";if(r&&r!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(r))return`attachment.${r}`}return"attachment"}var ml=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Em(e){switch(e){case"json":return fl;case"regex-json":return ul;case"xml":return gl;default:return pl}}var bp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Mm(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let s=bp(n);if(!bp(o))return e;if(!s||o===n||o.startsWith(n))return t;let a=ps(e);return ps(t)!==null&&a===null?t:e}var gr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??Sm,this.headers={"Content-Type":"application/json","X-Persona-Version":Cn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??Em(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new os(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:t,flowId:n};let r=Kd(o,s);return r.kind==="agentId"?{agentId:r.agentId}:r.kind==="flowId"?{flowId:r.flowId}:{targetPayload:r.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Sa}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,s={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Cn},body:JSON.stringify(s)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await r.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$/,"")||Sa}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Cn},body:JSON.stringify(s)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let s=await this.buildPayload(t.messages),r=s.metadata?Object.fromEntries(Object.entries(s.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(ml).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...r&&Object.keys(r).length>0&&{metadata:r},...s.inputs&&Object.keys(s.inputs).length>0&&{inputs:s.inputs},...s.context&&{context:s.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,s.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":Cn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(i.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(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let s=o instanceof Error?o:new Error(String(o));throw!s.message.includes("Session expired")&&!s.message.includes("Message limit")&&n({type:"error",error:s}),s}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Chat backend request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let r;if(this.customFetch)try{r=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else r=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:t.signal});if(!r.ok||!r.body){let a=new Error(`Agent execution request failed: ${r.status} ${r.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(r.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,s){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let s=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Sa}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(s,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,s){let r=!!(n&&n.length>0),a=r?qd(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=r&&i&&this.lastSentClientToolsFingerprint===a,d=!r&&s?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let h=0;;h++){if(u=await o({...r&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&h===0&&r&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,r?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let s=this.isClientTokenMode(),r=s?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Sa}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),s&&a){let d=[...ls(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,h=>{let f={...p,...h};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(r,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(r,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(ml).filter(a=>a.role==="user"||a.role==="assistant"||a.role==="system").filter(a=>!a.variant||a.variant==="assistant").sort((a,i)=>{let p=new Date(a.createdAt).getTime(),d=new Date(i.createdAt).getTime();return p-d}).map(a=>({role:a.role,content:a.contentParts??a.llmContent??a.rawContent??a.content,createdAt:a.createdAt})),s={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},r=[...ls(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(r.length>0&&(s.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let p=await i({messages:t,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&&(s.context=a)}return s}async buildPayload(t){let n=t.slice().filter(ml).sort((a,i)=>{let p=new Date(a.createdAt).getTime(),d=new Date(i.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(),s={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[a,i]of Object.entries(o.targetPayload))a!=="messages"&&(s[a]=i);let r=[...ls(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];if(r.length>0&&(s.clientTools=r),this.contextProviders.length){let a={};await Promise.all(this.contextProviders.map(async i=>{try{let p=await i({messages:t,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&&(s.context=a)}if(this.requestMiddleware)try{let a=await this.requestMiddleware({payload:{...s},config:this.config});if(a&&typeof a=="object"){let i=a;return s.clientTools!==void 0&&!("clientTools"in i)&&(i.clientTools=s.clientTools),i}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",a)}return s}async handleCustomSSEEvent(t,n,o,s,r,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===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:r(),...c!==void 0&&{partId:c}};return o.current=u,s(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,s(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,s(c)}return i.done&&(o.current&&(o.current.streaming=!1,s(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,s){let r=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=E=>{let J=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,v=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,A=E.tools?E.tools.map(M=>({...M,chunks:M.chunks?[...M.chunks]:void 0})):void 0;return{...E,reasoning:J,toolCall:v,tools:A}},h=E=>{if(E.role!=="assistant"||E.variant)return!0;let J=Array.isArray(E.contentParts)&&E.contentParts.length>0,v=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||J||v||!!E.stopReason},f=E=>{h(E)&&n({type:"message",message:u(E)})},b=null,C=null,T={current:null},L={current:null},P=null,R="",D=new Map,z=new Map,_=new Map,q=new Map,w=new Map,U={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},B=E=>{if(E==null)return null;try{return String(E)}catch{return null}},$=E=>B(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),pe=E=>B(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),ye=o,Te=!1,De=()=>{if(b)return b;let E,J="",v=P;return!Te&&ye?(E=ye,Te=!0,J=s??""):ye&&v?E=`${ye}_${v}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:E,role:"assistant",content:J,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(b),b},re=(E,J)=>{U.lastId=J,E&&U.byStep.set(E,J)},be=(E,J)=>{let v=E.reasoningId??E.id,A=$(E);if(v){let W=String(v);return re(A,W),W}if(A){let W=U.byStep.get(A);if(W)return U.lastId=W,W}if(U.lastId&&!J)return U.lastId;if(!J)return null;let M=`reason-${c()}`;return re(A,M),M},Y=E=>{let J=q.get(E);if(J)return J;let v={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return q.set(E,v),f(v),v},ce=(E,J)=>{Q.lastId=J,E&&Q.byCall.set(E,J)},Z=new Set,xe=new Map,me=new Set,fe=new Map,Pe=E=>{if(!E)return!1;let J=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return J==="emit_artifact_markdown"||J==="emit_artifact_component"},Oe=(E,J)=>{let v=E.toolId??E.id,A=pe(E);if(v){let W=String(v);return ce(A,W),W}if(A){let W=Q.byCall.get(A);if(W)return Q.lastId=W,W}if(Q.lastId&&!J)return Q.lastId;if(!J)return null;let M=`tool-${c()}`;return ce(A,M),M},je=E=>{let J=w.get(E);if(J)return J;let v={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return w.set(E,v),f(v),v},Ne=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let J=Number(E);if(!Number.isNaN(J)&&Number.isFinite(J))return J;let v=Date.parse(E);if(!Number.isNaN(v))return v}return Date.now()},we=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Le=new Map,ot=new Map,ie=new Map,Re=(E,J,v)=>{let A=ie.get(E);A||(A=[],ie.set(E,A));let M=0,W=A.length;for(;M<W;){let H=M+W>>>1;A[H].seq<J?M=H+1:W=H}A[M]?.seq===J?A[M]={seq:J,text:v}:A.splice(M,0,{seq:J,text:v});let K="";for(let H=0;H<A.length;H++)K+=A[H].text;return K},xt=(E,J)=>{let v=we(J),A=ot.get(E.id),M=Mm(A,v);E.rawContent=M;let W=Le.get(E.id),K=We=>{let ct=E.content??"";We.trim()!==""&&(ct.trim().length===0||We.startsWith(ct)||We.trimStart().startsWith(ct.trim()))&&(E.content=We)},H=()=>{if(W){let We=W.close?.();We instanceof Promise&&We.catch(()=>{})}Le.delete(E.id),ot.delete(E.id),E.streaming=!1,f(E)};if(!W){K(v),H();return}let j=ps(M);if(j!==null&&j.trim()!==""){K(j),H();return}let se=We=>{let ct=typeof We=="string"?We:We?.text??null;if(ct!==null&&ct.trim()!=="")return ct;let V=W.getExtractedText();return V!==null&&V.trim()!==""?V:v},et;try{et=W.processChunk(M)}catch{K(v),H();return}if(et instanceof Promise){et.then(We=>{K(se(We)),H()}).catch(()=>{K(v),H()});return}K(se(et)),H()},yt=null,rt=(E,J,v,A)=>{E.rawContent=J,Le.has(E.id)||Le.set(E.id,this.createStreamParser());let M=Le.get(E.id),W=J.trim().startsWith("{")||J.trim().startsWith("[");if(W&&ot.set(E.id,J),M.__isPlainTextParser===!0){E.content=A!==void 0?J:E.content+v,ot.delete(E.id),Le.delete(E.id),E.rawContent=void 0,f(E);return}let H=M.processChunk(J);if(H instanceof Promise)H.then(j=>{let se=typeof j=="string"?j:j?.text??null;se!==null&&se.trim()!==""?(E.content=se,f(E)):!W&&!J.trim().startsWith("<")&&(E.content=A!==void 0?J:E.content+v,ot.delete(E.id),Le.delete(E.id),E.rawContent=void 0,f(E))}).catch(()=>{E.content=A!==void 0?J:E.content+v,ot.delete(E.id),Le.delete(E.id),E.rawContent=void 0,f(E)});else{let j=typeof H=="string"?H:H?.text??null;j!==null&&j.trim()!==""?(E.content=j,f(E)):!W&&!J.trim().startsWith("<")&&(E.content=A!==void 0?J:E.content+v,ot.delete(E.id),Le.delete(E.id),E.rawContent=void 0,f(E))}},Ee=(E,J)=>{let v=J??E.content;if(v==null||v===""){E.streaming=!1,f(E);return}let M=ot.get(E.id)??we(v);E.rawContent=M;let W=Le.get(E.id),K=null,H=!1;if(W&&(K=W.getExtractedText(),K===null&&(K=ps(M)),K===null)){let j=W.processChunk(M);j instanceof Promise?(H=!0,j.then(se=>{let et=typeof se=="string"?se:se?.text??null;et!==null&&(E.content=et,E.streaming=!1,Le.delete(E.id),ot.delete(E.id),f(E))}).catch(()=>{})):K=typeof j=="string"?j:j?.text??null}if(!H){K!==null&&K.trim()!==""?E.content=K:ot.has(E.id)||(E.content=we(v));let j=Le.get(E.id);if(j){let se=j.close?.();se instanceof Promise&&se.catch(()=>{}),Le.delete(E.id)}ot.delete(E.id),E.streaming=!1,f(E)}},he=(E,J,v)=>{let A=z.get(E);if(A)return A;let M={id:`nested-${J}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:J}};return z.set(E,M),f(M),M},lt=[],Ie,ge=new Map,le=0,ve="agent",Ct=!1,O=null,te=null,Fe=new Map,Me=this.config.iterationDisplay??"separate";for(Ie=()=>{for(let E=0;E<lt.length;E++){let J=lt[E].payloadType,v=lt[E].payload;if(!Ct&&ve!=="flow"&&typeof v.stepType=="string"&&(ve="flow"),J==="reasoning_start"){let A=typeof v.id=="string"?v.id:null,M=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(A&&M){D.set(A,M),he(A,M,"reasoning");continue}let W=be(v,!0)??`reason-${c()}`,K=Y(W);K.reasoning=K.reasoning??{id:W,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ne(v.startedAt??v.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(J==="reasoning_delta"){let A=typeof v.id=="string"?v.id:null;if(A&&D.has(A)&&z.has(A)){let H=z.get(A),j=v.reasoningText??v.text??v.delta??"";j&&v.hidden!==!0&&H.reasoning&&(H.reasoning.chunks.push(String(j)),f(H));continue}let M=be(v,!1)??be(v,!0)??`reason-${c()}`,W=Y(M);W.reasoning=W.reasoning??{id:M,status:"streaming",chunks:[]},W.reasoning.startedAt=W.reasoning.startedAt??Ne(v.startedAt??v.timestamp);let K=v.reasoningText??v.text??v.delta??"";if(K&&v.hidden!==!0){let H=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(H!==void 0){let j=Re(M,H,String(K));W.reasoning.chunks=[j]}else W.reasoning.chunks.push(String(K))}if(W.reasoning.status=v.done?"complete":"streaming",v.done){W.reasoning.completedAt=Ne(v.completedAt??v.timestamp);let H=W.reasoning.startedAt??Date.now();W.reasoning.durationMs=Math.max(0,(W.reasoning.completedAt??Date.now())-H)}W.streaming=W.reasoning.status!=="complete",f(W)}else if(J==="reasoning_complete"){let A=typeof v.id=="string"?v.id:null;if(A&&D.has(A)&&z.has(A)){let j=z.get(A);if(j.reasoning){let se=typeof v.text=="string"?v.text:"";se&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(se),j.reasoning.status="complete",j.streaming=!1,f(j)}D.delete(A),z.delete(A);continue}let M=be(v,!1)??be(v,!0)??`reason-${c()}`,W=typeof v.text=="string"?v.text:"";!q.get(M)&&(W||v.scope==="loop")&&Y(M);let K=q.get(M);if(K?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(K.reasoning.scope=v.scope),W&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(W),K.reasoning.status="complete",K.reasoning.completedAt=Ne(v.completedAt??v.timestamp);let j=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-j),K.streaming=!1,f(K)}let H=$(v);H&&U.byStep.delete(H)}else if(J==="tool_start"){b&&(b.streaming=!1,f(b),b=null),typeof v.iteration=="number"&&(le=v.iteration);let A=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Oe(v,!0)??`tool-${c()}`,M=v.toolName??v.name;if(Pe(M)){Z.add(A);continue}ce(pe(v),A);let W=je(A),K=W.toolCall??{id:A,status:"pending"};K.name=M??K.name,K.status="running",v.parameters!==void 0?K.args=v.parameters:v.args!==void 0&&(K.args=v.args),K.startedAt=K.startedAt??Ne(v.startedAt??v.timestamp),K.completedAt=void 0,K.durationMs=void 0,W.toolCall=K,W.streaming=!0,v.executionId&&(W.agentMetadata={executionId:v.executionId,iteration:v.iteration}),f(W)}else if(J==="tool_output_delta"){let A=Oe(v,!1)??Oe(v,!0)??`tool-${c()}`;if(Z.has(A))continue;let M=je(A),W=M.toolCall??{id:A,status:"running"};W.startedAt=W.startedAt??Ne(v.startedAt??v.timestamp);let K=v.text??v.delta??v.message??"";K&&(W.chunks=W.chunks??[],W.chunks.push(String(K))),W.status="running",M.toolCall=W,M.streaming=!0;let H=v.agentContext;(H||v.executionId)&&(M.agentMetadata=M.agentMetadata??{executionId:H?.executionId??v.executionId,iteration:H?.iteration??v.iteration}),f(M)}else if(J==="tool_complete"){let A=Oe(v,!1)??Oe(v,!0)??`tool-${c()}`;if(Z.has(A)){Z.delete(A);continue}let M=je(A),W=M.toolCall??{id:A,status:"running"};W.status="complete",v.result!==void 0&&(W.result=v.result),typeof v.duration=="number"&&(W.duration=v.duration),W.completedAt=Ne(v.completedAt??v.timestamp);let K=v.duration??v.executionTime;if(typeof K=="number")W.durationMs=K;else{let se=W.startedAt??Date.now();W.durationMs=Math.max(0,(W.completedAt??Date.now())-se)}M.toolCall=W,M.streaming=!1;let H=v.agentContext;(H||v.executionId)&&(M.agentMetadata=M.agentMetadata??{executionId:H?.executionId??v.executionId,iteration:H?.iteration??v.iteration}),f(M);let j=pe(v);j&&Q.byCall.delete(j)}else if(J==="await"&&v.toolName){let A=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,M=A??v.toolId??`local-${c()}`,W=je(M),K=v.toolName,H=v.origin==="webmcp"&&!Oo(K)?`webmcp:${K}`:K,j=Oo(H),se=W.toolCall??{id:M,status:"pending"};se.name=H,se.args=v.parameters,se.status=j?"running":"complete",se.chunks=se.chunks??[],se.startedAt=se.startedAt??Ne(v.startedAt??v.timestamp??v.awaitedAt),j?(se.completedAt=void 0,se.duration=void 0,se.durationMs=void 0):se.completedAt=se.completedAt??se.startedAt,W.toolCall=se,W.streaming=!1,W.agentMetadata={...W.agentMetadata,executionId:v.executionId??W.agentMetadata?.executionId,awaitingLocalTool:!0,...A?{webMcpToolCallId:A}:{}},f(W)}else if(J==="text_start"){let A=typeof v.id=="string"?v.id:null,M=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(A&&M){D.set(A,M);continue}let W=b;W&&(ve==="flow"?(Ee(W),yt=W):(W.streaming=!1,f(W)),b=null),P=typeof v.id=="string"?v.id:P,R=""}else if(J==="text_delta"){let A=typeof v.id=="string"?v.id:null,M=A?D.get(A):void 0;if(A&&M){let K=typeof v.delta=="string"?v.delta:"",H=(_.get(A)??"")+K;if(_.set(A,H),H.trim()==="")continue;let j=he(A,M);j.agentMetadata={...j.agentMetadata,executionId:v.executionId,parentToolId:M},rt(j,H,K,void 0);continue}if(P=typeof v.id=="string"?v.id:P,ve==="flow"){let K=typeof v.delta=="string"?v.delta:"";if(R+=K,R.trim()==="")continue;let H=De();H.agentMetadata={executionId:v.executionId,iteration:v.iteration},rt(H,R,K,void 0),C=H;continue}let W=De();W.content+=v.delta??"",W.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:O??void 0,agentName:te?.agentName},C=W,f(W)}else if(J==="text_complete"){let A=typeof v.id=="string"?v.id:null;if(A&&D.has(A)){let W=z.get(A);W&&Ee(W),D.delete(A),_.delete(A),z.delete(A);continue}let M=b;M&&(ve==="flow"?(Ee(M),yt=M):((M.content??"")===""&&typeof v.text=="string"&&(M.content=v.text),M.streaming=!1,f(M)),b=null),P=null,R=""}else if(J==="step_complete"){let A=v.stepType,M=v.executionType;if(A==="tool"||M==="context")continue;if(v.success===!1){let W=v.error,K=typeof W=="string"&&W!==""?W:W!=null&&typeof W=="object"&&Reflect.has(W,"message")?String(W.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let H=b;H&&H.streaming&&(H.streaming=!1,f(H)),n({type:"status",status:"idle"});continue}{let W=yt;yt=null;let K=v.stopReason,H=v.result?.response;if(W)K&&(W.stopReason=K),H!=null?xt(W,H):W.streaming!==!1&&(Le.delete(W.id),ot.delete(W.id),W.streaming=!1,f(W));else{let j=H!=null&&H!=="";if(j||K){let se=De();K&&(se.stopReason=K),j?Ee(se,H):(se.streaming=!1,f(se))}}continue}}else if(J==="execution_start")ve=v.kind==="flow"?"flow":"agent",Ct=!0,ve==="agent"&&(te={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Ne(v.startedAt)});else if(J==="turn_start"){let A=typeof v.iteration=="number"?v.iteration:le;if(A!==le){if(te&&(te.currentIteration=A),Me==="separate"&&A>1){let M=b;M&&(M.streaming=!1,f(M),Fe.set(A-1,M),b=null)}le=A}O=typeof v.id=="string"?v.id:null,C=null}else if(J==="tool_input_delta"){let A=v.toolCallId??Q.lastId;if(A){let M=w.get(A);M?.toolCall&&(M.toolCall.chunks=M.toolCall.chunks??[],M.toolCall.chunks.push(v.delta??""),f(M))}}else{if(J==="tool_input_complete")continue;if(J==="turn_complete"){let A=v.stopReason,M=b??C;if(A&&M!==null){let W=v.id;(!W||M.agentMetadata?.turnId===W)&&(M.stopReason=A,f(M))}O===v.id&&(O=null)}else if(J==="media_start"){let A=String(v.id);ge.set(A,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(J==="media_delta"){let A=ge.get(String(v.id));A&&typeof v.delta=="string"&&A.parts.push(v.delta)}else if(J==="media_complete"){let A=String(v.id),M=ge.get(A);ge.delete(A);let W=(typeof v.mediaType=="string"?v.mediaType:void 0)??M?.mediaType??"application/octet-stream",K=typeof v.data=="string"?v.data:void 0,H=typeof v.url=="string"?v.url:M&&M.parts.length>0?M.parts.join(""):void 0,j=null;if(K)j={type:"media",data:K,mediaType:W};else if(H){let ct=W.toLowerCase();j={type:ct==="image"||ct.startsWith("image/")?"image-url":"file-url",url:H,mediaType:W}}let se=v.toolCallId??M?.toolCallId,et=j?[j]:[],We=[];for(let ct of et){if(!ct||typeof ct!="object")continue;let V=ct,Ue=typeof V.type=="string"?V.type:void 0,Ae=typeof V.mediaType=="string"?V.mediaType.toLowerCase():"",He=null,ke="";if(Ue==="media"){let Xe=typeof V.data=="string"?V.data:void 0;if(!Xe)continue;ke=Ae.length>0?Ae:"application/octet-stream",He=`data:${ke};base64,${Xe}`}else if(Ue==="image-url"){let Xe=typeof V.url=="string"?V.url:void 0;if(!Xe)continue;ke=Ae,He=Xe}else if(Ue==="file-url"){let Xe=typeof V.url=="string"?V.url:void 0;if(!Xe)continue;ke=Ae,He=Xe}else continue;if(He)if(Ue==="image-url"||ke.startsWith("image/"))We.push({type:"image",image:He,...ke.includes("/")?{mimeType:ke}:{}});else if(ke.startsWith("audio/"))We.push({type:"audio",audio:He,mimeType:ke});else if(ke.startsWith("video/"))We.push({type:"video",video:He,mimeType:ke});else{let Xe=ke||"application/octet-stream";We.push({type:"file",data:He,mimeType:Xe,filename:Tm(Xe)})}}if(We.length>0){let ct=c(),V=se,Ae={id:`agent-media-${typeof V=="string"&&V.length>0?`${V}-${ct}`:String(ct)}`,role:"assistant",content:"",contentParts:We,createdAt:new Date().toISOString(),streaming:!1,sequence:ct,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:le}};f(Ae);let He=b;He&&(He.streaming=!1,f(He)),b=null,T.current=null}}else if(J==="execution_complete"){let A=v.kind??ve;A==="agent"&&te&&(te.status=v.success?"complete":"error",te.completedAt=Ne(v.completedAt),te.stopReason=v.stopReason);let M=b;M&&(A==="flow"&&M.streaming!==!1?Ee(M):(M.streaming=!1,f(M)),b=null),P=null,R="",yt=null,n({type:"status",status:"idle",terminal:!0})}else if(J==="execution_error"){let A=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(A)})}else if(J!=="ping"){if(J==="approval_start"){let A=v.approvalId??`approval-${c()}`,M={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:te?.agentId??"virtual",executionId:v.executionId??te?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(M)}else if(J==="step_await"&&v.awaitReason==="approval_required"){let A=v.approvalId??`approval-${c()}`,M={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:"pending",agentId:te?.agentId??"virtual",executionId:v.executionId??te?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};f(M)}else if(J==="approval_complete"){let A=v.approvalId;if(A){let W={id:`approval-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:A,status:v.decision??"approved",agentId:te?.agentId??"virtual",executionId:v.executionId??te?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(W)}}else if(J==="artifact_start"||J==="artifact_delta"||J==="artifact_update"||J==="artifact_complete"){if(J==="artifact_start"){let A=v.artifactType,M=String(v.id),W=typeof v.title=="string"?v.title:void 0,K=v.file,H;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(H={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:M,artifactType:A,title:W,component:typeof v.component=="string"?v.component:void 0,...H?{file:H}:{}});let j=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(fe.set(M,{markdown:"",title:W,file:H,...j?{props:j}:{}}),!me.has(M)){me.add(M);let se=No(this.config.features?.artifacts,A),et=typeof v.component=="string"?v.component:void 0,We={id:`artifact-ref-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ga(se,{artifactId:M,title:W,artifactType:A,status:"streaming",...H?{file:H}:{},...et?{component:et}:{}})};xe.set(M,We),f(We)}}else if(J==="artifact_delta"){let A=String(v.id),M=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:A,artDelta:M});let W=fe.get(A);W&&(W.markdown+=M)}else if(J==="artifact_update"){let A=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:A,component:typeof v.component=="string"?v.component:void 0});let M=fe.get(String(v.id));M&&(M.props={...M.props??{},...A})}else if(J==="artifact_complete"){let A=String(v.id);n({type:"artifact_complete",id:A});let M=xe.get(A);if(M){M.streaming=!1;try{let W=JSON.parse(M.rawContent??"{}");if(W.props){W.props.status="complete";let K=fe.get(A);K?.markdown&&(W.props.markdown=K.markdown),K?.file&&(W.props.file=K.file),W.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(W.props.componentProps=K.props)}M.rawContent=JSON.stringify(W)}catch{}fe.delete(A),f(M),xe.delete(A)}}}else if(J==="transcript_insert"){let A=v.message;if(!A||typeof A!="object")continue;let M=String(A.id??`msg-${c()}`),W=A.role,H={id:M,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof A.content=="string"?A.content:"",rawContent:typeof A.rawContent=="string"?A.rawContent:void 0,createdAt:typeof A.createdAt=="string"?A.createdAt:new Date().toISOString(),streaming:A.streaming===!0,...typeof A.variant=="string"?{variant:A.variant}:{},sequence:c()};if(f(H),H.rawContent)try{let se=JSON.parse(H.rawContent)?.props?.artifactId;typeof se=="string"&&me.add(se)}catch{}b=null,T.current=null,Le.delete(M),ot.delete(M)}else if(J==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let A=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(A)});let M=b;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}else if(J==="step_error"||J==="dispatch_error"||J==="flow_error"){let A=null;if(v.error instanceof Error)A=v.error;else if(J==="dispatch_error"){let M=v.message??v.error;M!=null&&M!==""&&(A=new Error(String(M)))}else{let M=v.error;typeof M=="string"&&M!==""?A=new Error(M):M!=null&&typeof M=="object"&&Reflect.has(M,"message")&&(A=new Error(String(M.message??M)))}if(A){n({type:"error",error:A});let M=b;M&&M.streaming&&(M.streaming=!1,f(M)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:E,value:J}=await r.read();if(E)break;i+=a.decode(J,{stream:!0});let v=i.split(`
12
12
 
13
- `);i=(yr=Te.pop())!=null?yr:"";for(let ke of Te){let He=ke.split(`
14
- `),nt="message",Qe="",ht=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Qe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(ht=ce.slice(3).trim());let me=()=>{ht!==null&&ht!==""&&n({type:"cursor",id:ht})};if(!Qe){me();continue}let B;try{B=JSON.parse(Qe)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let xe=nt!=="message"?nt:(br=B.type)!=null?br:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,xe,B),this.parseSSEEvent){S.current=b;let ce=await this.handleCustomSSEEvent(B,n,S,g,p,T);if(S.current&&S.current!==b&&(b=S.current),ce){me();continue}}it.push({payloadType:xe,payload:B}),Ve(),me()}}Ve()}};function uy(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function my(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gy(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function yy(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function by(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xy(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vy=["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=[...Hm,...vy];function wy(e){return Hm.includes(e)||e.startsWith("image/")}function Ga(e){return wy(e.type)}async function Bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dm(e,t=Gr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Cy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nm(e,t){let n=Cy(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}dl();var Om=16e3,Ay=24e3,Sy=4096,Ty=1380533830;function Ey(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Ty?new Uint8Array(e,44):new Uint8Array(e)}function My(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ia=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Om,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Om});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ss(Ay);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${My(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let S=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Sy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Ey(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Yo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ia(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function pl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Yo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Yo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return pl(e),!0}catch{return!1}}function la(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Zo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):la(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ts=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function ul(e){if(!e)return"";let t=ky(e);return Fm(t!==null?t:e)}function ky(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Fm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);i=v.pop()??"";for(let A of v){let M=A.split(`
14
+ `),W="message",K="",H=null;for(let We of M)We.startsWith("event:")?W=We.replace("event:","").trim():We.startsWith("data:")?K+=We.replace("data:","").trim():We.startsWith("id:")&&(H=We.slice(3).trim());let j=()=>{H!==null&&H!==""&&n({type:"cursor",id:H})};if(!K){j();continue}let se;try{se=JSON.parse(K)}catch(We){n({type:"error",error:We instanceof Error?We:new Error("Failed to parse chat stream payload")});continue}let et=W!=="message"?W:se.type??"message";if(this.onSSEEvent?.(et,se),this.parseSSEEvent){T.current=b;let We=await this.handleCustomSSEEvent(se,n,T,f,c,L);if(T.current&&T.current!==b&&(b=T.current),We){j();continue}}lt.push({payloadType:et,payload:se}),Ie(),j()}}Ie()}};function km(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function us(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function jo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ta="[Image]";function Lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Rm(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Im(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ea(e){return{type:"text",text:e}}function Wm(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Hm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Bm(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var vp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Dm=["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"],$n=[...vp,...Dm];function Om(e){return vp.includes(e)||e.startsWith("image/")}function Ma(e){return Om(e.type)}async function xp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;Ma(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Cp(e,t=$n,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Nm(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function wp(e,t){let n=Nm(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}hl();var Ap=16e3,Fm=24e3,_m=4096,$m=1380533830;function jm(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===$m?new Uint8Array(e,44):new Uint8Array(e)}function Um(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var fs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let s=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let r=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Ap,channelCount:1,echoCancellation:!0}});if(s!==this.callGeneration){r.getTracks().forEach(u=>u.stop());return}this.mediaStream=r;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:Ap});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new mr(Fm);if(s!==this.callGeneration){p.destroy(),r.getTracks().forEach(u=>u.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{s===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${Um(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{s===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,r,c,s))},c.onmessage=u=>this.handleMessage(u,s),c.onerror=()=>{s===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(s===this.callGeneration){if(u.code!==1e3){let h=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${h}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(r){throw this.cleanup(),this.emitError(r),this.emitStatus("error"),r}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,s){let r=t.createMediaStreamSource(n);this.sourceNode=r;let a=t.createScriptProcessor(_m,1,1);this.processor=a,a.onaudioprocess=i=>{if(s!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},r.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=jm(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(s=>s(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Uo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(r=>r[0]).map(r=>r.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(r=>r({text:o,confidence:s?.8:.5,provider:"browser"})),s&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function zo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new fs(e.runtype);case"browser":if(!Uo.isSupported())throw new Error("Browser speech recognition not supported");return new Uo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function yl(e){if(e?.type==="custom"&&e.custom)return zo({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return zo({type:"runtype",runtype:e.runtype});if(Uo.isSupported())return zo({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ka(e){try{return yl(e),!0}catch{return!1}}function gs(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(s=>s.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var qo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(t.text),r=o.getVoices();if(t.voice){let a=r.find(i=>i.name===t.voice);a&&(s.voice=a)}else r.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(r):gs(r));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),s.onend=()=>n.onEnd?.(),s.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var hr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(o!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function bl(e){if(!e)return"";let t=zm(e);return Sp(t!==null?t:e)}function zm(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Sp(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var qm=null;var ml=()=>qm?qm():Promise.resolve().then(()=>(Um(),jm));var Wy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Hy(e,t){return Wy.some(n=>e[n]!==t[n])}function gl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
16
+ `),t.trim()}var Lp=null;var vl=()=>Lp?Lp():Promise.resolve().then(()=>(kp(),Mp));var Jm=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Xm(e,t){return Jm.some(n=>e[n]!==t[n])}function xl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
17
17
 
18
- _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),Km=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gm=e=>Ko(e)||e===Hr,da=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ts(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ko(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new As(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||ml().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Zo.isSupported()?new Zo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return ml().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){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:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Hy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new As(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?aa():n==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?aa():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=aa(),s=Xo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let S=gl(b,this.config.errorMessage);if(S){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Xo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=gl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.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(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,S,T,L,P,E,k;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,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=(v=t.toolCall)==null?void 0:v.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let j=typeof((S=I[0])==null?void 0:S.question)=="string"?I[0].question:"";j&&(a={[j]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([I,j])=>`${I}: ${Array.isArray(j)?j.join(", "):j}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((I,j)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let R=C[$],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${j}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${j}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(k=(E=this.callbacks).onError)==null||k.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var k,C,I,j,$,R,N;let g=(k=f.toolCall)==null?void 0:k.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),T=(j=(I=f.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?j:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:nl(),toolMessage:f,startedAt:S,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let P=this.client.executeWebMcpToolCall(g,($=f.toolCall)==null?void 0:$.args,L.signal),E;if(!P)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await P}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(N=(R=this.callbacks).onError)==null||N.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(f,ca(Z?"Aborted by cancel()":Km(O)),S),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ca("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:E,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,ca("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,S,T,L,P,E,k,C,I,j,$;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(N){(E=(P=this.callbacks).onError)==null||E.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Hr,p=(k=t.toolCall)==null?void 0:k.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let R;if(c?R=nl():u?R=await u:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),a);return}let N=(I=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;f="resume",await this.resumeWithToolOutput(n,N,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,R,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let N=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||N||d.aborted)&&this.markWebMcpToolComplete(t,ca(N||d.aborted?"Aborted by cancel()":Km(R)),a),N||($=(j=this.callbacks).onError)==null||$.call(j,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{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(()=>(Vm(),zm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>gl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=ul(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=ul(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let $=o.approval,R=n.approval;a.approval={...$,...R,executionId:R.executionId||$.executionId,toolName:R.toolName||$.toolName,description:R.description||$.description,toolType:(g=R.toolType)!=null?g:$.toolType,reason:(b=R.reason)!=null?b:$.reason,parameters:(v=R.parameters)!=null?v:$.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&Gm(i)&&d&&c&&((P=n.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let $=`${d}:${c}`,R=this.webMcpInflightKeys.has($),N=this.webMcpResolvedKeys.has($),O=(E=o.toolCall)==null?void 0:E.name,Z=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&O!==void 0&&Gm(O)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(R||N||Z)&&(a.agentMetadata={...(j=a.agentMetadata)!=null?j:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as By,ArrowDown as Dy,ArrowUp as Ny,ArrowUpRight as Oy,Bot as Fy,ChevronDown as _y,ChevronUp as $y,ChevronRight as jy,ChevronLeft as Uy,Check as qy,Clipboard as zy,ClipboardCopy as Vy,Copy as Ky,File as Gy,FileCode as Jy,FileSpreadsheet as Xy,FileText as Qy,ImagePlus as Yy,Loader as Zy,LoaderCircle as eb,Mic as tb,Paperclip as nb,RefreshCw as rb,Search as ob,Send as sb,ShieldAlert as ab,ShieldCheck as ib,ShieldX as lb,Square as cb,ThumbsDown as db,ThumbsUp as pb,Upload as ub,Volume2 as mb,X as gb,User as fb,Mail as hb,Phone as yb,Calendar as bb,Clock as xb,Building as vb,MapPin as wb,Lock as Cb,Key as Ab,CreditCard as Sb,AtSign as Tb,Hash as Eb,Globe as Mb,Link as kb,CircleCheck as Lb,CircleX as Pb,TriangleAlert as Ib,Info as Rb,Ban as Wb,Shield as Hb,ArrowLeft as Bb,ArrowRight as Db,ExternalLink as Nb,Ellipsis as Ob,EllipsisVertical as Fb,Menu as _b,House as $b,Plus as jb,Minus as Ub,Pencil as qb,Trash as zb,Trash2 as Vb,Save as Kb,Download as Gb,Share as Jb,Funnel as Xb,Settings as Qb,RotateCw as Yb,Maximize as Zb,Minimize as ex,ShoppingCart as tx,ShoppingBag as nx,Package as rx,Truck as ox,Tag as sx,Gift as ax,Receipt as ix,Wallet as lx,Store as cx,DollarSign as dx,Percent as px,Play as ux,Pause as mx,VolumeX as gx,Camera as fx,Image as hx,Film as yx,Headphones as bx,MessageCircle as xx,MessageSquare as vx,Bell as wx,Heart as Cx,Star as Ax,Eye as Sx,EyeOff as Tx,Bookmark as Ex,CalendarDays as Mx,History as kx,Timer as Lx,Folder as Px,FolderOpen as Ix,Files as Rx,Sparkles as Wx,Zap as Hx,Sun as Bx,Moon as Dx,Flag as Nx,Monitor as Ox,Smartphone as Fx}from"lucide";var _x={activity:By,"arrow-down":Dy,"arrow-up":Ny,"arrow-up-right":Oy,bot:Fy,"chevron-down":_y,"chevron-up":$y,"chevron-right":jy,"chevron-left":Uy,check:qy,clipboard:zy,"clipboard-copy":Vy,copy:Ky,file:Gy,"file-code":Jy,"file-spreadsheet":Xy,"file-text":Qy,"image-plus":Yy,loader:Zy,"loader-circle":eb,mic:tb,paperclip:nb,"refresh-cw":rb,search:ob,send:sb,"shield-alert":ab,"shield-check":ib,"shield-x":lb,square:cb,"thumbs-down":db,"thumbs-up":pb,upload:ub,"volume-2":mb,x:gb,user:fb,mail:hb,phone:yb,calendar:bb,clock:xb,building:vb,"map-pin":wb,lock:Cb,key:Ab,"credit-card":Sb,"at-sign":Tb,hash:Eb,globe:Mb,link:kb,"circle-check":Lb,"circle-x":Pb,"triangle-alert":Ib,info:Rb,ban:Wb,shield:Hb,"arrow-left":Bb,"arrow-right":Db,"external-link":Nb,ellipsis:Ob,"ellipsis-vertical":Fb,menu:_b,house:$b,plus:jb,minus:Ub,pencil:qb,trash:zb,"trash-2":Vb,save:Kb,download:Gb,share:Jb,funnel:Xb,settings:Qb,"rotate-cw":Yb,maximize:Zb,minimize:ex,"shopping-cart":tx,"shopping-bag":nx,package:rx,truck:ox,tag:sx,gift:ax,receipt:ix,wallet:lx,store:cx,"dollar-sign":dx,percent:px,play:ux,pause:mx,"volume-x":gx,camera:fx,image:hx,film:yx,headphones:bx,"message-circle":xx,"message-square":vx,bell:wx,heart:Cx,star:Ax,eye:Sx,"eye-off":Tx,bookmark:Ex,"calendar-days":Mx,history:kx,timer:Lx,folder:Px,"folder-open":Ix,files:Rx,sparkles:Wx,zap:Hx,sun:Bx,moon:Dx,flag:Nx,monitor:Ox,smartphone:Fx},ye=(e,t=24,n="currentColor",r=2)=>{let o=_x[e];return o?$x(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function $x(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ux(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Es=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ya.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Dm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Bm(c),f=Ga(c)?URL.createObjectURL(c):null,g={id:jx(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ux(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Nm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=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(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Jm(s)&&Jm(o)?n[r]=pa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",fl="440px",qx={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:tr,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)"},Dt={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:qx,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 Xm(e,t){if(!(!e&&!t))return e?t?pa(e,t):e:t}function hl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k;return e?{...Dt,...e,theme:Xm(Dt.theme,e.theme),darkTheme:Xm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let C=(re=Dt.features)==null?void 0:re.artifacts,I=(se=e.features)==null?void 0:se.artifacts,j=(ae=Dt.features)==null?void 0:ae.scrollToBottom,$=(fe=e.features)==null?void 0:fe.scrollToBottom,R=($e=Dt.features)==null?void 0:$e.scrollBehavior,N=(V=e.features)==null?void 0:V.scrollBehavior,O=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Le=j===void 0&&$===void 0?void 0:{...j,...$},Pe=R===void 0&&N===void 0?void 0:{...R,...N},ne=O===void 0&&Z===void 0?void 0:{...O,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Dt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(T=(S=e.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(E=Dt.markdown)==null?void 0:E.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var Qm={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"}},Ym={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"}},Zm={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:tr,maxWidth:fl,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 Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ms(e,r):r}function yl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function tg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=tg(s,o):n[r]=o}return n}function zx(e,t){return t?tg(e,t):e}function ua(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,S;let n={palette:Qm,semantic:Ym,components:Zm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:zx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=eg(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function bl(e){var v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,vn,Ct,fn,yr,br,Ue,M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro;let t=yl(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(k=n["--persona-semantic-colors-text"])!=null?k:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(j=n["--persona-semantic-colors-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(N=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"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"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--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)",n["--persona-input-radius"]=(vn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?vn:"0.5rem",n["--persona-message-user-radius"]=(fn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(xr=n["--persona-components-message-assistant-shadow"])!=null?xr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Xr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Xr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Qr=n["--persona-components-scrollToBottom-gap"])!=null?Qr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Yr=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(wr=n["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Cr=n["--persona-components-reasoningBubble-shadow"])!=null?Cr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Ar=(Lo=n["--persona-components-markdown-link-foreground"])!=null?Lo:n["--persona-accent"])!=null?Ar:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Po=n["--persona-components-markdown-codeBlock-background"])!=null?Po:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ss=n["--persona-components-markdown-codeBlock-textColor"])!=null?ss:"inherit",n["--persona-md-table-header-bg"]=(Zr=n["--persona-components-markdown-table-headerBackground"])!=null?Zr:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(eo=n["--persona-components-markdown-hr-color"])!=null?eo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(to=n["--persona-components-markdown-blockquote-borderColor"])!=null?to:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Io=n["--persona-components-markdown-blockquote-background"])!=null?Io:"transparent",n["--persona-md-blockquote-text-color"]=(Ro=n["--persona-components-markdown-blockquote-textColor"])!=null?Ro:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(no=n["--persona-components-collapsibleWidget-container"])!=null?no:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.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 f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ce=b.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(wn=n["--persona-dropdown-bg"])!=null?wn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(b!=null&&b.tab){let Ce=b.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(b!=null&&b.pane){let Ce=b.pane;if(Ce.toolbarBackground){let $r=(ro=Ms(e,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var Vx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Kx={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"}}},ng=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Gx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},rg=e=>Gx(e),Jx=e=>ua(e),Xx=e=>{var n;let t=ua(void 0,{validate:!1});return ua({...e,palette:{...t.palette,colors:{...Kx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ma=e=>{let t=rg(e),n=ng(e==null?void 0:e.theme),r=ng(e==null?void 0:e.darkTheme);return t==="dark"?Xx(pa(n!=null?n:{},r!=null?r:{})):Jx(n)},Qx=e=>bl(e),es=(e,t)=>{let n=ma(t),r=Qx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},xl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Yx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Yx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-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=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ti}}}function ag(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(P=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?P:0,(I=(C=(k=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(O=(N=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?O:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function cg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Co(e,t){return Br(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Ao=xn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zx=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ga.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ga.buffer}},fg=[{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"}],fa=new Map;for(let e of fg)fa.set(e.name,e);var ev=e=>{fa.set(e.name,e)},tv=e=>{fg.some(t=>t.name===e)||fa.delete(e)},nv=()=>Array.from(fa.keys()),ks=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
- `);return s<0?"":e.slice(0,s)}return e},rv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},ov=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,sv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},av=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let c=i;for(;c<s.length&&vl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!vl.test(s[p]);)c.appendChild(rv(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},iv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(ov(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Zx).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)sv(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?av:iv;for(let g of i)p(g,n,c);return o.innerHTML},ii=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ya=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},gg=new WeakMap,lv=(e,t)=>{var s;if(!e.styles)return;let n=gg.get(t);if(n||(n=new Set,gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,cv=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},hg=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},li=(e,t)=>{lv(e,t),cv(e,t)};function Cl(e,t=xn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var ba=0,So=null;function Al(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;So={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,ba=Math.max(0,ba-1),ba===0&&So)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,s.scrollTo(0,So.scrollY),So=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},To=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var hr={"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 dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ci=(e,t={})=>{var S,T,L,P,E,k;let{showClose:n=!0,wrapperClassName:r=dv,buttonSize:o,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(P=a.closeButtonShowTooltip)!=null?P:!0,u=(E=a.closeButtonIconName)!=null?E:"x",f=(k=a.closeButtonIconText)!=null?k:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=ye(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,I=()=>{if(C)return;let $=b.ownerDocument,R=$.body;if(!R)return;C=Wr($,"div","persona-clear-chat-tooltip"),C.textContent=c;let N=Wr($,"div");N.className="persona-clear-chat-tooltip-arrow",C.appendChild(N);let O=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ao),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},j=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",j),b.addEventListener("focus",I),b.addEventListener("blur",j),d._cleanupTooltip=()=>{j(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",j),b.removeEventListener("focus",I),b.removeEventListener("blur",j)}}return{button:b,wrapper:d}},pv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",di=(e,t={})=>{var C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe;let{wrapperClassName:n=pv,buttonSize:r,iconSize:o="20px"}=t,a=(I=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(j=r!=null?r:a.size)!=null?j:"32px",d=($=a.iconName)!=null?$:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(N=a.backgroundColor)!=null?N:"",u=(O=a.borderWidth)!=null?O:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ee=a.borderRadius)!=null?Ee:"",b=(de=a.paddingX)!=null?de:"",v=(ee=a.paddingY)!=null?ee:"",S=(Le=a.tooltipText)!=null?Le:"Clear chat",T=(Pe=a.showTooltip)!=null?Pe:!0,L=y("div",n),P=!!(u||f),E=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:c||Mn.actionIconColor,backgroundColor:p||void 0,border:P?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),k=ye(d,o,"currentColor",1);if(k&&(k.style.display="block",E.appendChild(k)),L.appendChild(E),T&&S){let ne=null,Ae=()=>{if(ne)return;let se=E.ownerDocument,ae=se.body;if(!ae)return;ne=Wr(se,"div","persona-clear-chat-tooltip"),ne.textContent=S;let fe=Wr(se,"div");fe.className="persona-clear-chat-tooltip-arrow",ne.appendChild(fe);let $e=E.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(Ao),ne.style.left=`${$e.left+$e.width/2}px`,ne.style.top=`${$e.top-8}px`,ne.style.transform="translate(-50%, -100%)",ae.appendChild(ne)},re=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",re),E.addEventListener("focus",Ae),E.addEventListener("blur",re),L._cleanupTooltip=()=>{re(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",re),E.removeEventListener("focus",Ae),E.removeEventListener("blur",re)}}return{button:E,wrapper:L}};var Mn={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))"},Eo=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae;let{config:t,showClose:n=!0}=e,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(k=t==null?void 0:t.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(I=o.closeButtonPlacement)!=null?I:"inline",i=(j=o.headerIconHidden)!=null?j:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,se=ye(d,re*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?R:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let re=y("img");re.src=t.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=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Mn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Pe=o.clearChat)!=null?Pe:{},b=(ne=g.enabled)!=null?ne:!0,v=(Ae=g.placement)!=null?Ae:"inline",S=null,T=null;if(b){let se=di(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=se.button,T=se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:E}=ci(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:P,closeButtonWrapper:E,clearChatButton:S,clearChatButtonWrapper:T}},Ls=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ts(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ao)):(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 g of t){if(g.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let S=ye(g.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",S=>{S.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ye(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function pi(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=ye(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function ui(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Sl(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=ye(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,S;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ts({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var yg=e=>{var r;let t=Eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function uv(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ts({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var bg=e=>{var L,P,E,k,C,I,j,$,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Sl({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Mn.titleColor,p=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(p),uv(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C: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 N=o==null?void 0:o.titleRowHover;N&&(c.style.borderRadius=(I=N.borderRadius)!=null?I:"10px",c.style.padding=(j=N.padding)!=null?j:"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=N.background)!=null?O:"",c.style.borderColor=(Z=N.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=($=a.closeButtonSize)!=null?$:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Mn.actionIconColor;let b=(R=a.closeButtonIconName)!=null?R:"x",v=ye(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let S=y("div");S.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:T,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:yg,minimal:bg},xg=e=>{var t;return(t=Tl[e])!=null?t:Tl.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=xg(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},gi=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee;let t=(k=e==null?void 0:e.sendButton)!=null?k:{},n=(C=t.useIcon)!=null?C:!1,r=(I=t.iconText)!=null?I:"\u2191",o=t.iconName,s=(j=t.stopIconName)!=null?j:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(O=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?O:"Send",c=(Ee=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("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&&!f&&"persona-bg-persona-primary",!n&&!g&&"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?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),S=null,T=null;if(n){let Le=parseFloat(u)||24,Pe=(g==null?void 0:g.trim())||"currentColor";o?(S=ye(o,Le,Pe,2),S?v.appendChild(S):v.textContent=r):v.textContent=r,T=ye(s,Le,Pe,2)}else v.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,b.appendChild(L)),v.setAttribute("aria-label",a),b.appendChild(v);let P="send";return{button:v,wrapper:b,setMode:Le=>{if(Le===P)return;P=Le;let Pe=Le==="stop"?i:a;if(v.setAttribute("aria-label",Pe),L&&(L.textContent=Pe),n){if(S&&T){let ne=Le==="stop"?T:S;v.replaceChildren(ne)}}else v.textContent=Le==="stop"?c:d}}},fi=e=>{var L,P,E,k,C,I,j,$,R,N,O,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||o))return null;let a=(k=(E=e==null?void 0:e.sendButton)==null?void 0:E.size)!=null?k:"40px",i=(C=t.iconName)!=null?C:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=($=t.backgroundColor)!=null?$:(j=e==null?void 0:e.sendButton)==null?void 0:j.backgroundColor,u=(N=t.iconColor)!=null?N:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,f=y("div","persona-send-button-wrapper"),g=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ye(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let S=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&S){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=S,f.appendChild(Ee)}return{button:g,wrapper:f}},hi=e=>{var b,v,S,T,L,P,E,k;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(S=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?S:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(P=t.buttonIconName)!=null?P:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=t.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ye(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(k=t.buttonTooltipText)!=null?k:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},bi=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=bi(),o=Et("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=mi(t);a();let i=gi(t),d=fi(t),c=hi(t),p=yi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var vg=()=>{let e=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ye("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},wg=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=bi();r.style.display="none";let o=yi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),c=hi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Cg=e=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(To(e)){let N=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(b=N.expandedSize)!=null?b:"anchored",O.style.zIndex=String((S=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?S:xn);let Z=y("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 Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=N.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((P=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?P:xn),{wrapper:O,panel:Z,pillRoot:Ee}}if(n){let N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(O),{wrapper:N,panel:O}}if(!t){let N=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.width)!=null?k:"100%";return N.style.width=Z,O.style.width="100%",N.appendChild(O),{wrapper:N,panel:O}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&hr[o.position]?hr[o.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((j=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?j:xn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?R:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},mv=(e,t)=>{var E,k,C,I,j,$,R,N,O;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ci(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=di(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(j=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?j:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),f=Et("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))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let S=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=wg({config:e}),{root:L,textNode:P}=vg();return n.append(d,o,c,S),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:P}},Ag=(e,t=!0)=>{var S,T,L,P,E,k,C,I,j;if(To(e))return mv(e,t);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(S=e==null?void 0:e.layout)==null?void 0:S.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):Eo({config:e,showClose:t}),a=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Et("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:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=wa({config:e}),b=((j=e==null?void 0:e.layout)==null?void 0:j.showFooter)!==!1;o?Ls(n,s,e):(s.header.style.display="none",Ls(n,s,e)),n.append(a);let v=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var El=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
+ _Details: ${n.message}_`:o}var ms=e=>({isError:!0,content:[{type:"text",text:e}]}),Ip=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Wp=e=>Oo(e)||e===kn,hs=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new hr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Oo(n.name)||n.name===kn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new gr(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||vl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return ka(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=qo.isSupported()?new qo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,s=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,r=this.config.clientToken,a=t.browserFallback!==!1;if(o&&s&&r)return vl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:s,clientToken:r,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return r&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=zo(n);let s=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(r=>{r.provider!=="runtype"&&r.text&&r.text.trim()&&this.sendMessage(r.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((r,a,i)=>{if(r==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(r=>{this.config.voiceRecognition?.onMetrics?.(r)}),this.voiceProvider.onError(r=>{console.error("Voice error:",r),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(r=>{this.voiceStatus=r,this.voiceActive=r==="listening",this.callbacks.onVoiceStatusChanged?.(r)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Xm(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 gr(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:s,contentParts:r,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,f={id:a??(n==="user"?us():n==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...s!==void 0&&{llmContent:s},...r!==void 0&&{contentParts:r},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:s,content:r,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:h,rawContent:f}=o,C={id:p??(s==="user"?us():s==="assistant"?jo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:s,content:r,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:s="",llmContent:r,id:a,createdAt:i,sequence:p}=t,d={text:s,component:n,props:o};return this.injectMessage({role:"assistant",content:s,rawContent:JSON.stringify(d),...r!==void 0&&{llmContent:r},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let s=us(),r=jo();this.activeAssistantMessageId=null;let a={id:s,role:"user",content:o||Ta,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 i=new AbortController;this.abortController=i;let p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:r},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=xl(d,this.config.errorMessage);if(u){let h={id:r,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(h)}}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 t=jo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;let r=s instanceof Error&&(s.name==="AbortError"||s.message.includes("aborted")||s.message.includes("abort"));if(!r){let a=xl(s,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,r||(s instanceof Error?this.callbacks.onError?.(s):this.callbacks.onError?.(new Error(String(s))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,s=!1;for(let r of this.messages)r.streaming&&r.id!==o&&(r.streaming=!1,s=!0);s&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(r instanceof Error?r:new Error(String(r)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(s=>{this.webMcpApprovalResolvers.set(o,s)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let s=this.messages.find(r=>r.id===t);s?.approval&&this.upsertMessage({...s,approval:{...s.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let s=`approval-${t.id}`,r={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===s),i={id:s,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:r};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let h=await c.json().catch(()=>null);throw new Error(h?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(s=>s.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let s=t.agentMetadata?.executionId,r=t.toolCall?.name;if(!s||!r){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let h=typeof u[0]?.question=="string"?u[0].question:"";h&&(a={[h]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,h)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let b=c[f],C=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${i}-${h}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${h}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(s,{[r]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let r=this.webMcpEpoch;queueMicrotask(()=>{r===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let s=this.webMcpAwaitBatches.get(n);s||(s={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,s)),!s.seen.has(o)&&(s.seen.add(o),s.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(s=>s.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==kn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,s=Date.now(),r){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...r},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:s,duration:void 0,durationMs:Math.max(0,s-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],s=[],r=new AbortController;this.webMcpResolveControllers.add(r),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=`${t}:${c}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let h=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===kn)return{dedupeKey:u,resumeKey:f,output:ll(),toolMessage:p,startedAt:h,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),s.push(b);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),T;if(!C)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await C}catch(L){let P=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return P||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,ms(P?"Aborted by cancel()":Ip(L)),h),this.webMcpInflightKeys.delete(u),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,ms("Aborted by cancel()"),h),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:T,toolMessage:p,startedAt:h,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:r.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===kn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of i)this.markWebMcpToolComplete(c.toolMessage,ms("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of s)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(r),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,s=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!s){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(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(b)}return}let r=`${n}:${s}`;if(this.webMcpInflightKeys.has(r)||this.webMcpResolvedKeys.has(r)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(r);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===kn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),h="execute",f=a;try{let b;if(d?b=ll():u?b=await u:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,ms("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;h="resume",await this.resumeWithToolOutput(n,C,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(r),this.markWebMcpToolComplete(t,b,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let C=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(h==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,ms(C||p.aborted?"Aborted by cancel()":Ip(b)),a),C||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(r),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,s){let r=await this.client.resumeFlow(t,{[n]:o},{signal:s?.signal});if(!r.ok){let a=await r.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${r.status}`)}s?.onHttpOk?.(),r.body?await this.connectStream(r.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=No(this.config.features?.artifacts,t.artifactType),s=ga(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),r=this.messages.find(a=>a.id===n);if(r){r.rawContent=s,r.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:s})}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Rp(),Pp)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,s)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:s}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>xl(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=jo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(r=>r.role==="assistant"&&r.content&&!r.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let s=bl(o.content);s.trim()&&this.readAloud.play(o.id,{text:s,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return gs(t)}toggleReadAloud(t){let n=this.messages.find(r=>r.id===t);if(!n||n.role!=="assistant")return;let o=bl(n.content||"");if(!o.trim())return;let s=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:s?.voice,rate:s?.rate,pitch:s?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(s=>s.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((s,r)=>{if(r!==o)return s;let a={...s,...n};if(s.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...s.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:s.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),s.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),s.approval&&n.approval&&s.approval.id===n.approval.id){let c=s.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&Wp(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),h=this.webMcpResolvedKeys.has(c),f=s.toolCall?.name,b=s.agentMetadata?.executionId===p&&s.toolCall?.id===d&&f!==void 0&&Wp(f)&&s.toolCall?.status==="complete";(u||h||b)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=s.toolCall,a.streaming=s.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let s=new Date(n.createdAt).getTime(),r=new Date(o.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(r)&&s!==r)return s-r;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};import{Activity as Qm,ArrowDown as Ym,ArrowUp as Zm,ArrowUpRight as eh,Bot as th,ChevronDown as nh,ChevronUp as oh,ChevronRight as rh,ChevronLeft as sh,Check as ah,Clipboard as ih,ClipboardCopy as lh,CodeXml as ch,Copy as dh,File as ph,FileCode as uh,FileSpreadsheet as fh,FileText as gh,ImagePlus as mh,Loader as hh,LoaderCircle as yh,Mic as bh,Paperclip as vh,RefreshCw as xh,Search as Ch,Send as wh,ShieldAlert as Ah,ShieldCheck as Sh,ShieldX as Th,Square as Eh,ThumbsDown as Mh,ThumbsUp as kh,Upload as Lh,Volume2 as Ph,X as Rh,User as Ih,Mail as Wh,Phone as Hh,Calendar as Bh,Clock as Dh,Building as Oh,MapPin as Nh,Lock as Fh,Key as _h,CreditCard as $h,AtSign as jh,Hash as Uh,Globe as zh,Link as qh,CircleCheck as Vh,CircleX as Kh,TriangleAlert as Gh,Info as Jh,Ban as Xh,Shield as Qh,ArrowLeft as Yh,ArrowRight as Zh,ExternalLink as ey,Ellipsis as ty,EllipsisVertical as ny,Menu as oy,House as ry,Plus as sy,Minus as ay,Pencil as iy,Trash as ly,Trash2 as cy,Save as dy,Download as py,Share as uy,Funnel as fy,Settings as gy,RotateCw as my,Maximize as hy,Minimize as yy,ShoppingCart as by,ShoppingBag as vy,Package as xy,Truck as Cy,Tag as wy,Gift as Ay,Receipt as Sy,Wallet as Ty,Store as Ey,DollarSign as My,Percent as ky,Play as Ly,Pause as Py,VolumeX as Ry,Camera as Iy,Image as Wy,Film as Hy,Headphones as By,MessageCircle as Dy,MessageSquare as Oy,Bell as Ny,Heart as Fy,Star as _y,Eye as $y,EyeOff as jy,Bookmark as Uy,CalendarDays as zy,History as qy,Timer as Vy,Folder as Ky,FolderOpen as Gy,Files as Jy,Sparkles as Xy,Zap as Qy,Sun as Yy,Moon as Zy,Flag as eb,Monitor as tb,Smartphone as nb}from"lucide";var ob={activity:Qm,"arrow-down":Ym,"arrow-up":Zm,"arrow-up-right":eh,bot:th,"chevron-down":nh,"chevron-up":oh,"chevron-right":rh,"chevron-left":sh,check:ah,clipboard:ih,"clipboard-copy":lh,"code-xml":ch,copy:dh,file:ph,"file-code":uh,"file-spreadsheet":fh,"file-text":gh,"image-plus":mh,loader:hh,"loader-circle":yh,mic:bh,paperclip:vh,"refresh-cw":xh,search:Ch,send:wh,"shield-alert":Ah,"shield-check":Sh,"shield-x":Th,square:Eh,"thumbs-down":Mh,"thumbs-up":kh,upload:Lh,"volume-2":Ph,x:Rh,user:Ih,mail:Wh,phone:Hh,calendar:Bh,clock:Dh,building:Oh,"map-pin":Nh,lock:Fh,key:_h,"credit-card":$h,"at-sign":jh,hash:Uh,globe:zh,link:qh,"circle-check":Vh,"circle-x":Kh,"triangle-alert":Gh,info:Jh,ban:Xh,shield:Qh,"arrow-left":Yh,"arrow-right":Zh,"external-link":ey,ellipsis:ty,"ellipsis-vertical":ny,menu:oy,house:ry,plus:sy,minus:ay,pencil:iy,trash:ly,"trash-2":cy,save:dy,download:py,share:uy,funnel:fy,settings:gy,"rotate-cw":my,maximize:hy,minimize:yy,"shopping-cart":by,"shopping-bag":vy,package:xy,truck:Cy,tag:wy,gift:Ay,receipt:Sy,wallet:Ty,store:Ey,"dollar-sign":My,percent:ky,play:Ly,pause:Py,"volume-x":Ry,camera:Iy,image:Wy,film:Hy,headphones:By,"message-circle":Dy,"message-square":Oy,bell:Ny,heart:Fy,star:_y,eye:$y,"eye-off":jy,bookmark:Uy,"calendar-days":zy,history:qy,timer:Vy,folder:Ky,"folder-open":Gy,files:Jy,sparkles:Xy,zap:Qy,sun:Yy,moon:Zy,flag:eb,monitor:tb,smartphone:nb},oe=(e,t=24,n="currentColor",o=2)=>{let s=ob[e];return s?rb(s,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function rb(e,t,n,o){if(!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",n),s.setAttribute("stroke-width",String(o)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(r=>{if(!Array.isArray(r)||r.length<2)return;let a=r[0],i=r[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),s.appendChild(p)}),s}var Ra={allowedTypes:$n,maxFileSize:10*1024*1024,maxFiles:4};function sb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ab(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var yr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ra.allowedTypes,maxFileSize:t.maxFileSize??Ra.maxFileSize,maxFiles:t.maxFiles??Ra.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ra.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Cp(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let s=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,s);continue}try{let s=await xp(n),r=Ma(n)?URL.createObjectURL(n):null,a={id:sb(),file:n,previewUrl:r,contentPart:s};this.attachments.push(a),this.renderPreview(a)}catch(s){console.error("[AttachmentManager] Failed to process file:",s)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(r=>r.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let s=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);s&&s.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ma(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=ab(t.file.type),p=oe(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=wp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let s=m("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let r=oe("x",10,"var(--persona-text-inverse, #ffffff)",2);r?s.appendChild(r):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(s),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Hp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ys(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];Hp(r)&&Hp(s)?n[o]=ys(r,s):n[o]=s}return n}var fn="min(440px, calc(100vw - 24px))",Cl="440px",ib={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:fn,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)"},ft={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:ib,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 Bp(e,t){if(!(!e&&!t))return e?t?ys(e,t):e:t}function wl(e){return e?{...ft,...e,theme:Bp(ft.theme,e.theme),darkTheme:Bp(ft.darkTheme,e.darkTheme),launcher:{...ft.launcher,...e.launcher,dock:{...ft.launcher?.dock,...e.launcher?.dock},clearChat:{...ft.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...ft.copy,...e.copy},sendButton:{...ft.sendButton,...e.sendButton},statusIndicator:{...ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...ft.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=ft.features?.artifacts,n=e.features?.artifacts,o=ft.features?.scrollToBottom,s=e.features?.scrollToBottom,r=ft.features?.scrollBehavior,a=e.features?.scrollBehavior,i=ft.features?.streamAnimation,p=e.features?.streamAnimation,d=ft.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},h=o===void 0&&s===void 0?void 0:{...o,...s},f=r===void 0&&a===void 0?void 0:{...r,...a},b=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...ft.features,...e.features,...h!==void 0?{scrollToBottom:h}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...b!==void 0?{streamAnimation:b}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??ft.suggestionChips,suggestionChipsConfig:{...ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ft.layout,...e.layout,header:{...ft.layout?.header,...e.layout?.header},messages:{...ft.layout?.messages,...e.layout?.messages,avatar:{...ft.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...ft.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...ft.layout?.slots,...e.layout?.slots}},markdown:{...ft.markdown,...e.markdown,options:{...ft.markdown?.options,...e.markdown?.options}},messageActions:{...ft.messageActions,...e.messageActions}}:ft}var Ia="16px",Wa="transparent",Dp={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"}},Op={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"}},Np={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:fn,maxWidth:Cl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ia,canvasBackground:Wa},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(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let s of n){if(o==null)return;o=o[s]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Gt(e,o):o}function Al(e){let t={};function n(o,s){for(let[r,a]of Object.entries(o)){let i=`${s}.${r}`;if(typeof a=="string"){let p=Gt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Fp(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function _p(e,t){let n={...e};for(let[o,s]of Object.entries(t)){let r=n[o];r&&typeof r=="object"&&!Array.isArray(r)&&s&&typeof s=="object"&&!Array.isArray(s)?n[o]=_p(r,s):n[o]=s}return n}function lb(e,t){return t?_p(e,t):e}function bs(e,t={}){let n={palette:Dp,semantic:Op,components:Np},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:lb(n.components,e?.components)};if(t.validate!==!1){let s=Fp(o);if(!s.valid)throw new Error(`Theme validation failed: ${s.errors.map(r=>r.message).join(", ")}`)}if(t.plugins)for(let s of t.plugins)o=s.transform(o);return o}function Sl(e){let t=Al(e),n={};for(let[w,U]of Object.entries(t)){let Q=w.replace(/\./g,"-");n[`--persona-${Q}`]=U.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-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"]??Ia,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Wa,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom);let s=e.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"]=s?.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 r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let 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=e.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 h=c?.labelButton;h&&(h.background&&(n["--persona-label-btn-bg"]=h.background),h.border&&(n["--persona-label-btn-border"]=h.border),h.color&&(n["--persona-label-btn-color"]=h.color),h.padding&&(n["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(n["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(n["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(n["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(n["--persona-label-btn-gap"]=h.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 w=b.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Gt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(b?.tab){let w=b.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(b?.pane){let w=b.pane;if(w.toolbarBackground){let U=Gt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(b?.card){let w=b.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(b?.inline){let w=b.inline;w.background&&(n["--persona-artifact-inline-bg"]=Gt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Gt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Gt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Gt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Gt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let C=c?.code;C&&(C.keywordColor&&(n["--persona-code-keyword-color"]=C.keywordColor),C.stringColor&&(n["--persona-code-string-color"]=C.stringColor),C.commentColor&&(n["--persona-code-comment-color"]=C.commentColor),C.numberColor&&(n["--persona-code-number-color"]=C.numberColor),C.tagColor&&(n["--persona-code-tag-color"]=C.tagColor),C.attrColor&&(n["--persona-code-attr-color"]=C.attrColor),C.propertyColor&&(n["--persona-code-property-color"]=C.propertyColor),C.lineNumberColor&&(n["--persona-code-line-number-color"]=C.lineNumberColor),C.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=C.gutterBorderColor),C.background&&(n["--persona-code-bg"]=Gt(e,C.background)??C.background));let T=n["--persona-surface"],L=n["--persona-container"],P=n["--persona-palette-colors-gray-100"]??"#f3f4f6",R=n["--persona-palette-colors-gray-200"]??"#e5e7eb",D=n["--persona-palette-colors-gray-300"]??"#d1d5db",z=!L||L===T,_=z?P:L,q=z?R:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??_,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??q,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"]??_,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??_,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??_,n}var cb={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var db={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"}}},$p=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ha=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",pb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ha()},Tl=e=>pb(e),ub=e=>bs(e),fb=e=>{let t=bs(void 0,{validate:!1});return bs({...e,palette:{...t.palette,colors:{...db.colors,...e?.palette?.colors}}},{validate:!1})},Vo=e=>{let t=Tl(e),n=$p(e?.theme),o=$p(e?.darkTheme);return t==="dark"?fb(ys(n??{},o??{})):ub(n)},gb=e=>Sl(e),br=(e,t)=>{let n=Vo(t),o=gb(n);for(let[s,r]of Object.entries(o))e.style.setProperty(s,r);e.setAttribute("data-persona-color-scheme",Tl(t))},vs=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ha())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ha());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Ln(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function jp(e){let t=Ln(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ba(e){if(typeof e!="string")return"";let t=e.indexOf(`
19
+ `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),s=o.lastIndexOf(`
20
+ `);return(s===-1?o:o.slice(0,s)).split("`\u200B``").join("```")}function xs(e){let t=jp(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function ao(e){switch(xs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=jp(e.path);return t?t.toUpperCase():"File"}}}function Up(e){let t=e.markdown??"";return e.file?{filename:Ln(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ba(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var El="http://www.w3.org/2000/svg";function zp(e){let t=document.createElementNS(El,"svg");t.setAttribute("class",Fo("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.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"),t.appendChild(n),t.appendChild(o),t}var io=(e,t,n)=>{let o=n;for(let s of t){let r=m("span","persona-tool-char");r.style.setProperty("--char-index",String(o)),r.textContent=s===" "?"\xA0":s,e.appendChild(r),o++}return o};function qp(e,t,n){let o=n?.loadingAnimation??"shimmer",s=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${s}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),io(e,t,0)}var Ml="persona-artifact-status-label",Vp="persona-artifact-status-detail",Kp="data-artifact-status-label",kl=new Map,Gp=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function vr(e){e&&kl.delete(e)}function mb(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?ao(t):e.artifactType==="component"?"Component":"Document"}function xr(e,t,n){let o=mb(e),s=`Generating ${o.toLowerCase()}...`,r=t?.statusLabel;if(typeof r=="string")return{label:r};if(typeof r!="function")return{label:s};let a=e.id,i=kl.get(a);e.status!=="complete"&&i===void 0&&(i=Gp(),kl.set(a,i));let p=i===void 0?0:Math.max(0,Gp()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,h=d||c===""?0:c.split(`
21
+ `).length,f=e.artifactType==="markdown"?e.file:void 0,b={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:h,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=r(b);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:s}}catch{return{label:s}}}function hb(e){e.className=Ml,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function Ko(e,t,n){let o=e.querySelector(`:scope > .${Ml}`);o||(o=m("span",Ml),e.appendChild(o)),o.getAttribute(Kp)!==t.label&&(hb(o),qp(o,t.label,n),o.setAttribute(Kp,t.label));let s=e.querySelector(`:scope > .${Vp}`),r=t.detail;r?(s||(s=m("span",Vp),e.appendChild(s)),s.textContent!==r&&(s.textContent=r)):s&&s.remove()}var yb={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"},bb=15e4,Da={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 vb(e,t){let n=(e||"").trim().toLowerCase();if(n&&Da[n])return Da[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let s=t.slice(o+1).toLowerCase();if(Da[s])return Da[s]}}return null}function Oa(e,t){let n=[],o=0,s=0,r=a=>{a>s&&n.push({type:"plain",value:e.slice(s,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){r(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,s=o,a=!0;break}}a||(o+=1)}return r(e.length),n}var xb=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"]),Cb=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:e=>xb.has(e)?"keyword":"plain"}];function Jp(e){return Oa(e,Cb)}var wb=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function Ab(e){let t=Oa(e,wb);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let s=t[o];s&&s.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var Sb=[{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 Xp(e){let t=Oa(e,Sb),n="";for(let o=0;o<t.length;o+=1){let s=t[o];if(s.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(s.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(s.type="property")}let r=s.value.replace(/\s+$/,"");r&&(n=r[r.length-1])}return t}var Tb=[{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 Eb(e){let t=[],n=(r,a)=>{a&&t.push({type:r,value:a})},o=e.length,s=0;for(;s<o;){if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4),i=a===-1?o:a+3;n("comment",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&e[s+1]==="!"){let a=e.indexOf(">",s),i=a===-1?o:a+1;n("tag",e.slice(s,i)),s=i;continue}if(e[s]==="<"&&/[A-Za-z/]/.test(e[s+1]||"")){let a=e.indexOf(">",s),i=a===-1?o:a+1,p=e.slice(s,i);for(let c of Oa(p,Tb))t.push(c);s=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),h=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(s)),f=h?s+h.index:o,b=e.slice(s,f),C=c==="script"?Jp(b):Xp(b);for(let T of C)t.push(T);s=f}continue}let r=e.indexOf("<",s);if(r===s)n("plain",e[s]),s+=1;else{let a=r===-1?o:r;n("plain",e.slice(s,a)),s=a}}return t}function Mb(e,t){switch(t){case"html":return Eb(e);case"css":return Xp(e);case"js":return Jp(e);case"json":return Ab(e)}}function kb(e){let t=Gd(),n=m("span","persona-code-line"),o=(s,r)=>{if(!r)return;let a=yb[s];if(a){let i=m("span",a);i.textContent=r,n.appendChild(i)}else n.appendChild(document.createTextNode(r))};for(let s of e){let r=s.value.split(`
22
+ `);for(let a=0;a<r.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
23
+ `)),n=m("span","persona-code-line")),o(s.type,r[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Qp(e,t,n){let o=e.length<=bb?vb(t,n):null,s=o?Mb(e,o):[{type:"plain",value:e}];return kb(s)}var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,lo=Ut+1;function Go(e){let{items:t,onSelect:n,anchor:o,position:s="bottom-left",portal:r}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),r?(a.style.position="fixed",a.style.zIndex=String(lo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}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 T=oe(f.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let C=document.createElement("span");C.textContent=f.label,b.appendChild(C),b.addEventListener("click",T=>{T.stopPropagation(),c(),n(f.id)}),a.appendChild(b)}let i=null;function p(){if(!r)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,s==="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),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function h(){c(),a.remove()}return r&&r.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:h}}function mt(e){let{icon:t,label:n,size:o,strokeWidth:s,className:r,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(r?" "+r:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=oe(t,o??16,"currentColor",s??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function co(e){let{icon:t,label:n,variant:o="default",size:s="sm",iconSize:r,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+s,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let h=oe(t,r??14,"currentColor",2);h&&c.appendChild(h)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[h,f]of Object.entries(p))c.setAttribute(h,f);return c}function po(e){let{items:t,selectedId:n,onSelect:o,className:s}=e,r=m("div","persona-toggle-group"+(s?" "+s:""));r.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=mt({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"),i.push({id:c.id,btn:u}),r.appendChild(u)}function d(c){a=c,p()}return{element:r,setSelected:d}}function Ll(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:s,position:r="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=oe(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 h=Go({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),s(f)},anchor:d,position:r,portal:a});return a||d.appendChild(h.element),d.addEventListener("click",f=>{f.stopPropagation();let b=!h.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),h.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"),h.show()},close:()=>{d.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let f=!h.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),d.remove()}}}var Na="persona-artifact-custom-action-btn";function Cr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let s="persona-label-btn persona-label-btn--sm "+Na+(n?" persona-artifact-doc-copy-btn":"");o=m("button",s)}else{let s="persona-icon-btn "+Na+(n?" persona-artifact-doc-icon-btn":"");o=m("button",s)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let s=e.icon();s&&o.appendChild(s)}catch{}if(e.showLabel){let s=m("span");s.textContent=e.label,o.appendChild(s)}}else e.showLabel||!e.icon?o=co({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-copy-btn":"")}):o=mt({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Cs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function Yp(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=n?Ln(n.path):o,r=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?ao(n):i==="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 ${s} in artifact panel`),r&&d.setAttribute("data-open-artifact",r);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 h=document.createElement("div");h.className="persona-truncate persona-text-sm persona-font-medium",h.style.color="var(--persona-text, #1f2937)",h.textContent=s;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=t?.config?.features?.artifacts,C={id:r,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},T=xr(C,b,"card");Ko(f,T,b)}else r&&vr(r),f.textContent=p;if(u.append(h,f),d.append(c,u),a==="complete"){let b=t?.config?.features?.artifacts?.cardActions;if(b&&b.length>0){let T={artifactId:r||null,title:s,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of b)try{if(L.visible===void 0||L.visible(T)){let P=Cr(L);P.setAttribute("data-artifact-custom-action",L.id),P.className=`${P.className} persona-flex-shrink-0`,d.append(P)}}catch{}}let C=co({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${s}`,C.setAttribute("data-download-artifact",r),d.append(C)}return d}var Fa=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>Yp(e,t)});if(i)return i}return Yp(e,t)};var uo=new WeakMap;function Pl(e,t,n){if(t.length===0)return;let o=new Map(t.map(s=>[s.id,s]));e.querySelectorAll("[data-artifact-inline]").forEach(s=>{let r=uo.get(s);if(!r)return;let a=o.get(s.getAttribute("data-artifact-inline")??"");a&&r(a,n)})}function ou(e){return uo.has(e)}function Lb(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let r=e.componentProps,a=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{}}}function Zp(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Ln(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?ao(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Pb(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var eu=180,Rb=240,Ib=.8,Wb=300,Hb=500,Bb="cubic-bezier(0.2, 0, 0, 1)",tu=240,Db=.35;function Ob(e,t,n){let{swap:o,onSettled:s}=n,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(!t||!e.isConnected||r||typeof e.animate!="function"){o(),s();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:eu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),s();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),s();return}let d=Math.abs(t-p),c=Math.round(Math.min(Hb,Math.max(Wb,Rb+d*Ib))),u=Math.round(c*Db),h=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=h?h.animate([{opacity:0},{opacity:1}],{duration:tu,delay:u,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Bb});e.style.height=`${p}px`;let C=!1,T=()=>{C||(C=!0,i(),s())};Promise.allSettled([b.finished,f?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,u+tu)+120)},eu)}function Nb(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var ws="--persona-artifact-inline-body-height";function Fb(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",s=320,r=320,a=t?.height;typeof a=="number"||a==="auto"?(s=a,r=a):a&&typeof a=="object"&&(s=a.streaming??320,r=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.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):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let h=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:s,completeHeight:r,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:h,completeDisplay:f}}function nu(e,t){let n=Lb(e),o=t.config?.features?.artifacts,{chromeEnabled:s,showCopy:r,showExpand:a,showViewToggle:i}=Nb(o),p=o?.inlineActions??[],d=Fb(o),c=d.completeDisplay==="card",u=null,h=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=Y=>Fa(Pb(Y),t),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ws),f.replaceChildren(b(Y)),uo.set(f,ce=>{f.replaceChildren(b(ce))})};if(c&&n.status==="complete")return C(n),f;let T=_a(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(T.el);let P=Y=>{let ce=Y.status!=="complete",Z=ce?d.streamingHeight:d.completeHeight,xe=typeof Z=="number";xe?f.style.setProperty(ws,`${Z}px`):f.style.removeProperty(ws);let me=!!T.el.querySelector(".persona-code-pre"),fe=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",me),L.classList.toggle("persona-artifact-inline-body--sized",xe&&fe),L.classList.toggle("persona-artifact-inline-body--cap",!ce&&!fe&&typeof d.completeHeight=="number")},R=n.status,D=(Y,ce)=>{R!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(ws,`${d.completeHeight}px`):f.style.removeProperty(ws),su(L,ce?.suppressTransition?"none":d.transition,Y.id,()=>{T.update(Y),P(Y)})):T.update(Y),P(Y),R=Y.status};P(n);let z=d.overflow==="clip"&&a&&!!n.id;if(z&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Zp(n).title} in panel`)),!s)return f.appendChild(L),uo.set(f,D),f;let _=m("div","persona-artifact-inline-chrome");_.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let q=m("div","persona-artifact-inline-chrome-lead"),w=m("span","persona-flex persona-items-center persona-flex-shrink-0"),U=oe("file-text",16,"currentColor",2);U&&w.appendChild(U);let Q=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),B=m("span","persona-artifact-inline-type");q.append(w,Q,B);let $=m("div","persona-artifact-inline-chrome-actions"),pe=m("span","persona-flex persona-items-center persona-gap-1"),ye=()=>u??d.viewMode,Te=i?po({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:ye(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ce=Y==="source"?"source":"rendered";ce!==ye()&&(u=ce,T.update(h),P(h))}}):null,De=r?mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let re=a?mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;re&&n.id&&re.setAttribute("data-expand-artifact-inline",n.id),$.appendChild(pe),Te&&$.appendChild(Te.element),De&&$.appendChild(De),re&&$.appendChild(re),_.append(q,$),f.append(_,L);let be=Y=>{let{title:ce,typeLabel:Z}=Zp(Y);Q.textContent=ce,Q.title=ce,z&&L.setAttribute("aria-label",`Open ${ce} in panel`);let xe=Y.status!=="complete";if(xe){B.classList.contains("persona-artifact-inline-status")||(B.className="persona-artifact-inline-status",B.removeAttribute("data-preserve-animation"),B.replaceChildren());let me=xr(Y,o,"inline-chrome");Ko(B,me,o)}else vr(Y.id),B.className="persona-artifact-inline-type",B.removeAttribute("data-preserve-animation"),B.replaceChildren(),B.textContent=Z;if(De&&De.classList.toggle("persona-hidden",xe),Te){let me=Y.artifactType==="markdown"?Y.file:void 0,fe=!1;if(!xe&&me&&d.viewMode!=="source"){let Pe=xs(me);Pe==="markdown"?fe=!0:(Pe==="html"||Pe==="svg")&&(fe=o?.filePreview?.enabled!==!1)}Te.element.classList.toggle("persona-hidden",!fe),Te.setSelected(ye())}if(pe.replaceChildren(),!xe&&p.length>0){let me=Cs(Y);if(me)for(let fe of p)try{if(fe.visible===void 0||fe.visible(me)){let Pe=Cr(fe,{documentChrome:!0});Pe.setAttribute("data-artifact-custom-action",fe.id),Pe.classList.add("persona-flex-shrink-0"),pe.appendChild(Pe)}}catch{}}};return be(n),uo.set(f,(Y,ce)=>{if(c&&R!=="complete"&&Y.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;R="complete";let xe=Y,me=!1,fe=Pe=>{xe=Pe,me=!0};uo.set(f,fe),Ob(f,Z,{swap:()=>{C(xe),me=!1,uo.set(f,fe)},onSettled:()=>{me?C(xe):uo.set(f,Pe=>{f.replaceChildren(b(Pe))})}});return}(Y.status!=="complete"||Y.id!==h.id)&&(u=null),h=Y,D(Y,ce),be(Y)}),f}var ru=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",s=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:s,title:o,artifactType:a,status:r},config:t.config,defaultRenderer:()=>nu(e,t)});if(i)return i}return nu(e,t)};var Rl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Pn=new Rl;Pn.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});Pn.register("PersonaArtifactInline",ru,{bubbleChrome:!1});function As(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ba(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Il=!1;function _b(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function su(e,t,n,o){let s=typeof document<"u"?document.startViewTransition:void 0,r=!1;try{r=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{r=!1}if(t!=="auto"||!e||typeof s!="function"||Il||r){o();return}Il=!0;let a=_b(n);e.style.setProperty("view-transition-name",a);let i=()=>{Il=!1,e.style.removeProperty("view-transition-name")};try{s.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var $b="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",jb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Ub(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function zb(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var qb=220;function Vb(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Kb(e){return`
24
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function Gb(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let s=m("div","persona-artifact-frame-loading-indicator");s.appendChild(zp());let r=null;return n.label!==!1&&(r=m("div","persona-artifact-frame-loading-text"),r.textContent=n.label,s.appendChild(r)),o.appendChild(s),{el:o,revealLabel:()=>{r&&r.classList.add("persona-artifact-frame-loading-text--visible")}}}function Jb(e,t,n,o,s,r){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(R=>clearTimeout(R)),d.clear()},u=(R,D)=>{let z=setTimeout(()=>{d.delete(z),R()},D);d.add(z)},h=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let R=Gb(s,r,o);a=R.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(R.revealLabel,o.labelDelayMs)},b=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(h,qb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",P)},T=()=>{if(p||(p=!0,C(),c(),!a))return;let R=Math.max(0,o.minVisibleMs-(Date.now()-i));R>0?u(b,R):b()};function L(R){if(n===null)return;let D=R.data;!D||D.persona!=="artifact-preview-ready"||D.token!==n||R.source===t.contentWindow&&T()}function P(){let R=D=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>D()):setTimeout(D,0)};R(()=>R(()=>T()))}return u(f,o.delayMs),u(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",P),()=>{p=!0,c(),C(),h()}}function _a(e,t){let{config:n}=t,o=t.registry??Pn,s=t.bodyLayout,r=n.markdown?pr(n.markdown):null,a=ns(n.sanitize),i=e,p=!1,d=re=>{let be=Fn()!==null;r&&!be&&!p&&(p=!0,ts(()=>De(i)));let Y=r?r(re):_n(re);return r&&be&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,h=null,f=null,b=()=>{f&&(f(),f=null),u=null,h=null},C=null,T=null,L=null,P=!1,R=()=>{C=null,T=null,L=null,P=!1},D=null,z=null,_=()=>{D=null,z=null},q=40,w=0,U=re=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>re()):setTimeout(re,0),Q=re=>re.scrollHeight-re.clientHeight-re.scrollTop<=q,B=re=>{if(!s)return;let be=re.scrollHeight-re.clientHeight>1,Y=re.scrollHeight-re.clientHeight-re.scrollTop;re.classList.toggle("persona-artifact-fade-top",s.fadeTop&&be&&re.scrollTop>1),re.classList.toggle("persona-artifact-fade-bottom",s.fadeBottom&&be&&Y>1)},$=re=>{w||(w=U(()=>{w=0,re.scrollTop=re.scrollHeight,B(re)}))},pe=(re,be,Y,ce)=>{let Z=!!s,xe=Y.id+"|"+(Z?"w":"p");if(!C||L!==xe||C.parentElement!==c){b(),_(),c.replaceChildren();let Pe=m("pre",$b+" persona-code-pre"),Oe=m("code","persona-code");if(Pe.appendChild(Oe),Z){let je=m("div","persona-artifact-source-window");if(je.appendChild(Pe),c.appendChild(je),!(s?.overflow==="clip")&&typeof je.addEventListener=="function"){let we=()=>je.scrollHeight-je.clientHeight>1;je.addEventListener("scroll",()=>{Q(je)&&(P=!1),B(je)},{passive:!0}),je.addEventListener("wheel",Le=>{we()&&Le.deltaY<0&&(P=!0)},{passive:!0}),je.addEventListener("touchmove",()=>{we()&&(P=!0)},{passive:!0})}C=je}else c.appendChild(Pe),C=Pe;T=Oe,L=xe}let me=Z?C:null;me&&(me.classList.toggle("persona-artifact-source-window--fixed",ce),me.classList.toggle("persona-artifact-source-window--clip",ce&&s?.overflow==="clip"));let fe=me?Q(me):!0;if(T.replaceChildren(Qp(re,be?.language,be?.path)),me){let Pe=Y.status!=="complete";ce&&Pe&&s?.followOutput&&!P&&fe?$(me):Pe||(P=!1),B(me)}},ye=re=>{b(),R(),_(),c.replaceChildren();let be=m("div",jb);be.innerHTML=d(re),c.appendChild(be)},Te=re=>{let be=re.id,Y=n.features?.artifacts,ce=xr(re,Y,"status-body");if(D&&z===be&&D.parentElement===c){let me=D.querySelector(".persona-artifact-status-view-text");me&&Ko(me,ce,Y);return}b(),R(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),xe=m("div","persona-artifact-status-view-text");Ko(xe,ce,Y),Z.appendChild(xe),c.appendChild(Z),D=Z,z=be},De=re=>{i=re;let be=t.resolveViewMode?.(re)??s?.viewMode??"rendered",Y=re.artifactType==="markdown"?re.file:void 0,ce=re.status!=="complete";ce||vr(re.id);let Z=ce?s?.streamingHeight:s?.completeHeight,xe=!!s&&typeof Z=="number";if(s?.streamingView==="status"&&ce){Te(re);return}if(Y){let fe=Ba(re.markdown??""),Pe=xs(Y),Oe=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&be==="rendered"&&Oe&&(Pe==="html"||Pe==="svg")){let Ne=re.id+"\0"+fe;if(u&&h===Ne&&u.parentElement===c)return;R(),_(),b(),c.replaceChildren();let we=n.features?.artifacts?.filePreview,Le=we?.iframeSandbox??"allow-scripts";!we?.dangerouslyAllowSameOrigin&&Le.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."),Le=Le.split(/\s+/).filter(yt=>yt&&yt!=="allow-same-origin").join(" "));let ot=zb(we?.loading),ie=m("div","persona-artifact-frame"),Re=m("iframe","persona-artifact-iframe");Re.setAttribute("sandbox",Le),Re.setAttribute("data-artifact-id",re.id);let xt=null;ot.enabled&&ot.injectReadySignal?(xt=Vb(),Re.srcdoc=fe+Kb(xt)):Re.srcdoc=fe,ie.appendChild(Re),c.appendChild(ie),ot.enabled&&(f=Jb(ie,Re,xt,ot,re.id,n)),u=ie,h=Ne;return}if(b(),!ce&&Pe==="markdown"&&be==="rendered"){ye(fe);return}pe(fe,{language:Y.language,path:Y.path},re,xe);return}if(re.artifactType==="markdown"){if(be==="source"){b(),pe(re.markdown??"",void 0,re,xe);return}ye(re.markdown??"");return}b(),R(),_(),c.replaceChildren();let me=re.component?o.get(re.component):void 0;if(me){let Pe={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Oe=me(re.props??{},Pe);if(Oe){c.appendChild(Oe);return}}catch{}}c.appendChild(Ub(re))};return De(e),{el:c,update(re){De(re)}}}import{Idiomorph as Xb}from"idiomorph";var $a=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Xb.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,r){if(s instanceof HTMLElement&&o){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-tool-elapsed"))return r instanceof HTMLElement&&r.getAttribute("data-tool-elapsed")===s.getAttribute("data-tool-elapsed")?!1:void 0;if(s.hasAttribute("data-preserve-animation")){if(r instanceof HTMLElement&&!r.hasAttribute("data-preserve-animation"))return;if(r instanceof HTMLElement&&r.hasAttribute("data-preserve-animation")){let a=s.textContent??"",i=r.textContent??"";if(a!==i)return}return!1}}}}})};var au=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ja={index:-1,draft:""};function iu(e){let{direction:t,history:n,currentValue:o,atStart:s,state:r}=e,a=r.index!==-1;if(n.length===0)return{handled:!1,state:r};if(t==="up"){if(!a&&!s)return{handled:!1,state:r};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(r.index>0){let i=r.index-1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,state:r}}if(!a)return{handled:!1,state:r};if(r.index<n.length-1){let i=r.index+1;return{handled:!0,value:n[i],state:{index:i,draft:r.draft}}}return{handled:!0,value:r.draft,state:{...ja}}}function lu(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function cu(){return new Map}function du(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function pu(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function uu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Ua(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Rn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function fo(e,t){return Rn(e)-e.scrollTop<=t}function za(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:s,userScrollThreshold:r,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<r?{action:"none",delta:c,nextLastScrollTop:n}:!t&&s&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!s?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function qa(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:s=!1}=e;return t&&n<0?"pause":!t&&s&&n>0&&o?"resume":"none"}function fu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function gu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ss={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Qb=["pre","code","a","script","style"],Va=e=>({type:e?.type??Ss.type,placeholder:e?.placeholder??Ss.placeholder,speed:e?.speed??Ss.speed,duration:e?.duration??Ss.duration,buffer:e?.buffer??Ss.buffer}),yu=[{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"}],Ts=new Map;for(let e of yu)Ts.set(e.name,e);var Yb=e=>{Ts.set(e.name,e)},Zb=e=>{yu.some(t=>t.name===e)||Ts.delete(e)},ev=()=>Array.from(Ts.keys()),wr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ts.get(e)??null,Ka=(e,t,n,o,s)=>{if(!s)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let r=e.search(/\s(?=\S*$)/);return r<0?"":e.slice(0,r)}if(t==="line"){let r=e.lastIndexOf(`
25
+ `);return r<0?"":e.slice(0,r)}return e},tv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${n}-${o}`,s.style.setProperty("--char-index",String(o)),s.textContent=t,s},nv=(e,t,n,o)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${n}-${o}`,s.style.setProperty("--word-index",String(o)),s.textContent=t,s},Wl=/\s/,ov=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},rv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=0;for(;i<r.length;)if(Wl.test(r[i])){let p=i;for(;p<r.length&&Wl.test(r[p]);)p+=1;a.appendChild(o.createTextNode(r.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<r.length&&!Wl.test(r[d]);)p.appendChild(tv(o,r[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}s.replaceChild(a,e)},sv=(e,t,n)=>{let o=e.ownerDocument,s=e.parentNode;if(!o||!s)return;let r=e.nodeValue??"";if(!r)return;let a=o.createDocumentFragment(),i=r.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(nv(o,p,t,n.value)),n.value+=1));s.replaceChild(a,e)},Es=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let s=document.createElement("div");s.innerHTML=e;let r=new Set((o?.skipTags??Qb).map(u=>u.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)ov(p,r)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?rv:sv;for(let u of i)c(u,n,d);return s.innerHTML},Ga=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ms=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},hu=new WeakMap,av=(e,t)=>{if(!e.styles)return;let n=hu.get(t);if(n||(n=new Set,hu.set(t,n)),n.has(e.name)){let r=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${r}"]`))return;n.delete(e.name)}n.add(e.name);let s=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,t.appendChild(s)},Hl=new WeakMap,iv=(e,t)=>{if(!e.onAttach)return;let n=Hl.get(t);if(n||(n=new Map,Hl.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},bu=e=>{let t=Hl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ja=(e,t)=>{av(e,t),iv(e,t)};function Bl(e,t=Ut){let n=e.style.position,o=e.style.zIndex,s=e.style.isolation,r=getComputedStyle(e),a=r.position==="static"||r.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=s}}var ks=0,go=null;function Dl(e=document){if(ks++,ks===1){let n=e.body,s=(e.defaultView??window).scrollY||e.documentElement.scrollTop;go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:s},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${s}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,ks=Math.max(0,ks-1),ks===0&&go)){let n=e.body,o=e.defaultView??window;n.style.overflow=go.originalOverflow,n.style.position=go.originalPosition,n.style.top=go.originalTop,n.style.width=go.originalWidth,o.scrollTo(0,go.scrollY),go=null}}}var Ls={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Bt=e=>(e?.launcher?.mountMode??"floating")==="docked",mo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",sn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ls.side,width:t?.width??Ls.width,animate:t?.animate??Ls.animate,reveal:t?.reveal??Ls.reveal,maxHeight:t?.maxHeight??Ls.maxHeight}};var wn={"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 lv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Xa=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=lv,buttonSize:s,iconSize:r="28px"}=t,a=e?.launcher??{},i=s??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",h=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=nt("button",{className:Fo("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Jt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=oe(u,r,"currentColor",1);if(C?(C.style.display="block",b.appendChild(C)):b.textContent=h,p.appendChild(b),c&&d){let T=null,L=()=>{if(T)return;let R=b.ownerDocument,D=R.body;if(!D)return;T=Mn(R,"div","persona-clear-chat-tooltip"),T.textContent=d;let z=Mn(R,"div");z.className="persona-clear-chat-tooltip-arrow",T.appendChild(z);let _=b.getBoundingClientRect();T.style.position="fixed",T.style.zIndex=String(lo),T.style.left=`${_.left+_.width/2}px`,T.style.top=`${_.top-8}px`,T.style.transform="translate(-50%, -100%)",D.appendChild(T)},P=()=>{T&&T.parentNode&&(T.parentNode.removeChild(T),T=null)};p.addEventListener("mouseenter",L),p.addEventListener("mouseleave",P),b.addEventListener("focus",L),b.addEventListener("blur",P),p._cleanupTooltip=()=>{P(),p.removeEventListener("mouseenter",L),p.removeEventListener("mouseleave",P),b.removeEventListener("focus",L),b.removeEventListener("blur",P)}}return{button:b,wrapper:p}},cv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qa=(e,t={})=>{let{wrapperClassName:n=cv,buttonSize:o,iconSize:s="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",h=a.borderColor??"",f=a.borderRadius??"",b=a.paddingX??"",C=a.paddingY??"",T=a.tooltipText??"Clear chat",L=a.showTooltip??!0,P=m("div",n),R=!!(u||h),D=nt("button",{className:Fo("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":T},style:{height:i,width:i,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:R?`${u||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=oe(p,s,"currentColor",1);if(z&&(z.style.display="block",D.appendChild(z)),P.appendChild(D),L&&T){let _=null,q=()=>{if(_)return;let U=D.ownerDocument,Q=U.body;if(!Q)return;_=Mn(U,"div","persona-clear-chat-tooltip"),_.textContent=T;let B=Mn(U,"div");B.className="persona-clear-chat-tooltip-arrow",_.appendChild(B);let $=D.getBoundingClientRect();_.style.position="fixed",_.style.zIndex=String(lo),_.style.left=`${$.left+$.width/2}px`,_.style.top=`${$.top-8}px`,_.style.transform="translate(-50%, -100%)",Q.appendChild(_)},w=()=>{_&&_.parentNode&&(_.parentNode.removeChild(_),_=null)};P.addEventListener("mouseenter",q),P.addEventListener("mouseleave",w),D.addEventListener("focus",q),D.addEventListener("blur",w),P._cleanupTooltip=()=>{w(),P.removeEventListener("mouseenter",q),P.removeEventListener("mouseleave",w),D.removeEventListener("focus",q),D.removeEventListener("blur",w)}}return{button:D,wrapper:P}};var Jt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ho=e=>{let{config:t,showClose:n=!0}=e,o=nt("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)))"}}),s=t?.launcher??{},r=s.headerIconSize??"48px",a=s.closeButtonPlacement??"inline",i=s.headerIconHidden??!1,p=s.headerIconName,d=nt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:r,width:r,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let z=parseFloat(r)||24,_=oe(p,z*.6,"currentColor",1);_?d.replaceChildren(_):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let z=m("img");z.src=t.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=r,z.style.width=r,d.replaceChildren(z)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=nt("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),h=nt("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});c.append(u,h),i?o.append(c):o.append(d,c);let f=s.clearChat??{},b=f.enabled??!0,C=f.placement??"inline",T=null,L=null;if(b){let _=Qa(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=_.button,L=_.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:R,wrapper:D}=Xa(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&o.appendChild(D),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:h,closeButton:R,closeButtonWrapper:D,clearChatButton:T,clearChatButtonWrapper:L}},Ar=(e,t,n)=>{let o=n?.launcher??{},s=o.closeButtonPlacement??"inline",r=o.clearChat?.placement??"inline";e.appendChild(t.header),s==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&r==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var vu=e=>{let t=ho({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function dv(e,t,n){if(t?.length)for(let o of t){let s=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(s.type="button",s.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let r=oe(o.icon,14,"currentColor",2);r&&s.appendChild(r)}else o.label&&(s.textContent=o.label);if(o.menuItems?.length){let r=m("div","persona-relative");r.appendChild(s);let a=Go({items:o.menuItems,onSelect:i=>n?.(i),anchor:r,position:"bottom-left"});r.appendChild(a.element),s.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(r)}else s.addEventListener("click",()=>n?.(o.id)),e.appendChild(s)}}var xu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:s,onHeaderAction:r}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s?.titleMenu,d,c;if(p)d=Ll({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Jt.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=Jt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),dv(d,s?.trailingActions,s?.onAction??r),s?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let R=s.onTitleClick;d.addEventListener("click",D=>{D.target.closest("button")||R()}),d.addEventListener("keydown",D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),R())})}let P=s?.titleRowHover;P&&(d.style.borderRadius=P.borderRadius??"10px",d.style.padding=P.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=P.background??"",d.style.borderColor=P.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",h=m("div",""),f=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Jt.actionIconColor;let b=a.closeButtonIconName??"x",C=oe(b,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),h.appendChild(f),i.appendChild(h);let T=m("div");T.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:T,headerTitle:c,headerSubtitle:L,closeButton:f,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},Ol={default:vu,minimal:xu},Cu=e=>Ol[e]??Ol.default,Ps=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let 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:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",r=Cu(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(r.iconHolder.style.display="none"),t.showTitle===!1&&(r.headerTitle.style.display="none"),t.showSubtitle===!1&&(r.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(r.closeButton.style.display="none"),t.showClearChat===!1&&r.clearChatButtonWrapper&&(r.clearChatButtonWrapper.style.display="none")),r};var Ya=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let s=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},r=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,s());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:r}},Za=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",s=t.iconName,r=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",h=t.backgroundColor,f=t.textColor,b=m("div","persona-send-button-wrapper"),C=nt("button",{className:Fo("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&&!h&&"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&&h||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,L=null;if(n){let z=parseFloat(u)||24,_=f?.trim()||"currentColor";s?(T=oe(s,z,_,2),T?C.appendChild(T):C.textContent=o):C.textContent=o,L=oe(r,z,_,2)}else C.textContent=p;let P=null;c&&a&&(P=m("div","persona-send-button-tooltip"),P.textContent=a,b.appendChild(P)),C.setAttribute("aria-label",a),b.appendChild(C);let R="send";return{button:C,wrapper:b,setMode:z=>{if(z===R)return;R=z;let _=z==="stop"?i:a;if(C.setAttribute("aria-label",_),P&&(P.textContent=_),n){if(T&&L){let q=z==="stop"?L:T;C.replaceChildren(q)}}else C.textContent=z==="stop"?d:p}}},ei=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),s=t.provider?.type==="runtype";if(!(o||s))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,h=m("div","persona-send-button-wrapper"),f=nt("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:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=oe(i,d,u||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",h.appendChild(f);let T=t.tooltipText??"Start voice recognition";if((t.showTooltip??!1)&&T){let P=m("div","persona-send-button-tooltip");P.textContent=T,h.appendChild(P)}return{button:f,wrapper:h}},ti=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let s=m("input");s.type="file",s.setAttribute("data-persona-composer-attachment-input",""),s.accept=(t.allowedTypes??$n).join(","),s.multiple=(t.maxFiles??4)>1,s.style.display="none",s.setAttribute("aria-label","Attach files");let r=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=nt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",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=oe(r,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",b=>{b.preventDefault(),s.click()}),d.appendChild(c);let h=t.buttonTooltipText??"Attach file",f=m("div","persona-send-button-tooltip");return f.textContent=h,d.appendChild(f),{button:c,wrapper:d,input:s,previewsContainer:o}},ni=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let s=t.visible??!0;o.style.display=s?"":"none";let r=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=r,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=r;return o},oi=()=>nt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Rs=e=>{let{config:t}=e,n=nt("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=oi(),s=nt("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:r,attachAutoResize:a}=Ya(t);a();let i=Za(t),p=ei(t),d=ti(t),c=ni(t);d&&(d.previewsContainer.style.gap="8px",s.append(d.previewsContainer,d.input)),s.append(r);let u=nt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=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&&h.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),u.append(h,f),s.append(u),s.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&r.focus()}),n.append(o,s,c),{footer:n,suggestions:o,composerForm:s,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:h,rightActions:f,setSendButtonMode:i.setMode}};var wu=()=>{let e=nt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),s=m("span","persona-pill-peek__caret"),r=oe("chevron-up",16,"currentColor",1.5);return r&&s.appendChild(r),e.append(t,o,s),{root:e,textNode:o}},Au=e=>{let{config:t}=e,n=nt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=oi(),s=ni(t);s.style.display="none";let{textarea:r,attachAutoResize:a}=Ya(t);r.style.maxHeight="100px",a();let i=Za(t),p=ei(t),d=ti(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=nt("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 h=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&h.append(p.wrapper),h.append(i.wrapper),c.addEventListener("click",b=>{b.target!==i.button&&b.target!==i.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&r.focus()}),d&&c.append(d.input),c.append(u,r,h),d&&n.append(d.previewsContainer),n.append(o,c,s);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:r,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:s,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:h,setSendButtonMode:i.setMode}};var Su=e=>{let t=e?.launcher?.enabled??!0,n=Bt(e);if(mo(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Ut);let h=m("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");h.style.width="100%",u.appendChild(h);let f=m("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:u,panel:h,pillRoot:f}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),h=e?.launcher?.width??"100%";return c.style.width=h,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let s=e?.launcher??{},r=s.position&&wn[s.position]?wn[s.position]:wn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${r} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Ut);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??fn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},pv=(e,t)=>{let n=m("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:s}=Xa(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});s.style.position="absolute",s.style.top="8px",s.style.right="8px",s.style.zIndex="10";let r=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(r){let D=Qa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=D.button,i=D.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=nt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=nt("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=nt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=nt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),h=nt("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=e?.layout?.contentMaxWidth;b&&(f.style.maxWidth=b,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(h.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(h,f);let T=nt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=Au({config:e}),{root:P,textNode:R}=wu();return n.append(p,s,d,T),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:f,composerOverlay:T,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:s,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:P,peekTextNode:R}},Tu=(e,t=!0)=>{if(mo(e))return pv(e,t);let n=nt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,s=e?.layout?.showHeader!==!1,r=o?Ps(e,o,{showClose:t}):ho({config:e,showClose:t}),a=nt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=nt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=nt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=nt("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:Bt(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let f=Rs({config:e}),b=e?.layout?.showFooter!==!1;s?Ar(n,r,e):(r.header.style.display="none",Ar(n,r,e)),n.append(a);let C=nt("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(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:p,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,header:r.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 Nl=(e,t)=>{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: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
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
- `,n.addEventListener("click",t);let r=s=>{var P,E,k,C,I,j,$,R,N,O,Z,Ee,de;let a=(P=s.launcher)!=null?P:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(k=a.subtitle)!=null?k:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,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 Le=parseFloat(ee)||24,Pe=ye(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(u.appendChild(Pe),u.style.display=""):(u.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(j=a.agentIconText)!=null?j:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ee=($=a.agentIconSize)!=null?$:"40px";f.style.height=ee,f.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ee=(R=a.callToActionIconSize)!=null?R:"32px";g.style.height=ee,g.style.width=ee,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Pe=parseFloat(ee)||24,ne=Math.max(Pe-Le,8),Ae=ye(a.callToActionIconName,ne,"currentColor",2);Ae?g.appendChild(Ae):g.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let b=a.position&&hr[a.position]?hr[a.position]:hr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?S:`${v} ${b}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:xn));let T="1px solid var(--persona-border, #e5e7eb)",L="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=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Sg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Cg(e),s=Ag(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},Ml=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>El(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=El(e,n);return{instance:o,element:o.element}};var gv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fv=(e,t)=>{if(!e)return null;let n=gv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},hv=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},yv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},kl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ll=320,Eg=320,bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cv=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=y("img");c.alt=((u=i.alt)==null?void 0:u.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=`${Ll}px`,c.style.maxHeight=`${Eg}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 p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),yv(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Av=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!kl(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!kl(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,o.style.maxHeight=`${Eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Tv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!kl(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ps=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Mg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ps};if(t){let o=t(r);if(o!==null)return o}return Ps()},Ev=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Tg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Mv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-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"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},kg=(e,t,n)=>{var b,v,S,T,L,P,E;let r=(b=t.showCopy)!=null?b:!0,o=(v=t.showUpvote)!=null?v:!0,s=(S=t.showDownvote)!=null?S:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let k=y("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let i=(L=t.visibility)!=null?L:"hover",d=(P=t.align)!=null?P:"right",c=(E=t.layout)!=null?E:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(k,C,I)=>{let j=Gt({icon:k,label:C,size:14,className:"persona-message-action-btn"});return j.setAttribute("data-action",I),j};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ca=(e,t,n,r,o,s)=>{var re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(ae=c==null?void 0:c.show)!=null?ae:!1,f=(fe=d==null?void 0:d.position)!=null?fe:"left",g=($e=c==null?void 0:c.position)!=null?$e:"below",b=Mv(e.role,i),v=y("div",b.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=bv(e),T=(Q=(V=e.content)==null?void 0:V.trim())!=null?Q:"",P=S.length>0&&T===Va,E=si((J=(Me=s==null?void 0:s.widgetConfig)==null?void 0:Me.features)==null?void 0:J.streamAnimation),k=(he=(Ie=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ie.streamAnimation)==null?void 0:he.plugins,C=e.role==="assistant"&&E.type!=="none"?ks(E.type,k):null,I=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,j=e.role==="assistant"&&C!==null&&(!!e.streaming||I);j&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),e.streaming&&$.classList.add("persona-content-streaming"),j&&C&&(C.containerClass&&$.classList.add(C.containerClass),$.style.setProperty("--persona-stream-step",`${E.speed}ms`),$.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=j?ai((gt=e.content)!=null?gt:"",E.buffer,C,e,!!e.streaming):(Wt=e.content)!=null?Wt:"",N=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=N;j&&(C==null?void 0:C.wrap)==="char"?O=ha(N,"char",e.id,{skipTags:C.skipTags}):j&&(C==null?void 0:C.wrap)==="word"&&(O=ha(N,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=O,Z.style.display="none",$.appendChild(Z)):$.innerHTML=O,j&&(C!=null&&C.useCaret)&&!P&&T){let X=ii(),it=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=it[it.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Se=$.lastElementChild;Se?Se.appendChild(X):$.appendChild(X)}}if(u&&g==="inline"&&e.createdAt){let X=Tg(e,c,"span");X.classList.add("persona-timestamp-inline");let it=$.lastElementChild;it?it.appendChild(X):$.appendChild(X)}if(S.length>0){let X=Cv(S,!P&&!!T,()=>{P&&Z&&(Z.style.display="")});X?v.appendChild(X):P&&Z&&(Z.style.display="")}let Ee=xv(e);if(Ee.length>0){let X=Av(Ee);X&&v.appendChild(X)}let de=vv(e);if(de.length>0){let X=Sv(de);X&&v.appendChild(X)}let ee=wv(e);if(ee.length>0){let X=Tv(ee);X&&v.appendChild(X)}if(v.appendChild($),u&&g==="below"&&e.createdAt){let X=Tg(e,c);X.classList.add("persona-mt-1"),v.appendChild(X)}let Le=e.role==="assistant"?fv(e.stopReason,(ge=(tt=s==null?void 0:s.widgetConfig)==null?void 0:tt.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),it=E.placeholder==="skeleton",Ve=it&&E.buffer==="line"&&X;if(X)Ve&&v.appendChild(ya());else if(it)v.appendChild(ya());else{let Se=Mg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&v.appendChild(Se)}}if(Le&&e.stopReason&&!e.streaming&&(T||($.style.display="none"),v.appendChild(hv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=kg(e,r,o);v.appendChild(X)}if(!p||e.role==="system")return v;let ne=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Ev(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ne.append(v,Ae):ne.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ne},kv=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ca(e,t,n,r,o,s)};var Is=new Set,Lv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Pv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},Lg=(e,t)=>{let n=Is.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ye(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Pl=(e,t)=>{var de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(ee=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Is.has(e.id),i=n.status!=="complete",d=Pv(e,(Le=o.previewMaxLines)!=null?Le:3),c=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Pe=t==null?void 0:t.reasoning)!=null?Pe:{},b=String((ne=n.startedAt)!=null?ne:Date.now()),v=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",b),V.textContent=Ua(n),V},S=(Ae=g.renderCollapsedSummary)==null?void 0:Ae.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ua(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(u.textContent=S,p.appendChild(u)):S instanceof HTMLElement?p.appendChild(S):(u.textContent=f,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=Pm(n),p.appendChild(T);let L=(re=o.loadingAnimation)!=null?re:"none",P=g.activeTextTemplate,E=g.completeTextTemplate,k=i?P:E,C=S instanceof HTMLElement,I=(V,Q,Me)=>{let J=Me;for(let le of Q){let Ie=y("span","persona-tool-char");Ie.style.setProperty("--char-index",String(J)),Ie.textContent=le===" "?"\xA0":le,V.appendChild(Ie),J++}return J},j=(V,Q)=>{u.textContent="";let Me=qa(V,""),J=0;for(let le of Me){let Ie=le.styles.length>0?(()=>{let he=y("span",le.styles.map(Ke=>`persona-tool-text-${Ke}`).join(" "));return u.appendChild(he),he})():u;if(le.isDuration&&i)Ie.appendChild(v());else{let he=le.isDuration?Ua(n):le.text;Q?J=I(Ie,he,J):Ie.appendChild(document.createTextNode(he))}}};if(!C&&k)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(se=g.loadingAnimationDuration)!=null?se:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),j(k,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),j(k,!0))}else j(k,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(ae=g.loadingAnimationDuration)!=null?ae:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Q=u.textContent||f;u.textContent="",I(u,Q,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let $=null;if(s){$=y("div","persona-flex persona-items-center");let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?$.appendChild(Q):$.textContent=a?"Hide":"Show";let Me=y("div","persona-flex persona-items-center persona-ml-auto");Me.append($),c.append(p,Me)}else c.append(p);let R=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=($e=(fe=t==null?void 0:t.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:$e.call(fe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Lv(R,V)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,R),r;let N=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let O=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?$.appendChild(Q):$.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(c,R,N),r};var Rs=new Set,Iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Rv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
- `);let o=wo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
- `):""},Il=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Wv=(e,t)=>{var p,u,f,g,b;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=Rv(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Im(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((b=n.name)==null?void 0:b.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ol(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ol(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Pg=(e,t,n)=>{var p;let r=Rs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=ye(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Rl=(e,t)=>{var O,Z,Ee,de,ee,Le,Pe,ne,Ae;let n=e.toolCall,r=(O=t==null?void 0:t.toolCall)!=null?O:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ee=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Rs.has(e.id),{summary:d,previewText:c,isActive:p}=Wv(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let b=String((de=n.startedAt)!=null?de:Date.now()),v=()=>{let re=y("span","");return re.setAttribute("data-tool-elapsed",b),re.textContent=oa(n),re},S=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:oa(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(g.textContent=S,f.appendChild(g)):S instanceof HTMLElement?f.appendChild(S):(g.textContent=d,f.appendChild(g));let T=(Pe=s.loadingAnimation)!=null?Pe:"none",L=r.activeTextTemplate,P=r.completeTextTemplate,E=p?L:P,k=S instanceof HTMLElement,C=(re,se,ae)=>{let fe=ae;for(let $e of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(fe)),V.textContent=$e===" "?"\xA0":$e,re.appendChild(V),fe++}return fe},I=(re,se)=>{var V;g.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",fe=qa(re,ae),$e=0;for(let Q of fe){let Me=Q.styles.length>0?(()=>{let J=y("span",Q.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(J),J})():g;if(Q.isDuration&&p)Me.appendChild(v());else{let J=Q.isDuration?oa(n):Q.text;se?$e=C(Me,J,$e):Me.appendChild(document.createTextNode(J))}}};if(!k)if(p&&T!=="none"){let re=(ne=r.loadingAnimationDuration)!=null?ne:2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),E&&I(E,!1);else if(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)I(E,!0);else{let se=g.textContent||d;g.textContent="",C(g,se,0)}}else E&&I(E,!1);let j=null;if(a){j=y("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(j),u.append(f,ae)}else u.append(f);let $=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let re=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Iv($,re)||($.textContent=c),$.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,$),o;let R=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let re=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,R.appendChild(re)}if(n.args!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.args),re.append(se,ae),R.appendChild(re)}if(n.chunks&&n.chunks.length){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=n.chunks.join(""),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.result),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,R.appendChild(re)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),j){j.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),o.append(u,$,R),o};var ns=new Map,xi=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Ig=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Rg=(e,t)=>{var r,o,s;let n=(o=(r=Ig(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ns.get(e))!=null?s:n==="expanded"},Wg=(e,t,n)=>{var a,i;let r=Ig(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Hg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Rg(e,n);Wg(r,s,n),o.style.display=s?"":"none"};var vi=(e,t)=>{var I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(j=r==null?void 0:r.borderColor)!=null?j:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":($=r==null?void 0:r.titleColor)!=null?$:"currentColor",p=ye(d,20,c,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(g),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),f.appendChild(se)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Ys(n.toolName):void 0,S=(N=r==null?void 0:r.formatDescription)==null?void 0:N.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=S||(T?n.description:`The assistant wants to use \u201C${v!=null?v:xi(n.toolName)}\u201D.`),P=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=L,u.appendChild(P),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(ae),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",k=!!n.description&&!T,C=k||!!n.parameters;if(E!=="hidden"&&C){let se=Rg(e.id,t),ae=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=y("span");fe.setAttribute("data-approval-details-label","true");let $e=y("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),ae.append(fe,$e),Wg(ae,se,t),u.appendChild(ae);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",k){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor),Q.textContent=n.description,V.appendChild(Q)}if(n.parameters){let Q=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Q.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Q.style.color=r.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=wo(n.parameters),V.appendChild(Q)}u.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ae=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let $e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ae.appendChild($e);let V=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ne=r==null?void 0:r.denyButtonTextColor)!=null?ne:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let Q=ye("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",V.appendChild(Q));let Me=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");V.appendChild(Me),se.append(ae,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function Hv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Bg(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:Hv(t),p=!1,u=null,f=()=>{if(!p)return;let S=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${S.width}px`);let T=r==="top-start"||r==="top-end"?S.top-o-n.getBoundingClientRect().height:S.bottom+o,L=r==="bottom-end"||r==="top-end"?S.right-n.getBoundingClientRect().width:S.left;n.style.top=`${T}px`,n.style.left=`${L}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},b=()=>{var k,C,I;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let S=(C=((k=t.ownerDocument)!=null?k:document).defaultView)!=null?C:window,T=(I=t.ownerDocument)!=null?I:document,L=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},P=j=>{let $=typeof j.composedPath=="function"?j.composedPath():[];$.includes(n)||$.includes(t)||(g(),d==null||d("outside"))},E=S.setTimeout(()=>{T.addEventListener("pointerdown",P,!0)},0);S.addEventListener("scroll",L,!0),S.addEventListener("resize",L),u=()=>{S.clearTimeout(E),T.removeEventListener("pointerdown",P,!0),S.removeEventListener("scroll",L,!0),S.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:b,close:g,toggle:()=>p?g():b(),reposition:f,destroy:g}}function Dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Bv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Ng=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},rs=(e,t)=>{Ng(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Dv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Nv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ns.get(e))!=null?o:n==="expanded"},Wl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Ov=(e,t)=>{var c,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?Ys(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:xi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Fv=e=>{let t=y("div","persona-approval-resolved"),n=ye("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?xi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},_v=(e,t,n,r,o,s,a)=>{var j,$,R,N,O,Z,Ee;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(j=r==null?void 0:r.detailsDisplay)!=null?j:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&Nv(t.id,r),g=($=r==null?void 0:r.showDetailsLabel)!=null?$:"Show details",b=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",v=y("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?b:g)):v.setAttribute("data-static","true");let S=y("span","persona-approval-logo"),T=ye("shield-check",16,"currentColor",2);T&&S.appendChild(T),v.appendChild(S);let L=Ov(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&de.appendChild(ee),L.append(" "),L.appendChild(de)}v.appendChild(L),i.appendChild(v);let P=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!f,c){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,de.appendChild(ee)}if(p){let ee=y("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(n.parameters),de.appendChild(ee)}P.appendChild(de)}if(n.reason){let de=y("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,de.append(ee,document.createTextNode(n.reason)),P.appendChild(de)}let E=y("div","persona-approval-actions"),k=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},I=y("button","persona-approval-deny");if(I.type="button",I.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(I.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(I.style.color=r.denyButtonTextColor),I.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let de=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Wl("\u23CE"));let Le=y("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),C(Le);let Pe=ye("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(ee,Le),E.append(de,I),I.append(Wl("Esc"));let ne=y("div","persona-approval-menu"),Ae=y("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",Wl("\u2318\u23CE")),ne.appendChild(Ae),k=Bg({anchor:de,content:ne,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,k),Ae.addEventListener("click",()=>{rs(e,t.id),o()})}else{let de=y("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),C(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),E.append(de,I)}return P.appendChild(E),i.appendChild(P),i.addEventListener("click",de=>{let ee=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!ee)return;let Le=ee.getAttribute("data-action");if(Le==="toggle-params"){let Pe=i.querySelector('[data-role="params"]');if(Pe){let ne=Pe.hidden;Pe.hidden=!ne,v.setAttribute("aria-expanded",ne?"true":"false"),v.setAttribute("aria-label",ne?b:g),ns.set(t.id,ne)}return}if(Le==="toggle-menu"){k==null||k.toggle();return}if(Le==="always"){rs(e,t.id),o({remember:!0});return}if(Le==="allow"){rs(e,t.id),o();return}if(Le==="deny"){rs(e,t.id),s();return}}),i},Og=()=>{let e=Bv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Dv(a);if(i.status!=="pending"){if(rs(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Fv(i)}Ng(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=_v(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{Dg(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),rs(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])rs(e,r);e.latestPendingApprovalId=null}}};var Fg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(S=>S.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=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(o.forEach(b=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=b,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let b=JSON.stringify(o);b!==n&&(n=b,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Aa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Sa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var $v=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),jv=new Set(["step_start","execution_start"]),Uv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qv=new Set(["step_complete","agent_turn_complete"]),zv=new Set(["flow_complete","agent_complete"]),_g=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,os=(e,t)=>{let n=e[t];return jg(n)?n:void 0};function Hl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function wi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Vv(e,t){return typeof t.type=="string"?t.type:e}function Kv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Gv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function $g(e){var r,o,s,a,i;let t=os(e,"result"),n=[os(e,"tokens"),os(e,"totalTokens"),t?os(t,"tokens"):void 0,os(e,"usage"),t?os(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=qn(e.outputTokens))!=null?s:qn(e.completionTokens))!=null?i:t?(a=qn(t.outputTokens))!=null?a:qn(t.completionTokens):void 0}function Jv(e){var n,r,o,s,a;let t=os(e,"result");return(a=(o=(r=(n=qn(e.executionTime))!=null?n:qn(e.executionTimeMs))!=null?r:qn(e.execution_time))!=null?o:qn(e.duration))!=null?a:t?(s=qn(t.executionTime))!=null?s:qn(t.executionTimeMs):void 0}function Xv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=Xv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:wi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!jg(n)){_g.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Vv(t,n),o=this.now();if($v.has(r)){this.startRun(o);return}if(jv.has(r)){this.run||this.startRun(o);return}if(Uv.has(r)){if(!Gv(r,n))return;let a=Kv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Hl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(qv.has(r)){if(!this.run)return;let a=this.run,i=$g(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Hl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:wi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(zv.has(r)){if(!this.run)return;let a=this.run,i=$g(n),d=i!=null?i:a.exactOutputTokens+Hl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:wi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(_g.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Jv(n);return s!=null?s:r-t.startedAt}};function Ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Qv={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)"}},Yv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Zv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ew=100;function tw(e,t){let n={...Qv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Yv}function nw(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function rw(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function ow(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function sw(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function aw(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function iw(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function lw(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function cw(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Bl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ws(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var O,Z;let g=y("div",""),b=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");b.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&v.appendChild(S);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(O=r.timestampFormat)!=null?O:"relative";T.textContent=L==="relative"?nw(e.timestamp,n):rw(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let E=tw(e.type,r.badgeColors),k=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=E.text+"50",k.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:Zv,I=ow(e.payload,C),j=null;I&&(j=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),j.textContent=I);let $=y("div","persona-flex-1 persona-min-w-0"),R=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=ye("clipboard","12px","currentColor",1.5);return N&&R.appendChild(N),R.addEventListener("click",async Ee=>{Ee.stopPropagation(),await sw(aw(e)),R.innerHTML="";let de=ye("check","12px","currentColor",1.5);de&&R.appendChild(de),setTimeout(()=>{R.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),b.appendChild(v),b.appendChild(T),P&&b.appendChild(P),b.appendChild(k),j&&b.appendChild(j),b.appendChild($),b.appendChild(R),g.appendChild(b),d&&g.appendChild(cw(e,a,i)),g}}function Ug(e){var b,v,S,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},f=s.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let P=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return g();function g(){let P=u.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ws(E,P==null?void 0:P.panel);let k=[],C="",I="",j=null,$=[],R={},N=0,O=ni(),Z=0,Ee=0,de=!1,ee=null,Le=!1,Pe=0,ne=new Set,Ae=new Map,re="",se="",ae=null,fe,$e,V,Q,Me=null,J=null,le=null;function Ie(){let me=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Ws(B,P==null?void 0:P.headerBar),a){J=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Me=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Me.textContent="-- tok/s",le=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ot=J,en=le,xr=()=>{if(!en.textContent)return;let or=Ot.getBoundingClientRect(),sr=me.getBoundingClientRect();en.style.left=`${or.left-sr.left}px`,en.style.top=`${or.bottom-sr.top+4}px`,en.style.display="block"},Nr=()=>{en.style.display="none"};J.addEventListener("mouseenter",xr),J.addEventListener("mouseleave",Nr),J.appendChild(Me)}let xe=y("div","persona-flex-1");fe=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ce=y("option","");ce.value="",ce.textContent="All events (0)",fe.appendChild(ce),$e=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),$e.type="button",$e.title="Copy All";let Je=ye("clipboard-copy","12px","currentColor",1.5);Je&&$e.appendChild(Je);let Lt=y("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",$e.appendChild(Lt),J&&B.appendChild(J),B.appendChild(xe),B.appendChild(fe),B.appendChild($e);let Mt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ws(Mt,P==null?void 0:P.searchBar);let xt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");xt&&Rt.appendChild(xt),V=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ws(V,P==null?void 0:P.searchInput),V.type="text",V.placeholder="Search event payloads...",Q=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Q.type="button",Q.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&Q.appendChild(Xt),Mt.appendChild(Rt),Mt.appendChild(V),Mt.appendChild(Q),me.appendChild(B),me.appendChild(Mt),le&&me.appendChild(le),me}let he,Ke=s.find(me=>me.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&o){let me=Ke.renderEventStreamToolbar({config:o,defaultRenderer:()=>Ie(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,be(),Ct()},onSearchChange:B=>{I=B,be(),Ct()}});he=me!=null?me:Ie()}else he=Ie();let gt=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");gt.style.display="none";function Wt(){if(!a||!Me||!J)return;let me=a(),B=iw(me);Me.textContent=B;let xe=lw(me);le&&(le.textContent=xe,xe||(le.style.display="none")),J.setAttribute("aria-label",xe?`Throughput: ${B}, ${xe}`:`Throughput: ${B}`)}let tt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ge=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ge.style.height="100%";let X=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ws(X,P==null?void 0:P.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let it=ye(c,"14px","currentColor",2);it&&X.appendChild(it);let Ve=y("span","");Ve.textContent=p,X.appendChild(Ve);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",tt.appendChild(ge),tt.appendChild(Se),tt.appendChild(X),E.setAttribute("tabindex","0"),E.appendChild(he),E.appendChild(gt),E.appendChild(tt);function we(){let me=t.getAll(),B={};for(let Mt of me)B[Mt.type]=(B[Mt.type]||0)+1;let xe=Object.keys(B).sort(),ce=xe.length!==$.length||!xe.every((Mt,xt)=>Mt===$[xt]),ft=!ce&&xe.some(Mt=>B[Mt]!==R[Mt]),Je=me.length!==Object.values(R).reduce((Mt,xt)=>Mt+xt,0);if(!ce&&!ft&&!Je||($=xe,R=B,!fe))return;let Lt=fe.value;if(fe.options[0].textContent=`All events (${me.length})`,ce){for(;fe.options.length>1;)fe.remove(1);for(let Mt of xe){let xt=y("option","");xt.value=Mt,xt.textContent=`${Mt} (${B[Mt]||0})`,fe.appendChild(xt)}Lt&&xe.includes(Lt)?fe.value=Lt:Lt&&(fe.value="",C="")}else for(let Mt=1;Mt<fe.options.length;Mt++){let xt=fe.options[Mt];xt.textContent=`${xt.value} (${B[xt.value]||0})`}}function Ze(){let me=t.getAll();if(C&&(me=me.filter(B=>B.type===C)),I){let B=I.toLowerCase();me=me.filter(xe=>xe.type.toLowerCase().includes(B)||xe.payload.toLowerCase().includes(B))}return me}function qt(){return C!==""||I!==""}function be(){N=0,Z=0,O.resume(),X.style.display="none"}function pe(me){ne.has(me)?ne.delete(me):ne.add(me),ae=me;let B=ge.scrollTop,xe=O.isFollowing();Le=!0,O.pause(),Ct(),ge.scrollTop=B,xe&&O.resume(),Le=!1}function vn(){return Co(ge,50)}function Ct(){Ee=Date.now(),de=!1,Wt(),we();let me=t.getEvictedCount();me>0?(gt.textContent=`${me.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",k=Ze();let B=k.length,xe=t.getSize()>0;B===0&&xe&&qt()?(Se.textContent=I?`No events matching '${I}'`:"No events matching filter",Se.style.display="",ge.style.display="none"):(Se.style.display="none",ge.style.display=""),$e&&($e.title=qt()?`Copy Filtered (${B})`:"Copy All"),d&&!O.isFollowing()&&B>N&&(Z+=B-N,Ve.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),N=B;let ce=t.getAll(),ft=ce.length>0?ce[0].timestamp:0,Je=new Set(k.map(xt=>xt.id));for(let xt of ne)Je.has(xt)||ne.delete(xt);let Lt=C!==re||I!==se,Mt=Ae.size===0&&k.length>0;if(Lt||Mt||k.length===0){ge.innerHTML="",Ae.clear();let xt=document.createDocumentFragment();for(let Rt=0;Rt<k.length;Rt++){let Xt=Bl(k[Rt],Rt,ft,u,ne,pe,s,o);Ae.set(k[Rt].id,Xt),xt.appendChild(Xt)}ge.appendChild(xt),re=C,se=I,ae=null}else{if(ae!==null){let Rt=Ae.get(ae);if(Rt&&Rt.parentNode===ge){let Xt=k.findIndex(Ot=>Ot.id===ae);if(Xt>=0){let Ot=Bl(k[Xt],Xt,ft,u,ne,pe,s,o);ge.insertBefore(Ot,Rt),Rt.remove(),Ae.set(ae,Ot)}}ae=null}let xt=new Set(k.map(Rt=>Rt.id));for(let[Rt,Xt]of Ae)xt.has(Rt)||(Xt.remove(),Ae.delete(Rt));for(let Rt=0;Rt<k.length;Rt++){let Xt=k[Rt];if(!Ae.has(Xt.id)){let Ot=Bl(Xt,Rt,ft,u,ne,pe,s,o);Ae.set(Xt.id,Ot),ge.appendChild(Ot)}}}O.isFollowing()&&(ge.scrollTop=ge.scrollHeight)}function fn(){if(Date.now()-Ee>=ew){ee!==null&&(cancelAnimationFrame(ee),ee=null),Ct();return}de||(de=!0,ee=requestAnimationFrame(()=>{ee=null,Ct()}))}let yr=(me,B)=>{if(!$e)return;$e.innerHTML="";let xe=ye(me,"12px","currentColor",1.5);xe&&$e.appendChild(xe);let ce=y("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 Je=y("span","persona-text-xs");Je.textContent="Copy All",$e.appendChild(Je),$e.disabled=!1},B)},br=async()=>{if($e){$e.disabled=!0;try{let me;qt()?me=k:n?(me=await n(),me.length===0&&(me=t.getAll())):me=t.getAll();let B=me.map(xe=>{try{return JSON.parse(xe.payload)}catch{return xe.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),yr("check",1500)}catch{yr("x",1500)}}},Ue=()=>{fe&&(C=fe.value,be(),Ct())},M=()=>{!V||!Q||(Q.style.display=V.value?"":"none",j&&clearTimeout(j),j=setTimeout(()=>{I=V.value,be(),Ct()},150))},ue=()=>{!V||!Q||(V.value="",I="",Q.style.display="none",j&&clearTimeout(j),be(),Ct())},Te=()=>{if(Le)return;let me=ge.scrollTop,{action:B,nextLastScrollTop:xe}=ri({following:O.isFollowing(),currentScrollTop:me,lastScrollTop:Pe,nearBottom:vn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=xe,B==="resume"?(O.resume(),Z=0,X.style.display="none"):B==="pause"&&(O.pause(),d&&(Ve.textContent=p,X.style.display=""))},ke=me=>{let B=oi({following:O.isFollowing(),deltaY:me.deltaY,nearBottom:vn(),resumeWhenNearBottom:!0});B==="pause"?(O.pause(),d&&(Ve.textContent=p,X.style.display="")):B==="resume"&&(O.resume(),Z=0,X.style.display="none")},He=()=>{d&&(ge.scrollTop=ge.scrollHeight,O.resume(),Z=0,X.style.display="none")},nt=me=>{let B=me.target;if(!B||B.closest("button"))return;let xe=B.closest("[data-event-id]");if(!xe)return;let ce=xe.getAttribute("data-event-id");ce&&pe(ce)},Qe=me=>{if((me.metaKey||me.ctrlKey)&&me.key==="f"){me.preventDefault(),V==null||V.focus(),V==null||V.select();return}me.key==="Escape"&&(V&&document.activeElement===V?(ue(),V.blur(),E.focus()):r&&r())};$e&&$e.addEventListener("click",br),fe&&fe.addEventListener("change",Ue),V&&V.addEventListener("input",M),Q&&Q.addEventListener("click",ue),ge.addEventListener("scroll",Te),ge.addEventListener("wheel",ke,{passive:!0}),ge.addEventListener("click",nt),X.addEventListener("click",He),E.addEventListener("keydown",Qe);function ht(){j&&clearTimeout(j),ee!==null&&(cancelAnimationFrame(ee),ee=null),de=!1,Ae.clear(),$e&&$e.removeEventListener("click",br),fe&&fe.removeEventListener("change",Ue),V&&V.removeEventListener("input",M),Q&&Q.removeEventListener("click",ue),ge.removeEventListener("scroll",Te),ge.removeEventListener("wheel",ke),ge.removeEventListener("click",nt),X.removeEventListener("click",He),E.removeEventListener("keydown",Qe)}return{element:E,update:fn,destroy:ht}}}function qg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var zg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>qg(e,t)});if(p)return p}return qg(e,t)};var Dl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Mo=new Dl;Mo.register("PersonaArtifactCard",zg);function dw(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Vg(e,t){var $e,V,Q,Me;let n=(V=($e=e.features)==null?void 0:$e.artifacts)==null?void 0:V.layout,o=((Q=n==null?void 0:n.toolbarPreset)!=null?Q:"default")==="document",s=(Me=n==null?void 0:n.panePadding)==null?void 0:Me.trim(),a=e.markdown?vs(e.markdown):null,i=Xs(e.sanitize),d=J=>{let le=a?a(J):Kr(J);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};c&&c.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let u=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let b=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let v="rendered",S=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),P=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,k=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(k&&C&&C.length>0),j=null,$,R=null,N=null;if(o&&(E||k)&&!I){if($=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let J=ye("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else o&&I?(j=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Gt({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"}}),j.append($,R)):o?$=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=Gt({icon:"copy",label:"Copy"});let O=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ke,gt,Wt;let J=(Ke=Ae.find(tt=>tt.id===re))!=null?Ke:Ae[Ae.length-1],le=(gt=J==null?void 0:J.id)!=null?gt:null,Ie=(J==null?void 0:J.artifactType)==="markdown"&&(Wt=J.markdown)!=null?Wt:"",he=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Ie,jsonPayload:he,id:le}},de=async()=>{var Ke;let{markdown:J,jsonPayload:le}=Ee(),Ie=(Ke=Ae.find(gt=>gt.id===re))!=null?Ke:Ae[Ae.length-1],he=(Ie==null?void 0:Ie.artifactType)==="markdown"?J:Ie?le:"";try{await navigator.clipboard.writeText(he)}catch{}};if($.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&I){let{markdown:le,jsonPayload:Ie,id:he}=Ee();try{await J({actionId:"primary",artifactId:he,markdown:le,jsonPayload:Ie})}catch{}return}await de()}),R&&(C!=null&&C.length)){let J=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},le=()=>{N=ts({items:C.map(Ie=>({id:Ie.id,label:Ie.label})),onSelect:async Ie=>{let{markdown:he,jsonPayload:Ke,id:gt}=Ee(),Wt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Wt?await Wt({actionId:Ie,artifactId:gt,markdown:he,jsonPayload:Ke}):Ie==="markdown"||Ie==="md"?await navigator.clipboard.writeText(he):Ie==="json"||Ie==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(he||Ke)}catch{}},anchor:j!=null?j:R,position:"bottom-right",portal:J()})};u.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Ie=>{Ie.stopPropagation(),N==null||N.toggle()})}O.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}ae()}),Z.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let ee=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),L.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",ee(),ae()}),L.addEventListener("click",()=>{v="source",ee(),ae()});let Le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),S.append(T,L),j?P.append(j,O,Z):P.append($,O,Z),f.append(S,Le,P),ee()):(f.appendChild(g),f.appendChild(b)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Pe=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ne=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ne.style.padding=s),u.appendChild(f),u.appendChild(Pe),u.appendChild(ne);let Ae=[],re=null,se=!1,ae=()=>{var he,Ke,gt,Wt;let J=o&&Ae.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let tt of Ae){let ge=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ge.type="button",ge.textContent=tt.title||tt.id.slice(0,8),tt.id===re&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(tt.id)),Pe.appendChild(ge)}ne.replaceChildren();let le=re&&Ae.find(tt=>tt.id===re)||Ae[Ae.length-1];if(!le)return;if(o){let tt=le.artifactType==="markdown"?"MD":(he=le.component)!=null?he:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${tt}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let ge=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(Ke=le.markdown)!=null?Ke:"",ne.appendChild(ge);return}let tt=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");tt.innerHTML=d((gt=le.markdown)!=null?gt:""),ne.appendChild(tt);return}let Ie=le.component?Mo.get(le.component):void 0;if(Ie){let ge={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Ie((Wt=le.props)!=null?Wt:{},ge);if(X){ne.appendChild(X);return}}catch{}}ne.appendChild(dw(le))},fe=()=>{var le;let J=Ae.length>0;if(u.classList.toggle("persona-hidden",!J),c){let Ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((le=Ie==null?void 0:Ie.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Ke&&se?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(J){var le,Ie,he;Ae=J.artifacts,re=(he=(Ie=J.selectedId)!=null?Ie:(le=J.artifacts[J.artifacts.length-1])==null?void 0:le.id)!=null?he:null,Ae.length>0&&(se=!0),ae(),fe()},setMobileOpen(J){se=J,!J&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):fe()}}}function rr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Kg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!rr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function pw(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ci(e,t){var d,c,p,u,f,g,b,v,S,T;if(!rr(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),pw(e),Kg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(b=n==null?void 0:n.panePadding)==null?void 0:b.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Kg(e,t)}var Gg=["panel","seamless"];function Ai(e,t){var i,d,c,p,u,f;for(let g of Gg)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!rr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Gg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Jg(e,t){var n,r,o;return!t||!rr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function uw(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function mw(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function gw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function fw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Xg(e,t){var a;let r=(a=(t.getComputedStyle(e).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 Qg(e,t,n,r,o,s){let a=uw(o,200),i=fw(t,n,r,200);i=Math.max(a,i);let d=mw(s);return d!==null&&(i=Math.min(i,d)),gw(e,a,i)}var Yg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Nl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,v,S;if(s.dataset.enhanced==="true")return;let a=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let i=(v=Yg[a])!=null?v:Yg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,I;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let P=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=T.label,L.appendChild(P);let E=(C=T.type)!=null?C:"text",k;E==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=E),k.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",k.id=`${t.id}-${a}-${T.name}`,k.name=T.name,k.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(k.required=!0),L.appendChild(k),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(S=i.submitLabel)!=null?S:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var k,C;T.preventDefault();let L=(k=n.formEndpoint)!=null?k:"/form",P=new FormData(p),E={};P.forEach((I,j)=>{E[j]=I}),E.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let I=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let j=await I.json();f.textContent=(C=j.message)!=null?C:"Thanks! We'll be in touch soon.",j.success&&j.nextPrompt&&await r.sendMessage(String(j.nextPrompt))}catch(I){f.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ol=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Si=new Ol;var Zg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var hw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ti=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=hw(e),n=yw(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Fl=e=>typeof e=="string"?e:e==null?"":String(e),Hs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Fl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Fl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Fl(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ei=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var bw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},xw=e=>e.map(t=>({...t,streaming:!1})),vw=e=>e.map(t=>({...t,status:"complete"})),_l=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?bw(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?xw(n.messages):void 0,artifacts:n.artifacts?vw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as ww,STR as Cw,OBJ as Aw}from"partial-json";function Sw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Tw(e,t){if(!Sw(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function $l(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=ww(n,Cw|Aw),s=Tw(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ew(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function jl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Mo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Mw(){let e=$l();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function tf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ul(e){let t=tf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ql(e){let t=tf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var kw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function zl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=kw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=r,g.appendChild(b);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),I.title=c[C-1],I.dataset.rating=String(C),I.innerHTML=`
33
+ `,n.addEventListener("click",t);let o=r=>{let a=r.launcher??{},i=Bt(r),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||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let 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,z=oe(a.agentIconName,D*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),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 h=n.querySelector("[data-role='launcher-image']");if(h){let R=a.agentIconSize??"40px";h.style.height=R,h.style.width=R,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.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=i?"none":"",f.innerHTML="",a.callToActionIconName){let z=parseFloat(R)||24,_=Math.max(z-D,8),q=oe(a.callToActionIconName,_,"currentColor",2);q?f.appendChild(q):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let b=a.position&&wn[a.position]?wn[a.position]:wn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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";n.className=i?T:`${C} ${b}`,i||(n.style.zIndex=String(a.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",P="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:P,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},s=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:s}};var Eu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:s}=Su(e),r=Tu(e,t),a={wrapper:n,panel:o,pillRoot:s},i={container:r.container,body:r.body,messagesWrapper:r.messagesWrapper,composerOverlay:r.composerOverlay,introTitle:r.introTitle,introSubtitle:r.introSubtitle},p={element:r.header,iconHolder:r.iconHolder,headerTitle:r.headerTitle,headerSubtitle:r.headerSubtitle,closeButton:r.closeButton,closeButtonWrapper:r.closeButtonWrapper,clearChatButton:r.clearChatButton,clearChatButtonWrapper:r.clearChatButtonWrapper},d={footer:r.footer,form:r.composerForm,textarea:r.textarea,sendButton:r.sendButton,sendButtonWrapper:r.sendButtonWrapper,micButton:r.micButton,micButtonWrapper:r.micButtonWrapper,statusText:r.statusText,suggestions:r.suggestions,attachmentButton:r.attachmentButton,attachmentButtonWrapper:r.attachmentButtonWrapper,attachmentInput:r.attachmentInput,attachmentPreviewsContainer:r.attachmentPreviewsContainer,actionsRow:r.actionsRow,leftActions:r.leftActions,rightActions:r.rightActions,setSendButtonMode:r.setSendButtonMode,peekBanner:r.peekBanner,peekTextNode:r.peekTextNode};return{shell:a,panelElements:r,transcript:i,header:p,composer:d,replaceHeader:h=>(p.element.replaceWith(h.header),p.element=h.header,p.iconHolder=h.iconHolder,p.headerTitle=h.headerTitle,p.headerSubtitle=h.headerSubtitle,p.closeButton=h.closeButton,p.closeButtonWrapper=h.closeButtonWrapper,p.clearChatButton=h.clearChatButton,p.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{d.footer.replaceWith(h),d.footer=h}}},Fl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(r=>r.renderLauncher);if(o?.renderLauncher){let r=o.renderLauncher({config:e,defaultRenderer:()=>Nl(e,n).element,onToggle:n});if(r)return{instance:null,element:r}}let s=Nl(e,n);return{instance:s,element:s.element}};var uv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fv=(e,t)=>{if(!e)return null;let n=uv(e);if(n===null)return null;let o=t?.[e],s=o!==void 0?o:n;return s||null},gv=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},mv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},_l=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},$l=320,ku=320,hv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),yv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),xv=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let s=0,r=!1,a=()=>{r||(r=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${$l}px`,d.style.maxHeight=`${ku}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;s+=1,d.addEventListener("error",()=>{c||(c=!0,s=Math.max(0,s-1),d.remove(),s===0&&a())}),d.addEventListener("load",()=>{c=!0}),mv(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,s=Math.max(0,s-1),d.remove())}),s===0?(a(),null):o}catch{return n?.(),null}},Cv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!_l(o.audio))return;let s=m("audio");s.controls=!0,s.preload="metadata",s.src=o.audio,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${$l}px`,t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},wv=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!_l(o.video))return;let s=m("video");s.controls=!0,s.preload="metadata",s.src=o.video,s.style.display="block",s.style.width="100%",s.style.maxWidth=`${$l}px`,s.style.maxHeight=`${ku}px`,s.style.borderRadius="10px",s.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Av=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!_l(o.data))return;let s=m("a");s.href=o.data,s.download=o.filename,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o.filename,s.className="persona-message-file-attachment",s.style.display="inline-flex",s.style.alignItems="center",s.style.gap="6px",s.style.padding="6px 10px",s.style.borderRadius="8px",s.style.fontSize="0.875rem",s.style.textDecoration="underline",s.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",s.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",s.style.color="inherit",t.appendChild(s),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(s),e},Lu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Sr};if(t){let s=t(o);if(s!==null)return s}return Sr()},Sv=(e,t)=>{let n=m("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let s=m("img");s.src=o,s.alt=t==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(s)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Mu=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),s=new Date(e.createdAt);return t.format?o.textContent=t.format(s):o.textContent=s.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Tv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-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"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Pu=(e,t,n)=>{let o=t.showCopy??!0,s=t.showUpvote??!0,r=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!s&&!r&&!a){let b=m("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],h=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id);let f=(b,C,T)=>{let L=mt({icon:b,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return o&&h.appendChild(f("copy","Copy message","copy")),a&&h.appendChild(f("volume-2","Read aloud","read-aloud")),s&&h.appendChild(f("thumbs-up","Upvote","upvote")),r&&h.appendChild(f("thumbs-down","Downvote","downvote")),h},Is=(e,t,n,o,s,r)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,h=p?.position??"left",f=d?.position??"below",b=Tv(e.role,i),C=m("div",b.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=hv(e),L=e.content?.trim()??"",R=T.length>0&&L===Ta,D=Va(r?.widgetConfig?.features?.streamAnimation),z=r?.widgetConfig?.features?.streamAnimation?.plugins,_=e.role==="assistant"&&D.type!=="none"?wr(D.type,z):null,q=e.role==="assistant"&&_?.isAnimating?.(e)===!0,w=e.role==="assistant"&&_!==null&&(!!e.streaming||q);w&&_?.bubbleClass&&C.classList.add(_.bubbleClass);let U=document.createElement("div");U.classList.add("persona-message-content"),e.streaming&&U.classList.add("persona-content-streaming"),w&&_&&(_.containerClass&&U.classList.add(_.containerClass),U.style.setProperty("--persona-stream-step",`${D.speed}ms`),U.style.setProperty("--persona-stream-duration",`${D.duration}ms`));let Q=w?Ka(e.content??"",D.buffer,_,e,!!e.streaming):e.content??"",B=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent}),$=B;w&&_?.wrap==="char"?$=Es(B,"char",e.id,{skipTags:_.skipTags}):w&&_?.wrap==="word"&&($=Es(B,"word",e.id,{skipTags:_.skipTags}));let pe=null;if(R?(pe=document.createElement("div"),pe.innerHTML=$,pe.style.display="none",U.appendChild(pe)):U.innerHTML=$,w&&_?.useCaret&&!R&&L){let Z=Ga(),xe=U.querySelectorAll(".persona-stream-char, .persona-stream-word"),me=xe[xe.length-1];if(me?.parentNode)me.parentNode.insertBefore(Z,me.nextSibling);else{let fe=U.lastElementChild;fe?fe.appendChild(Z):U.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=Mu(e,d,"span");Z.classList.add("persona-timestamp-inline");let xe=U.lastElementChild;xe?xe.appendChild(Z):U.appendChild(Z)}if(T.length>0){let Z=xv(T,!R&&!!L,()=>{R&&pe&&(pe.style.display="")});Z?C.appendChild(Z):R&&pe&&(pe.style.display="")}let ye=yv(e);if(ye.length>0){let Z=Cv(ye);Z&&C.appendChild(Z)}let Te=bv(e);if(Te.length>0){let Z=wv(Te);Z&&C.appendChild(Z)}let De=vv(e);if(De.length>0){let Z=Av(De);Z&&C.appendChild(Z)}if(C.appendChild(U),u&&f==="below"&&e.createdAt){let Z=Mu(e,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let re=e.role==="assistant"?fv(e.stopReason,r?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),xe=D.placeholder==="skeleton",me=xe&&D.buffer==="line"&&Z;if(Z)me&&C.appendChild(Ms());else if(xe)C.appendChild(Ms());else{let fe=Lu("inline",r?.loadingIndicatorRenderer,r?.widgetConfig);fe&&C.appendChild(fe)}}if(re&&e.stopReason&&!e.streaming&&(L||(U.style.display="none"),C.appendChild(gv(e.stopReason,re))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Pu(e,o,s);C.appendChild(Z)}if(!c||e.role==="system")return C;let Y=m("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=Sv(p,e.role);return h==="right"||h==="left"&&e.role==="user"?Y.append(C,ce):Y.append(ce,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Ev=(e,t,n,o,s,r)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Is(e,t,n,o,s,r)};var Tr=new Set,Mv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),kv=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
34
+ `):""},Ru=(e,t)=>{let n=Tr.has(e),o=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),r=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!s)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=oe(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}s.style.display=n?"":"none",r&&(r.style.display=n?"none":r.textContent||r.childNodes.length?"":"none")},jl=(e,t)=>{let n=e.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-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let s=t?.features?.reasoningDisplay??{},r=s.expandable!==!1,a=r&&Tr.has(e.id),i=n.status!=="complete",p=kv(e,s.previewMaxLines??3),d=m("button",r?"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",r&&(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"),h="Thinking...",f=t?.reasoning??{},b=String(n.startedAt??Date.now()),C=()=>{let ye=m("span","");return ye.setAttribute("data-tool-elapsed",b),ye.textContent=wa(n),ye},T=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:h,previewText:p,isActive:i,config:t??{},elapsed:wa(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(u.textContent=T,c.appendChild(u)):T instanceof HTMLElement?c.appendChild(T):(u.textContent=h,c.appendChild(u));let L=m("span","persona-text-xs persona-text-persona-primary");L.textContent=mp(n),c.appendChild(L);let P=s.loadingAnimation??"none",R=f.activeTextTemplate,D=f.completeTextTemplate,z=i?R:D,_=T instanceof HTMLElement,q=(ye,Te)=>{u.textContent="";let De=Aa(ye,""),re=0;for(let be of De){let Y=be.styles.length>0?(()=>{let ce=m("span",be.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ce),ce})():u;if(be.isDuration&&i)Y.appendChild(C());else{let ce=be.isDuration?wa(n):be.text;Te?re=io(Y,ce,re):Y.appendChild(document.createTextNode(ce))}}};if(!_&&z)if(L.style.display="none",u.style.display="",i&&P!=="none"){let ye=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),P==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),q(z,!1)):(u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),P==="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)),q(z,!0))}else q(z,!1);else if(!_&&i&&P!=="none"){u.style.display="";let ye=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),P==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`);else{u.classList.add(`persona-tool-loading-${P}`),u.style.setProperty("--persona-tool-anim-duration",`${ye}ms`),P==="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 Te=u.textContent||h;u.textContent="",io(u,Te,0)}n.status==="complete"&&(u.style.display="none")}else _||(n.status==="complete"?u.style.display="none":u.style.display="");let w=null;if(r){w=m("div","persona-flex persona-items-center");let Te=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Te?w.appendChild(Te):w.textContent=a?"Hide":"Show";let De=m("div","persona-flex persona-items-center persona-ml-auto");De.append(w),d.append(c,De)}else d.append(c);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","reasoning"),U.style.display="none",U.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&p){let ye=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});Mv(U,ye)||(U.textContent=p),U.style.display=""}if(!a&&i&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!r)return o.append(d,U),o;let Q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=a?"":"none";let B=n.chunks.join(""),$=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return $.textContent=B||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild($),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),w){w.innerHTML="";let Te=oe(a?"chevron-up":"chevron-down",16,"currentColor",2);Te?w.appendChild(Te):w.textContent=a?"Hide":"Show"}Q.style.display=a?"":"none",U.style.display=a?"none":U.textContent||U.childNodes.length?"":"none"})(),o.append(d,U,Q),o};var Er=new Set,Lv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Pv=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
35
+ `);let s=so(n.args).trim();return s?s.split(/\r?\n/).map(r=>r.trim()).filter(Boolean).slice(0,t).join(`
36
+ `):""},Ul=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},Rv=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,s=o?.collapsedMode??"tool-call",r=Pv(e,o?.previewMaxLines??3),a=n?hp(n):"";if(!n)return{summary:a,previewText:r,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return s==="tool-name"?d=n.name?.trim()||a:s==="tool-preview"&&r&&(d=r),i&&p.activeTextTemplate?d=dl(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=dl(n,p.completeTextTemplate,d)),{summary:d,previewText:r,isActive:i}},Iu=(e,t,n)=>{let o=Er.has(e),s=n?.toolCall??{},r=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!r||!a)return;r.setAttribute("aria-expanded",o?"true":"false");let d=r.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=s.toggleTextColor||s.headerTextColor||"var(--persona-primary, #171717)",u=oe(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},zl=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},s=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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),o.backgroundColor&&(s.style.backgroundColor=o.backgroundColor),o.borderColor&&(s.style.borderColor=o.borderColor),o.borderWidth&&(s.style.borderWidth=o.borderWidth),o.borderRadius&&(s.style.borderRadius=o.borderRadius),s.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 s;let r=t?.features?.toolCallDisplay??{},a=r.expandable!==!1,i=a&&Er.has(e.id),{summary:p,previewText:d,isActive:c}=Rv(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let h=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()),C=()=>{let B=m("span","");return B.setAttribute("data-tool-elapsed",b),B.textContent=ds(n),B},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:r.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:ds(n),createElapsedElement:C});typeof T=="string"&&T.trim()?(f.textContent=T,h.appendChild(f)):T instanceof HTMLElement?h.appendChild(T):(f.textContent=p,h.appendChild(f));let L=r.loadingAnimation??"none",P=o.activeTextTemplate,R=o.completeTextTemplate,D=c?P:R,z=T instanceof HTMLElement,_=(B,$)=>{f.textContent="";let pe=n.name?.trim()||"tool",ye=Aa(B,pe),Te=0;for(let De of ye){let re=De.styles.length>0?(()=>{let be=m("span",De.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(be),be})():f;if(De.isDuration&&c)re.appendChild(C());else{let be=De.isDuration?ds(n):De.text;$?Te=io(re,be,Te):re.appendChild(document.createTextNode(be))}}};if(!z)if(c&&L!=="none"){let B=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),L==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${B}ms`),D&&_(D,!1);else if(f.classList.add(`persona-tool-loading-${L}`),f.style.setProperty("--persona-tool-anim-duration",`${B}ms`),L==="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)_(D,!0);else{let $=f.textContent||p;f.textContent="",io(f,$,0)}}else D&&_(D,!1);let q=null;if(a){q=m("div","persona-flex persona-items-center");let B=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(i?"chevron-up":"chevron-down",16,B,2);$?q.appendChild($):q.textContent=i?"Hide":"Show";let pe=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(q),u.append(h,pe)}else u.append(h);let w=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(w.setAttribute("data-persona-collapsed-preview","tool"),w.style.display="none",w.style.whiteSpace="pre-wrap",!i&&c&&r.activePreview&&d){let B=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});Lv(w,B)||(w.textContent=d),w.style.display=""}if(!i&&c&&r.activeMinHeight&&(s.style.minHeight=r.activeMinHeight),!a)return s.append(u,w),s;let U=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(U.style.display=i?"":"none",o.contentBackgroundColor&&(U.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(U.style.color=o.contentTextColor),o.contentPaddingX&&(U.style.paddingLeft=o.contentPaddingX,U.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(U.style.paddingTop=o.contentPaddingY,U.style.paddingBottom=o.contentPaddingY),n.name){let B=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?B.style.color=o.contentTextColor:o.headerTextColor&&(B.style.color=o.headerTextColor),B.textContent=n.name,U.appendChild(B)}if(n.args!==void 0){let B=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Arguments";let pe=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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Ul(pe,o),pe.textContent=so(n.args),B.append($,pe),U.appendChild(B)}if(n.chunks&&n.chunks.length){let B=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Activity";let pe=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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Ul(pe,o),pe.textContent=n.chunks.join(""),B.append($,pe),U.appendChild(B)}if(n.status==="complete"&&n.result!==void 0){let B=m("div","persona-space-y-1"),$=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&($.style.color=o.labelTextColor),$.textContent="Result";let pe=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");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",Ul(pe,o),pe.textContent=so(n.result),B.append($,pe),U.appendChild(B)}if(n.status==="complete"&&typeof n.duration=="number"){let B=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(B.style.color=o.contentTextColor),B.textContent=`Duration: ${n.duration}ms`,U.appendChild(B)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),q){q.innerHTML="";let B=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",$=oe(i?"chevron-up":"chevron-down",16,B,2);$?q.appendChild($):q.textContent=i?"Hide":"Show"}U.style.display=i?"":"none",w.style.display=i?"none":w.textContent||w.childNodes.length?"":"none"})(),s.append(u,w,U),s};var Jo=new Map,ri=e=>{let n=(e.startsWith(En)?e.slice(En.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Wu=e=>e?.approval!==!1?e?.approval:void 0,Hu=(e,t)=>{let n=Wu(t)?.detailsDisplay??"collapsed";return Jo.get(e)??n==="expanded"},Bu=(e,t,n)=>{let o=Wu(n);e.setAttribute("aria-expanded",t?"true":"false");let s=e.querySelector("[data-approval-details-label]");s&&(s.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let r=e.querySelector("[data-approval-details-chevron]");if(r){r.innerHTML="";let a=oe(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&r.appendChild(a)}},Du=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),s=t.querySelector("[data-approval-details]");if(!o||!s)return;let r=Hu(e,n);Bu(o,r,n),s.style.display=r?"":"none"};var si=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,s=n?.status==="pending",r=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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",r.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",r.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 r;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let 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=oe(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),h=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",h.appendChild(f),!s){let q=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");q.setAttribute("data-approval-status",n.status),n.status==="approved"?(q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",q.style.color="var(--persona-palette-colors-success-700, #15803d)",q.textContent="Approved"):n.status==="denied"?(q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",q.textContent="Denied"):n.status==="timeout"&&(q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",q.style.color="var(--persona-palette-colors-warning-700, #b45309)",q.textContent="Timeout"),h.appendChild(q)}u.appendChild(h);let C=n.toolType==="webmcp"||n.toolName.startsWith(En)?rs(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,P=T||(L?n.description:`The assistant wants to use \u201C${C??ri(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=P,u.appendChild(R),n.reason){let q=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");q.setAttribute("data-approval-reason","true"),o?.reasonColor?q.style.color=o.reasonColor:o?.descriptionColor&&(q.style.color=o.descriptionColor);let w=m("span","persona-font-medium");w.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,q.appendChild(w),q.appendChild(document.createTextNode(n.reason)),u.appendChild(q)}let D=o?.detailsDisplay??"collapsed",z=!!n.description&&!L,_=z||!!n.parameters;if(D!=="hidden"&&_){let q=Hu(e.id,t),w=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");w.type="button",w.setAttribute("data-expand-header","true"),w.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(w.style.color=o.descriptionColor);let U=m("span");U.setAttribute("data-approval-details-label","true");let Q=m("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),w.append(U,Q),Bu(w,q,t),u.appendChild(w);let B=m("div");if(B.setAttribute("data-approval-details","true"),B.style.display=q?"":"none",z){let $=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&($.style.color=o.descriptionColor),$.textContent=n.description,B.appendChild($)}if(n.parameters){let $=m("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&($.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&($.style.color=o.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=so(n.parameters),B.appendChild($)}u.appendChild(B)}if(s){let q=m("div","persona-flex persona-gap-2 persona-mt-2");q.setAttribute("data-approval-buttons","true");let w=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");w.type="button",w.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",w.style.color=o?.approveButtonTextColor??"#ffffff",w.setAttribute("data-approval-action","approve");let U=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);U&&(U.style.marginRight="4px",w.appendChild(U));let Q=document.createTextNode(o?.approveLabel??"Approve");w.appendChild(Q);let B=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");B.type="button",B.style.backgroundColor=o?.denyButtonColor??"transparent",B.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",B.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,B.setAttribute("data-approval-action","deny");let $=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);$&&($.style.marginRight="4px",B.appendChild($));let pe=document.createTextNode(o?.denyLabel??"Deny");B.appendChild(pe),q.append(w,B),u.appendChild(q)}return a.append(i,u),r.appendChild(a),r};function Iv(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Ou(e){let{anchor:t,content:n,placement:o="bottom-start",offset:s=6,matchAnchorWidth:r=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:p}=e,d=e.container??Iv(t),c=!1,u=null,h=()=>{if(!c)return;let C=t.getBoundingClientRect();n.style.position="fixed",r&&(n.style.minWidth=`${C.width}px`);let T=o==="top-start"||o==="top-end"?C.top-s-n.getBoundingClientRect().height:C.bottom+s,L=o==="bottom-end"||o==="top-end"?C.right-n.getBoundingClientRect().width:C.left;n.style.top=`${T}px`,n.style.left=`${L}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),h();let C=(t.ownerDocument??document).defaultView??window,T=t.ownerDocument??document,L=()=>{if(!t.isConnected){f(),p?.("anchor-removed");return}h()},P=D=>{let z=typeof D.composedPath=="function"?D.composedPath():[];z.includes(n)||z.includes(t)||(f(),p?.("outside"))},R=C.setTimeout(()=>{T.addEventListener("pointerdown",P,!0)},0);C.addEventListener("scroll",L,!0),C.addEventListener("resize",L),u=()=>{C.clearTimeout(R),T.removeEventListener("pointerdown",P,!0),C.removeEventListener("scroll",L,!0),C.removeEventListener("resize",L)},i?.()};return{get isOpen(){return c},open:b,close:f,toggle:()=>c?f():b(),reposition:h,destroy:f}}function Nu(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Wv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Fu=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Xo=(e,t)=>{Fu(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Hv=e=>e?.approval!==!1?e?.approval:void 0,Bv=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Jo.get(e)??n==="expanded"},ql=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Dv=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let s=e.toolType==="webmcp"||e.toolName.startsWith(En)?rs(e.toolName):void 0,r=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...s?{displayTitle:s}:{},...e.reason?{reason:e.reason}:{}});if(r)return n.textContent=r,n;let a=s??ri(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},Ov=e=>{let t=m("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?ri(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Nv=(e,t,n,o,s,r,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,h=u&&Bv(t.id,o),f=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",C=m("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",h?"true":"false"),C.setAttribute("aria-label",h?b:f)):C.setAttribute("data-static","true");let T=m("span","persona-approval-logo"),L=oe("shield-check",16,"currentColor",2);L&&T.appendChild(L),C.appendChild(T);let P=Dv(n,o);if(u){let w=m("span","persona-approval-toggle");w.setAttribute("aria-hidden","true");let U=oe("chevron-down",14,"currentColor",2);U&&w.appendChild(U),P.append(" "),P.appendChild(w)}C.appendChild(P),i.appendChild(C);let R=m("div","persona-approval-body");if(u){let w=m("div","persona-approval-details");if(w.setAttribute("data-role","params"),w.hidden=!h,d){let U=m("p","persona-approval-desc");o?.descriptionColor&&(U.style.color=o.descriptionColor),U.textContent=n.description,w.appendChild(U)}if(c){let U=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(U.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(U.style.color=o.parameterTextColor),U.textContent=so(n.parameters),w.appendChild(U)}R.appendChild(w)}if(n.reason){let w=m("p","persona-approval-reason");o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let U=m("span","persona-approval-reason-label");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.append(U,document.createTextNode(n.reason)),R.appendChild(w)}let D=m("div","persona-approval-actions"),z=null,_=w=>{o?.approveButtonColor&&(w.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(w.style.color=o.approveButtonTextColor)},q=m("button","persona-approval-deny");if(q.type="button",q.setAttribute("data-action","deny"),o?.denyButtonColor&&(q.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(q.style.color=o.denyButtonTextColor),q.append(o?.denyLabel??"Deny"),a){let w=m("div","persona-approval-split"),U=m("button","persona-approval-primary");U.type="button",U.setAttribute("data-action","always"),_(U),U.append(o?.approveLabel??"Always allow",ql("\u23CE"));let Q=m("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),_(Q);let B=oe("chevron-down",15,"currentColor",2);B&&Q.appendChild(B),w.append(U,Q),D.append(w,q),q.append(ql("Esc"));let $=m("div","persona-approval-menu"),pe=m("button","persona-approval-menu-item");pe.type="button",pe.append("Allow once",ql("\u2318\u23CE")),$.appendChild(pe),z=Ou({anchor:w,content:$,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,z),pe.addEventListener("click",()=>{Xo(e,t.id),s()})}else{let w=m("button","persona-approval-primary persona-approval-primary--solo");w.type="button",w.setAttribute("data-action","allow"),_(w),w.append(o?.approveLabel??"Allow"),D.append(w,q)}return R.appendChild(D),i.appendChild(R),i.addEventListener("click",w=>{let U=w.target instanceof Element?w.target.closest("[data-action]"):null;if(!U)return;let Q=U.getAttribute("data-action");if(Q==="toggle-params"){let B=i.querySelector('[data-role="params"]');if(B){let $=B.hidden;B.hidden=!$,C.setAttribute("aria-expanded",$?"true":"false"),C.setAttribute("aria-label",$?b:f),Jo.set(t.id,$)}return}if(Q==="toggle-menu"){z?.toggle();return}if(Q==="always"){Xo(e,t.id),s({remember:!0});return}if(Q==="allow"){Xo(e,t.id),s();return}if(Q==="deny"){Xo(e,t.id),r();return}}),i},_u=()=>{let e=Wv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:s,deny:r,config:a})=>{let i=o?.approval;if(!i)return null;let p=Hv(a);if(i.status!=="pending"){if(Xo(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Ov(i)}Fu(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Nv(e,o,i,p,s,r,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=h=>{Nu(h)||o.id===e.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Xo(e,o.id),h.key==="Escape"?r():h.metaKey||h.ctrlKey?s():s({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Xo(e,o);e.latestPendingApprovalId=null}}};var $u=e=>{let t=[],n=null;return{buttons:t,render:(s,r,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!s||!s.length||!c&&(i??(r?r.getMessages():[])).some(T=>T.role==="user"))return;let u=document.createDocumentFragment(),h=r?r.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(s.forEach(b=>{let C=m("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=b,C.disabled=h,p?.fontFamily&&(C.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!r||r.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),r.sendMessage(b))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let b=JSON.stringify(s);b!==n&&(n=b,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...s]},bubbles:!0,composed:!0})))}}}};var Ws=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Hs=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let s=o.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let r=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of t)o.put(s)}catch{}}};var Fv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),_v=new Set(["step_start","execution_start"]),$v=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),jv=new Set(["step_complete","agent_turn_complete"]),Uv=new Set(["flow_complete","agent_complete"]),ju=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),zu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),an=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Qo=(e,t)=>{let n=e[t];return zu(n)?n:void 0};function Vl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function ai(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function zv(e,t){return typeof t.type=="string"?t.type:e}function qv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Vv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Uu(e){let t=Qo(e,"result"),n=[Qo(e,"tokens"),Qo(e,"totalTokens"),t?Qo(t,"tokens"):void 0,Qo(e,"usage"),t?Qo(t,"usage"):void 0];for(let o of n){if(!o)continue;let s=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(s!==void 0)return s}return an(e.outputTokens)??an(e.completionTokens)??(t?an(t.outputTokens)??an(t.completionTokens):void 0)}function Kv(e){let t=Qo(e,"result");return an(e.executionTime)??an(e.executionTimeMs)??an(e.execution_time)??an(e.duration)??(t?an(t.executionTime)??an(t.executionTimeMs):void 0)}function Gv(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Bs=class{constructor(t=Gv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:ai(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!zu(n)){ju.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=zv(t,n),s=this.now();if(Fv.has(o)){this.startRun(s);return}if(_v.has(o)){this.run||this.startRun(s);return}if($v.has(o)){if(!Vv(o,n))return;let r=qv(n);if(!r)return;this.run||this.startRun(s);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=s),a.visibleCharCount+=r.length;let i=a.exactOutputTokens+Vl(a.visibleCharCount),p=s-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:ai(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(jv.has(o)){if(!this.run)return;let r=this.run,a=Uu(n);a!==void 0&&(r.exactOutputTokens+=a,r.visibleCharCount=0);let i=r.exactOutputTokens>0,p=r.exactOutputTokens+Vl(r.visibleCharCount),d=this.resolveDuration(r,n,s);this.metric={status:"running",tokensPerSecond:ai(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Uv.has(o)){if(!this.run)return;let r=this.run,a=Uu(n),i=a??r.exactOutputTokens+Vl(r.visibleCharCount),p=a!==void 0||r.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(r,n,s);this.metric={status:"complete",tokensPerSecond:ai(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(ju.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let s=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return s!==void 0&&s>=250?s:Kv(n)??o-t.startedAt}};function Mr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Jv={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)"}},Xv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Qv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Yv=100;function Zv(e,t){let n={...Jv,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Xv}function ex(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function tx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),s=String(t.getSeconds()).padStart(2,"0"),r=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${s}.${r}`}function nx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let s=o.split("."),r=n;for(let a of s)if(r&&typeof r=="object"&&r!==null)r=r[a];else{r=void 0;break}if(typeof r=="string"&&r.trim())return r.trim()}}catch{}return null}function ox(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function rx(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function sx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function ax(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function ix(e,t,n){let o,s;try{s=JSON.parse(e.payload),o=JSON.stringify(s,null,2)}catch{s=e.payload,o=e.payload}let r=t.find(i=>i.renderEventStreamPayload);if(r?.renderEventStreamPayload&&n){let i=r.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=m("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),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,i.appendChild(p),i}}function Kl(e,t,n,o,s,r,a,i){let p=s.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Mr(d,o.classNames?.eventRow);let c=a.find(h=>h.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let h=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>r(e.id)});if(h)return d.appendChild(h),d}return d.appendChild(u()),d;function u(){let h=m("div",""),f=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let 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"),C=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&b.appendChild(C);let T=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";T.textContent=L==="relative"?ex(e.timestamp,n):tx(e.timestamp);let P=null;o.showSequenceNumbers!==!1&&(P=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let R=Zv(e.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=e.type;let z=o.descriptionFields??Qv,_=nx(e.payload,z),q=null;_&&(q=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=_);let w=m("div","persona-flex-1 persona-min-w-0"),U=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"),Q=oe("clipboard","12px","currentColor",1.5);return Q&&U.appendChild(Q),U.addEventListener("click",async B=>{B.stopPropagation(),await ox(rx(e)),U.innerHTML="";let $=oe("check","12px","currentColor",1.5);$&&U.appendChild($),setTimeout(()=>{U.innerHTML="";let pe=oe("clipboard","12px","currentColor",1.5);pe&&U.appendChild(pe)},1500)}),f.appendChild(b),f.appendChild(T),P&&f.appendChild(P),f.appendChild(D),q&&f.appendChild(q),f.appendChild(w),f.appendChild(U),h.appendChild(f),p&&h.appendChild(ix(e,a,i)),h}}function qu(e){let{buffer:t,getFullHistory:n,onClose:o,config:s,plugins:r=[],getThroughput:a}=e,i=s?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=s?.features?.eventStream??{},h=r.find(b=>b.renderEventStreamView);if(h?.renderEventStreamView&&s){let b=h.renderEventStreamView({config:s,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return f();function f(){let b=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Mr(C,b?.panel);let T=[],L="",P="",R=null,D=[],z={},_=0,q=Ua(),w=0,U=0,Q=!1,B=null,$=!1,pe=0,ye=new Set,Te=new Map,De="",re="",be=null,Y,ce,Z,xe,me=null,fe=null,Pe=null;function Oe(){let H=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=m("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Mr(j,b?.headerBar),a){fe=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),fe.style.cursor="help",me=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"),me.textContent="-- tok/s",Pe=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"),Pe.style.display="none",Pe.style.pointerEvents="none";let Xe=fe,bo=Pe,vo=()=>{if(!bo.textContent)return;let Fs=Xe.getBoundingClientRect(),Qt=H.getBoundingClientRect();bo.style.left=`${Fs.left-Qt.left}px`,bo.style.top=`${Fs.bottom-Qt.top+4}px`,bo.style.display="block"},xi=()=>{bo.style.display="none"};fe.addEventListener("mouseenter",vo),fe.addEventListener("mouseleave",xi),fe.appendChild(me)}let se=m("div","persona-flex-1");Y=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 et=m("option","");et.value="",et.textContent="All events (0)",Y.appendChild(et),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=oe("clipboard-copy","12px","currentColor",1.5);ct&&ce.appendChild(ct);let V=m("span","persona-event-copy-all persona-text-xs");V.textContent="Copy All",ce.appendChild(V),fe&&j.appendChild(fe),j.appendChild(se),j.appendChild(Y),j.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");Mr(Ue,b?.searchBar);let Ae=oe("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");Ae&&He.appendChild(Ae),Z=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"),Mr(Z,b?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",xe=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"),xe.type="button",xe.style.display="none";let ke=oe("x","12px","currentColor",2);return ke&&xe.appendChild(ke),Ue.appendChild(He),Ue.appendChild(Z),Ue.appendChild(xe),H.appendChild(j),H.appendChild(Ue),Pe&&H.appendChild(Pe),H}let je,Ne=r.find(H=>H.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&s?je=Ne.renderEventStreamToolbar({config:s,defaultRenderer:()=>Oe(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{L=j,Ie(),ve()},onSearchChange:j=>{P=j,Ie(),ve()}})??Oe():je=Oe();let we=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");we.style.display="none";function Le(){if(!a||!me||!fe)return;let H=a(),j=sx(H);me.textContent=j;let se=ax(H);Pe&&(Pe.textContent=se,se||(Pe.style.display="none")),fe.setAttribute("aria-label",se?`Throughput: ${j}, ${se}`:`Throughput: ${j}`)}let ot=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ie=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ie.style.height="100%";let Re=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");Mr(Re,b?.scrollIndicator),Re.style.display="none",Re.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xt=oe(d,"14px","currentColor",2);xt&&Re.appendChild(xt);let yt=m("span","");yt.textContent=c,Re.appendChild(yt);let rt=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");rt.style.display="none",ot.appendChild(ie),ot.appendChild(rt),ot.appendChild(Re),C.setAttribute("tabindex","0"),C.appendChild(je),C.appendChild(we),C.appendChild(ot);function Ee(){let H=t.getAll(),j={};for(let Ue of H)j[Ue.type]=(j[Ue.type]||0)+1;let se=Object.keys(j).sort(),et=se.length!==D.length||!se.every((Ue,Ae)=>Ue===D[Ae]),We=!et&&se.some(Ue=>j[Ue]!==z[Ue]),ct=H.length!==Object.values(z).reduce((Ue,Ae)=>Ue+Ae,0);if(!et&&!We&&!ct||(D=se,z=j,!Y))return;let V=Y.value;if(Y.options[0].textContent=`All events (${H.length})`,et){for(;Y.options.length>1;)Y.remove(1);for(let Ue of se){let Ae=m("option","");Ae.value=Ue,Ae.textContent=`${Ue} (${j[Ue]||0})`,Y.appendChild(Ae)}V&&se.includes(V)?Y.value=V:V&&(Y.value="",L="")}else for(let Ue=1;Ue<Y.options.length;Ue++){let Ae=Y.options[Ue];Ae.textContent=`${Ae.value} (${j[Ae.value]||0})`}}function he(){let H=t.getAll();if(L&&(H=H.filter(j=>j.type===L)),P){let j=P.toLowerCase();H=H.filter(se=>se.type.toLowerCase().includes(j)||se.payload.toLowerCase().includes(j))}return H}function lt(){return L!==""||P!==""}function Ie(){_=0,w=0,q.resume(),Re.style.display="none"}function ge(H){ye.has(H)?ye.delete(H):ye.add(H),be=H;let j=ie.scrollTop,se=q.isFollowing();$=!0,q.pause(),ve(),ie.scrollTop=j,se&&q.resume(),$=!1}function le(){return fo(ie,50)}function ve(){U=Date.now(),Q=!1,Le(),Ee();let H=t.getEvictedCount();H>0?(we.textContent=`${H.toLocaleString()} older events truncated`,we.style.display=""):we.style.display="none",T=he();let j=T.length,se=t.getSize()>0;j===0&&se&&lt()?(rt.textContent=P?`No events matching '${P}'`:"No events matching filter",rt.style.display="",ie.style.display="none"):(rt.style.display="none",ie.style.display=""),ce&&(ce.title=lt()?`Copy Filtered (${j})`:"Copy All"),p&&!q.isFollowing()&&j>_&&(w+=j-_,yt.textContent=c?`${c}${w>0?` (${w})`:""}`:"",Re.style.display=""),_=j;let et=t.getAll(),We=et.length>0?et[0].timestamp:0,ct=new Set(T.map(Ae=>Ae.id));for(let Ae of ye)ct.has(Ae)||ye.delete(Ae);let V=L!==De||P!==re,Ue=Te.size===0&&T.length>0;if(V||Ue||T.length===0){ie.innerHTML="",Te.clear();let Ae=document.createDocumentFragment();for(let He=0;He<T.length;He++){let ke=Kl(T[He],He,We,u,ye,ge,r,s);Te.set(T[He].id,ke),Ae.appendChild(ke)}ie.appendChild(Ae),De=L,re=P,be=null}else{if(be!==null){let He=Te.get(be);if(He&&He.parentNode===ie){let ke=T.findIndex(Xe=>Xe.id===be);if(ke>=0){let Xe=Kl(T[ke],ke,We,u,ye,ge,r,s);ie.insertBefore(Xe,He),He.remove(),Te.set(be,Xe)}}be=null}let Ae=new Set(T.map(He=>He.id));for(let[He,ke]of Te)Ae.has(He)||(ke.remove(),Te.delete(He));for(let He=0;He<T.length;He++){let ke=T[He];if(!Te.has(ke.id)){let Xe=Kl(ke,He,We,u,ye,ge,r,s);Te.set(ke.id,Xe),ie.appendChild(Xe)}}}q.isFollowing()&&(ie.scrollTop=ie.scrollHeight)}function Ct(){if(Date.now()-U>=Yv){B!==null&&(cancelAnimationFrame(B),B=null),ve();return}Q||(Q=!0,B=requestAnimationFrame(()=>{B=null,ve()}))}let O=(H,j)=>{if(!ce)return;ce.innerHTML="";let se=oe(H,"12px","currentColor",1.5);se&&ce.appendChild(se);let et=m("span","persona-text-xs");et.textContent="Copy All",ce.appendChild(et),setTimeout(()=>{ce.innerHTML="";let We=oe("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},j)},te=async()=>{if(ce){ce.disabled=!0;try{let H;lt()?H=T:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let j=H.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),O("check",1500)}catch{O("x",1500)}}},Fe=()=>{Y&&(L=Y.value,Ie(),ve())},Me=()=>{!Z||!xe||(xe.style.display=Z.value?"":"none",R&&clearTimeout(R),R=setTimeout(()=>{P=Z.value,Ie(),ve()},150))},E=()=>{!Z||!xe||(Z.value="",P="",xe.style.display="none",R&&clearTimeout(R),Ie(),ve())},J=()=>{if($)return;let H=ie.scrollTop,{action:j,nextLastScrollTop:se}=za({following:q.isFollowing(),currentScrollTop:H,lastScrollTop:pe,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});pe=se,j==="resume"?(q.resume(),w=0,Re.style.display="none"):j==="pause"&&(q.pause(),p&&(yt.textContent=c,Re.style.display=""))},v=H=>{let j=qa({following:q.isFollowing(),deltaY:H.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});j==="pause"?(q.pause(),p&&(yt.textContent=c,Re.style.display="")):j==="resume"&&(q.resume(),w=0,Re.style.display="none")},A=()=>{p&&(ie.scrollTop=ie.scrollHeight,q.resume(),w=0,Re.style.display="none")},M=H=>{let j=H.target;if(!j||j.closest("button"))return;let se=j.closest("[data-event-id]");if(!se)return;let et=se.getAttribute("data-event-id");et&&ge(et)},W=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),Z?.focus(),Z?.select();return}H.key==="Escape"&&(Z&&document.activeElement===Z?(E(),Z.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",te),Y&&Y.addEventListener("change",Fe),Z&&Z.addEventListener("input",Me),xe&&xe.addEventListener("click",E),ie.addEventListener("scroll",J),ie.addEventListener("wheel",v,{passive:!0}),ie.addEventListener("click",M),Re.addEventListener("click",A),C.addEventListener("keydown",W);function K(){R&&clearTimeout(R),B!==null&&(cancelAnimationFrame(B),B=null),Q=!1,Te.clear(),ce&&ce.removeEventListener("click",te),Y&&Y.removeEventListener("change",Fe),Z&&Z.removeEventListener("input",Me),xe&&xe.removeEventListener("click",E),ie.removeEventListener("scroll",J),ie.removeEventListener("wheel",v),ie.removeEventListener("click",M),Re.removeEventListener("click",A),C.removeEventListener("keydown",W)}return{element:C,update:Ct,destroy:K}}}function Gl(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",s=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let r=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let h=u;return r.findIndex(f=>f===h||f.contains(h))},d=u=>{let h=p(u.target);if(h<0)return;let f=h;if(u.key===s)f=Math.min(h+1,r.length-1);else if(u.key===o)f=Math.max(h-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=r.length-1;else return;u.preventDefault(),f!==h&&t.onSelect(f)},c=u=>{let h=p(u.target);h>=0&&i(r[h])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,h){if(r=u,u.forEach((f,b)=>{f.setAttribute("role","tab");let C=b===h;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||h<0&&b===0?0:-1}),a){let f=(h>=0?u[h]:void 0)??u[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Vu(e,t){let n=e.features?.artifacts?.layout,s=(n?.toolbarPreset??"default")==="document",r=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=O=>({start:O===!1?!1:typeof O=="object"&&O?O.start!==!1:!0,end:O===!1?!1:typeof O=="object"&&O?O.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),h=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=()=>{h?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),$?.hide()};h&&h.addEventListener("click",()=>{f(),t.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"),s&&b.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&C.classList.add("persona-artifact-toolbar-document");let T=m("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=r;let L=mt({icon:"x",label:a});L.addEventListener("click",()=>{f(),t.onDismiss?.()});let P="rendered",R=po({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:s?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:s?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:O=>{P=O==="source"?"source":"rendered",le()}}),D=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,_=n?.documentToolbarShowCopyChevron===!0,q=n?.documentToolbarCopyMenuItems,w=!!(_&&q&&q.length>0),U=null,Q,B=null,$=null;if(s&&(z||_)&&!w){if(Q=z?co({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),_){let O=oe("chevron-down",14,"currentColor",2);O&&Q.appendChild(O)}}else s&&w?(U=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=z?co({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B=mt({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"}}),U.append(Q,B)):s?Q=mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let pe=s?mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):mt({icon:"refresh-cw",label:"Refresh"}),ye=s?mt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):mt({icon:"x",label:a}),Te=mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(s?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Te.classList.add("persona-hidden");let De=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),re=e.features?.artifacts?.toolbarActions??[],be=()=>{let O=we.find(E=>E.id===Le)??we[we.length-1],te=O?.id??null,Fe=O?.artifactType==="markdown"?O.markdown??"":"",Me=O?JSON.stringify({component:O.component,props:O.props},null,2):"";return{markdown:Fe,jsonPayload:Me,id:te}},Y=async()=>{let O=we.find(te=>te.id===Le)??we[we.length-1];try{await navigator.clipboard.writeText(As(O))}catch{}};if(Q.addEventListener("click",async()=>{let O=n?.onDocumentToolbarCopyMenuSelect;if(O&&w){let{markdown:te,jsonPayload:Fe,id:Me}=be();try{await O({actionId:"primary",artifactId:Me,markdown:te,jsonPayload:Fe})}catch{}return}await Y()}),B&&q?.length){let O=()=>b.closest("[data-persona-root]")??document.body,te=()=>{$=Go({items:q.map(Fe=>({id:Fe.id,label:Fe.label})),onSelect:async Fe=>{let{markdown:Me,jsonPayload:E,id:J}=be(),v=n?.onDocumentToolbarCopyMenuSelect;try{v?await v({actionId:Fe,artifactId:J,markdown:Me,jsonPayload:E}):Fe==="markdown"||Fe==="md"?await navigator.clipboard.writeText(Me):Fe==="json"||Fe==="source"?await navigator.clipboard.writeText(E):await navigator.clipboard.writeText(Me||E)}catch{}},anchor:U??B,position:"bottom-right",portal:O()})};b.isConnected?te():requestAnimationFrame(te),B.addEventListener("click",Fe=>{Fe.stopPropagation(),$?.toggle()})}pe.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}le()}),ye.addEventListener("click",()=>{f(),t.onDismiss?.()});let ce=m("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(s)C.replaceChildren(),U?D.append(U,pe,ye):D.append(Q,pe,ye),D.insertBefore(De,ye),D.insertBefore(Te,ye),C.append(R.element,ce,D);else{let O=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");O.append(Q,De,Te,L),C.appendChild(T),C.appendChild(O)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=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&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let xe=e.features?.artifacts?.renderTabBar,me=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=Gl(Z,{onSelect:O=>t.onSelect(we[O].id)}),Pe=O=>{let te=O.scrollWidth-O.clientWidth,Fe=te>1,Me=Math.abs(O.scrollLeft);O.classList.toggle("persona-artifact-tab-fade-start",c&&Fe&&Me>1),O.classList.toggle("persona-artifact-tab-fade-end",u&&Fe&&Me<te-1)},Oe=0,je=()=>{if(Oe)return;let O=()=>{Oe=0,Pe(Z)};Oe=typeof requestAnimationFrame=="function"?requestAnimationFrame(O):setTimeout(O,0)};Z.addEventListener("scroll",()=>je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Pe(Z)).observe(Z);let Ne=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(i){for(let O of[Z,me])O.style.paddingLeft=i,O.style.paddingRight=i;Ne.style.padding=i}b.appendChild(C),b.appendChild(Z),b.appendChild(me),b.appendChild(Ne);let we=[],Le=null,ot=!1,ie=!0,Re=!1,xt=null,yt="",rt=null,Ee=!1,he=O=>O.artifactType==="markdown"&&!!O.file||s?P:"rendered",lt=O=>{s||(O&&!Ee?(C.insertBefore(R.element,T),Ee=!0):!O&&Ee&&(R.element.remove(),Ee=!1))},Ie=()=>Le&&we.find(O=>O.id===Le)||we[we.length-1],ge=()=>{let O=Cs(Ie());if(!O){De.replaceChildren();return}let te=re.filter(Fe=>Fe.visible===void 0||Fe.visible(O)).map(Fe=>Cr(Fe,{documentChrome:s,onClick:()=>{let Me=Cs(Ie());if(Me)try{Promise.resolve(Fe.onClick(Me)).catch(()=>{})}catch{}}}));De.replaceChildren(...te)},le=()=>{ge();let O=s&&we.length<=1,te=!!xe;if(Z.classList.toggle("persona-hidden",O||te),me.classList.toggle("persona-hidden",O||!te),te&&xe){let E=we.map(J=>J.id).join("|")+" "+(Le??"");if(E!==yt){yt=E;let J=xe({records:we,selectedId:Le,onSelect:t.onSelect});me.firstElementChild!==J&&me.replaceChildren(J)}}else{fe.beforeRender(),Z.replaceChildren();let E=[],J=-1;for(let[v,A]of we.entries()){let M=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");M.type="button";let W=A.artifactType==="markdown"?A.file:void 0,K=W?Ln(W.path):A.title||A.id.slice(0,8),H=W?.path||A.title||K;M.textContent=K,M.title=H,M.setAttribute("aria-label",H),A.id===Le&&(M.classList.add("persona-bg-persona-container","persona-border-persona-border"),J=v),M.addEventListener("click",()=>t.onSelect(A.id)),Z.appendChild(M),E.push(M)}if(fe.render(E,J),J>=0&&Le!==xt){xt=Le;let v=E[J];typeof v.scrollIntoView=="function"&&v.scrollIntoView({block:"nearest",inline:"nearest"})}Pe(Z)}let Fe=Le&&we.find(E=>E.id===Le)||we[we.length-1];if(!Fe){Ne.replaceChildren(),rt=null,lt(!1);return}let Me=Fe.artifactType==="markdown"?Fe.file:void 0;if(lt(!!Me),s){let E=Me?ao(Me):Fe.artifactType==="markdown"?"MD":Fe.component??"Component",J=(Fe.title||"Document").trim(),v=Me?Ln(Me.path):J.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${v} \xB7 ${E}`}else T.textContent=Me?Ln(Me.path):r;rt?(rt.el.parentElement!==Ne&&Ne.replaceChildren(rt.el),rt.update(Fe)):(rt=_a(Fe,{config:e,resolveViewMode:he}),Ne.replaceChildren(rt.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},ve=()=>{let O=we.length>0;if(b.classList.toggle("persona-hidden",!O),h){let Me=((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;O&&Me&&ot?(h.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},Ct=()=>{Re=!1,le(),ve()};return{element:b,backdrop:h,update(O){we=O.artifacts,Le=O.selectedId??O.artifacts[O.artifacts.length-1]?.id??null,we.length>0&&(ot=!0),Re=!0,ie&&Ct()},setMobileOpen(O){ot=O,!O&&h?(h.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):ve()},setExpanded(O){let te=oe(O?"minimize":"maximize",16,"currentColor",2);te&&Te.replaceChildren(te);let Fe=O?"Collapse artifacts panel":"Expand artifacts panel";Te.setAttribute("aria-label",Fe),Te.title=Fe},setExpandToggleVisible(O){Te.classList.toggle("persona-hidden",!O)},setCopyButtonVisible(O){s||Q.classList.toggle("persona-hidden",!O)},setCustomActions(O){re=O,ge()},setTabFade(O){let te=d(O);te.start===c&&te.end===u||(c=te.start,u=te.end,Pe(Z))},setRenderTabBar(O){O!==xe&&(xe=O,yt="",le())},setVisible(O){O!==ie&&(ie=O,O&&Re&&Ct())}}}function Xt(e){return e?.features?.artifacts?.enabled===!0}function Ku(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function lx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Gu=["panel","seamless","detached"];function Jl(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&Gu.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function Xl(e){return!e||!Xt(e)?!1:Jl(e)==="detached"}function Ds(e,t){if(!Xt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),lx(e),Ku(e,t);return}let n=t.features?.artifacts?.layout,o=Jl(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?e.style.setProperty("--persona-artifact-pane-bg",s):e.style.removeProperty("--persona-artifact-pane-bg");let r=n?.panePadding?.trim();r?e.style.setProperty("--persona-artifact-pane-padding",r):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ku(e,t)}function Os(e,t){for(let i of Gu)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Xt(t))return;let n=t.features?.artifacts?.layout,o=Jl(t);e.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let r=n?.paneShadow?.trim();r&&e.style.setProperty("--persona-artifact-pane-shadow",r);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function Ju(e,t){return!t||!Xt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function cx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function dx(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function px(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function ux(e,t,n,o){let s=e-o-2*t-n;return Math.max(0,s)}function Ql(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let r=/^([\d.]+)/.exec(o);return r?Number(r[1]):8}function Xu(e,t,n,o,s,r){let a=cx(s,200),i=ux(t,n,o,200);i=Math.max(a,i);let p=dx(r);return p!==null&&(i=Math.min(i,p)),px(e,a,i)}var Qu={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"}},Yl=(e,t,n,o)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(r=>{if(r.dataset.enhanced==="true")return;let a=r.dataset.tvForm??"init";r.dataset.enhanced="true";let i=Qu[a]??Qu.init;r.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=i.title,p.appendChild(d),i.description){let b=m("p","persona-text-sm persona-text-persona-muted");b.textContent=i.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(b=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${b.name}`;let T=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,C.appendChild(T);let L=b.type??"text",P;L==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=L),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${b.name}`,P.name=b.name,P.placeholder=b.placeholder??"",b.required&&(P.required=!0),C.appendChild(P),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",u.appendChild(h),u.appendChild(f),c.appendChild(u),r.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let C=n.formEndpoint??"/form",T=new FormData(c),L={};T.forEach((P,R)=>{L[R]=P}),L.type=a,f.disabled=!0,h.textContent="Submitting\u2026";try{let P=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let R=await P.json();h.textContent=R.message??"Thanks! We'll be in touch soon.",R.success&&R.nextPrompt&&await o.sendMessage(String(R.nextPrompt))}catch(P){h.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Zl=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(r=>r.id));return[...n.filter(r=>!o.has(r.id)),...t].sort((r,a)=>(a.priority??0)-(r.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ii=new Zl;var Yu=()=>{let e=new Map,t=(s,r)=>(e.has(s)||e.set(s,new Set),e.get(s).add(r),()=>n(s,r)),n=(s,r)=>{e.get(s)?.delete(r)};return{on:t,off:n,emit:(s,r)=>{e.get(s)?.forEach(a=>{try{a(r)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var fx=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},gx=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<t.length;s+=1){let r=t[s];if(r==="{"&&(o+=1),r==="}"&&(o-=1,o===0))return t.slice(n,s+1)}return null},li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=fx(e),n=gx(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...r}=o;return{type:String(s),payload:r,raw:o}}catch{return null}},ec=e=>typeof e=="string"?e:e==null?"":String(e),kr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ec(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=ec(n.element);if(o&&t.document?.querySelector){let s=t.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:ec(n.text)}}},Zu=e=>Array.isArray(e)?e.map(t=>String(t)):[],ci=e=>{let t=new Set(Zu(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Zu(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let r=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:r}))};return{process:r=>{if(r.streaming||r.message.role!=="assistant"||!r.text||t.has(r.message.id))return null;let a=typeof r.raw=="string"&&r.raw||typeof r.message.rawContent=="string"&&r.message.rawContent||typeof r.text=="string"&&r.text||null;!a&&typeof r.text=="string"&&r.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:r.message})||null,null):null;if(!i)return null;t.add(r.message.id),o();let p={action:i,message:r.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:r.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!u)continue;if(u.handled){let h=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:h,resubmit:u.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var mx=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},hx=e=>e.map(t=>({...t,streaming:!1})),yx=e=>e.map(t=>({...t,status:"complete"})),tc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?mx(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let s={...n,messages:n.messages?hx(n.messages):void 0,artifacts:n.artifacts?yx(n.artifacts):void 0};o.setItem(e,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as bx,STR as vx,OBJ as xx}from"partial-json";function Cx(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function wx(e,t){if(!Cx(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function nc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let s=bx(n,vx|xx),r=wx(s,n);r&&(e=r)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ax(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function oc(e,t){let{config:n,message:o,onPropsUpdate:s}=t,r=Pn.get(e.component);if(!r)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{s&&s(i)}};try{return r(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Sx(){let e=nc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ef(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function di(e){let t=ef(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function rc(e){let t=ef(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var Tx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function sc(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:r="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=Tx}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,h=document.createElement("div");h.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 C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,f.appendChild(C),h.appendChild(f);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let _=1;_<=5;_++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-star-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`${_} star${_>1?"s":""}: ${d[_-1]}`),q.title=d[_-1],q.dataset.rating=String(_),q.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
- `,I.addEventListener("click",()=>{u=C,T.forEach((j,$)=>{let R=$<C;j.classList.toggle("selected",R),j.setAttribute("aria-checked",$===C-1?"true":"false")})}),T.push(I),S.appendChild(I)}f.appendChild(S);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),f.appendChild(C)}let P=document.createElement("div");P.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),P.appendChild(E),P.appendChild(k),f.appendChild(P),p.appendChild(f),p}function Vl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,b.appendChild(v);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,b.appendChild(S),g.appendChild(b);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=p,L.appendChild(P),L.appendChild(E);let k=document.createElement("div");k.className="persona-feedback-numbers";let C=[];for(let N=0;N<=10;N++){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 ${N} out of 10`),O.textContent=String(N),O.dataset.rating=String(N),N<=6?O.classList.add("persona-feedback-detractor"):N<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{f=N,C.forEach((Z,Ee)=>{Z.classList.toggle("selected",Ee===N),Z.setAttribute("aria-checked",Ee===N?"true":"false")})}),C.push(O),k.appendChild(O)}T.appendChild(L),T.appendChild(k),g.appendChild(T);let I=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),N.appendChild(I),g.appendChild(N)}let j=document.createElement("div");j.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let N=(I==null?void 0:I.value.trim())||void 0;await t(f,N),u.remove()}catch(N){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),j.appendChild($),j.appendChild(R),g.appendChild(j),u.appendChild(g),u}var Bs="persona-chat-history",Lw=30*1e3,Pw={"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 Iw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Pw[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Mi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Rw(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Ww(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kl=e=>!e||typeof e!="object"?{}:{...e},nf=e=>e.map(t=>({...t,streaming:!1})),rf=(e,t,n)=>{let r=e!=null&&e.markdown?vs(e.markdown):null,o=Xs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?rm(a):a,b=r(g);c=o&&d?o(b):b}else c=Kr(a);return c}};function of(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Gl=(e,t,n)=>{var $c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=hl(t),o=Si.getForInstance(r.plugins),{plugin:s,teardown:a}=Og();r.components&&Mo.registerAll(r.components);let i=Zg(),c=r.persistState===!1?null:($c=r.storageAdapter)!=null?$c:_l(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Kl(h.metadata)),(jc=h.messages)!=null&&jc.length&&(r={...r,initialMessages:h.messages}),(Uc=h.artifacts)!=null&&Uc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(qc=h.selectedArtifactId)!=null?qc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(zc=l.messages)!=null&&zc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let b=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},Pn()},S=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick],L=Ei({parsers:S,handlers:T,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let P=(Kc=(Vc=r.launcher)==null?void 0:Vc.enabled)!=null?Kc:!0,E=(Jc=(Gc=r.launcher)==null?void 0:Gc.autoExpand)!=null?Jc:!1,k=(Xc=r.autoFocusInput)!=null?Xc:!1,C=E,I=P,j=(Yc=(Qc=r.layout)==null?void 0:Qc.header)==null?void 0:Yc.layout,$=!1,R=()=>To(r),N=()=>P||R(),O=R()?!1:P?E:!0,Z=!1,Ee=null,de=()=>{Z=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=rf(r,L,de),Le=(ed=(Zc=r.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,Pe=(nd=(td=r.features)==null?void 0:td.showToolCalls)!=null?nd:!0,ne=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,Ae=(ad=(sd=r.features)==null?void 0:sd.scrollToBottom)!=null?ad:{},re=(ld=(id=r.features)==null?void 0:id.scrollBehavior)!=null?ld:{},ae=`${(dd=typeof r.persistState=="object"?(cd=r.persistState)==null?void 0:cd.keyPrefix:void 0)!=null?dd:"persona-"}event-stream`,fe=ne?new Sa(ae):null,$e=(md=(ud=(pd=r.features)==null?void 0:pd.eventStream)==null?void 0:ud.maxEvents)!=null?md:2e3,V=ne?new Aa($e,fe):null,Q=ne?new Ta:null,Me=null,J=!1,le=null,Ie=0;fe==null||fe.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let he={onCopy:l=>{var m,h;i.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ke=(gd=r.statusIndicator)!=null?gd:{},gt=l=>{var m,h,x,A,W,U;return l==="idle"?(m=Ke.idleText)!=null?m:nn.idle:l==="connecting"?(h=Ke.connectingText)!=null?h:nn.connecting:l==="connected"?(x=Ke.connectedText)!=null?x:nn.connected:l==="error"?(A=Ke.errorText)!=null?A:nn.error:l==="paused"?(W=Ke.pausedText)!=null?W:nn.paused:l==="resuming"?(U=Ke.resumingText)!=null?U:nn.resuming:nn[l]};function Wt(l,m,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=m,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=m}let tt=Sg({config:r,showClose:N()}),{wrapper:ge,panel:X,pillRoot:it}=tt.shell,Ve=tt.panelElements,{container:Se,body:we,messagesWrapper:Ze,suggestions:qt,textarea:be,sendButton:pe,sendButtonWrapper:vn,composerForm:Ct,statusText:fn,introTitle:yr,introSubtitle:br,closeButton:Ue,iconHolder:M,headerTitle:ue,headerSubtitle:Te,header:ke,footer:He,actionsRow:nt,leftActions:Qe,rightActions:ht}=Ve,me=Ve.setSendButtonMode,B=Ve.micButton,xe=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Je=Ve.attachmentInput,Lt=Ve.attachmentPreviewsContainer;Se.classList.add("persona-relative"),we.classList.add("persona-relative");let Mt=12,xt=()=>{var l;return(l=Ae.label)!=null?l:""},Rt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ot=()=>{var l;return(l=re.mode)!=null?l:"anchor-top"},en=()=>Ot()==="follow"||Ot()==="anchor-top"&&so,xr=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Nr=()=>{var l;return(l=re.restorePosition)!=null?l:"bottom"},or=()=>re.pauseOnInteraction===!0,sr=()=>re.showActivityWhilePinned!==!1,Xr=()=>re.announce===!0,zt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let ar=y("span","persona-flex persona-items-center"),Or=y("span",""),Hn=y("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",zt.append(ar,Or,Hn),Se.appendChild(zt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",we.appendChild(kn);let Bn=y("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.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"}),Se.appendChild(Bn);let ir=null,vr=null,Qr=l=>{!Xr()||!l||(vr=l,ir===null&&(ir=setTimeout(()=>{ir=null,vr&&Xr()&&(Bn.textContent=vr),vr=null},400)))},zn=()=>{let m=He.style.display==="none"?0:He.offsetHeight;zt.style.bottom=`${m+Mt}px`};zn();let Yr=()=>{let l=!!xt();zt.setAttribute("aria-label",xt()||"Jump to latest"),zt.title=xt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ar.innerHTML="";let m=ye(Rt(),"14px","currentColor",2);m?(ar.appendChild(m),ar.style.display=""):ar.style.display="none",Or.textContent=xt(),Or.style.display=l?"":"none"};Yr();let At=null,wr=null,Cr=o.find(l=>l.renderHeader);if(Cr!=null&&Cr.renderHeader){let l=Cr.renderHeader({config:r,defaultRenderer:()=>{let m=Eo({config:r,showClose:N()});return Ls(Se,m,r),m.header},onClose:()=>_t(!1,"user")});if(l){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ke=l,tt.header.element=l)}}let Fr=()=>{var m,h,x,A;if(!V)return;if(J=!0,!Me&&V&&(Me=Ug({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var W;return(W=Q==null?void 0:Q.getMetric())!=null?W:{status:"idle"}}})),Me&&(we.style.display="none",(m=He.parentNode)==null||m.insertBefore(Me.element,He),Me.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(A=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:A.toggleButtonActive;W&&W.split(/\s+/).forEach(U=>U&&yt.classList.add(U))}let l=()=>{if(!J)return;let W=Date.now();W-Ie>=200&&(Me==null||Me.update(),Ie=W),le=requestAnimationFrame(l)};Ie=0,le=requestAnimationFrame(l),Fn(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var l,m,h;if(J){if(J=!1,Me&&Me.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(A=>A&&yt.classList.remove(A))}le!==null&&(cancelAnimationFrame(le),le=null),Fn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ne){let l=(hd=(fd=r.features)==null?void 0:fd.eventStream)==null?void 0:hd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=y("button",m),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=ye("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let x=Ve.clearChatButtonWrapper,A=Ve.closeButtonWrapper,W=x||A;W&&W.parentNode===ke?ke.insertBefore(yt,W):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}let Lo=l=>{var A,W,U,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ie=l.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ie=y("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=((U=m.allowedTypes)!=null?U:Gr).join(","),ie.multiple=((_=m.maxFiles)!=null?_:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ie)}},Ar=o.find(l=>l.renderComposer);if(Ar!=null&&Ar.renderComposer){let l=r.composer,m=Ar.renderComposer({config:r,defaultRenderer:()=>wa({config:r}).footer,onSubmit:h=>{var U;if(!F||F.isStreaming())return;let x=h.trim(),A=(U=At==null?void 0:At.hasAttachments())!=null?U:!1;if(!x&&!A)return;hc();let W;A&&(W=[],W.push(...At.getContentParts()),x&&W.push(Ka(x))),F.sendMessage(x,{contentParts:W}),A&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((yd=r.voiceRecognition)==null?void 0:yd.enabled)===!0?()=>{wr==null||wr()}:void 0});m&&(tt.replaceComposer(m),He=tt.composer.footer)}let Po=l=>{let m=(...oe)=>{for(let Y of oe){let ve=l.querySelector(Y);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Ct=h),x&&(be=x),A&&(pe=A),W&&(B=W,xe=W.parentElement),U&&(fn=U);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(qt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(ce=D,ft=D.parentElement),Je=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(nt=ie)};Lo(He),Po(He);let Ln=(Cd=(bd=r.layout)==null?void 0:bd.contentMaxWidth)!=null?Cd:R()?(wd=(vd=(xd=r.launcher)==null?void 0:xd.composerBar)==null?void 0:vd.contentMaxWidth)!=null?wd:"720px":void 0;if(Ln&&(Ze.style.maxWidth=Ln,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Ln&&Ct&&!R()&&(Ct.style.maxWidth=Ln,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Ln&&qt&&!R()&&(qt.style.maxWidth=Ln,qt.style.marginLeft="auto",qt.style.marginRight="auto"),Ln&&Lt&&!R()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(Ad=r.attachments)!=null&&Ad.enabled&&Je&&Lt){At=Es.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Je.addEventListener("change",h=>{let x=h.target;At==null||At.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=of(l);Se.appendChild(m)}(()=>{var x,A;let l=(A=(x=r.layout)==null?void 0:x.slots)!=null?A:{},m=W=>{switch(W){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return fn;default:return null}},h=(W,U)=>{var _;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")ke.insertBefore(U,ke.firstChild);else if(W==="header-right")ke.appendChild(U);else{let D=ke.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(U,D.nextSibling):ke.appendChild(U)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(U):we.insertBefore(U,we.firstChild);break}case"body-bottom":we.appendChild(U);break;case"footer-top":qt.replaceWith(U);break;case"footer-bottom":fn.replaceWith(U);break;default:break}};for(let[W,U]of Object.entries(l))if(U)try{let _=U({config:r,defaultContent:()=>m(W)});_&&h(W,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,_)}})();let Zr=l=>{var U,_;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Is.has(A)?Is.delete(A):Is.add(A),Lg(A,x);else if(W==="tool")Rs.has(A)?Rs.delete(A):Rs.add(A),Pg(A,x,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,ie=((U=D==null?void 0:D.detailsDisplay)!=null?U:"collapsed")==="expanded",oe=(_=ns.get(A))!=null?_:ie;ns.set(A,!oe),Hg(A,x,r)}Mr.delete(A)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=Ze.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),W=og(A);!W||W===A||(m.setData("text/plain",W),l.preventDefault())});let _r=new Map,eo=null,to="idle",Io={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ro=(l,m)=>{let{icon:h,label:x}=Io[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let A=ye(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},no=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var W;let h=m.closest("[data-actions-for]"),x=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ro(m,x&&x===eo?to:"idle")})};Ze.addEventListener("click",l=>{var U;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let W=h.getAttribute("data-action");if(W==="copy"){let D=F.getMessages().find(ie=>ie.id===A);if(D&&he.onCopy){let ie=D.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let oe=ye("check",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ye("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),he.onCopy(D)}}else if(W==="read-aloud")F.toggleReadAloud(A);else if(W==="upvote"||W==="downvote"){let D=((U=_r.get(A))!=null?U:null)===W,ie=W==="upvote"?"thumbs-up":"thumbs-down";if(D){_r.delete(A),h.classList.remove("persona-message-action-active");let oe=ye(ie,14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))}else{let oe=W==="upvote"?"downvote":"upvote",Y=x.querySelector(`[data-action="${oe}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=ye(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}_r.set(A,W),h.classList.add("persona-message-action-active");let ve=ye(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Fe=F.getMessages().find(je=>je.id===A);Fe&&he.onFeedback&&he.onFeedback({type:W,messageId:Fe.id,message:Fe})}}}),Ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-approval-action");if(!W)return;let U=W==="approve"?"approved":"denied",D=F.getMessages().find(oe=>oe.id===A);if(!(D!=null&&D.approval))return;let ie=x.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?F.resolveWebMcpApproval(A,U):F.resolveApproval(D.approval,U)});let vt=null,Dn=null,Nn={artifacts:[],selectedId:null},wn=!1,St={current:null};Ze.addEventListener("click",l=>{var Y,ve,Oe,Fe,je;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Oe=(ve=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:x}))===!0)return;let W=F.getArtifactById(x),U=W==null?void 0:W.markdown,_=(W==null?void 0:W.title)||"artifact";if(!U){let qe=h.closest("[data-open-artifact]"),ut=qe==null?void 0:qe.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Re=F.getMessages().find(ze=>ze.id===st);if(Re!=null&&Re.rawContent)try{let ze=JSON.parse(Re.rawContent);U=(Fe=ze==null?void 0:ze.props)==null?void 0:Fe.markdown,_=((je=ze==null?void 0:ze.props)==null?void 0:je.title)||_}catch{}}}if(!U)return;let D=new Blob([U],{type:"text/markdown"}),ie=URL.createObjectURL(D),oe=document.createElement("a");oe.href=ie,oe.download=`${_}.md`,oe.click(),URL.revokeObjectURL(ie)}),Ze.addEventListener("click",l=>{var W,U,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||((_=(U=(W=r.features)==null?void 0:W.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:_.call(U,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),wn=!1,F.selectArtifact(x),Sr())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Vn=Ve.composerOverlay,Kn=(l,m,h)=>{var _,D,ie,oe;let x=m.trim();if(!x||!St.current)return;let A=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?x.split(", "):[x],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Jo(Vn,A);let U=St.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===A});(ie=U==null?void 0:U.agentMetadata)!=null&&ie.awaitingLocalTool?St.current.resolveAskUserQuestion(U,(oe=h.structured)!=null?oe:x):St.current.sendMessage(x)},On=l=>{var A;let m=St.current;if(!m)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",x=m.getMessages().find(W=>{var U;return((U=W.toolCall)==null?void 0:U.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:Na(l,x),currentIndex:er(l)})},ro=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=l=>{var A,W,U;if(((W=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=er(l),h=Cs(l);if(m>=h-1)return;let x=(U=St.current)==null?void 0:U.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});x&&(Oa(l,x,r,m+1),On(l))};Vn.addEventListener("click",l=>{var W,U,_,D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let Be=(W=x.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be);let Re=(U=St.current)==null?void 0:U.getMessages().find(ze=>{var Xe;return((Xe=ze.toolCall)==null?void 0:Xe.id)===Be});(_=Re==null?void 0:Re.agentMetadata)!=null&&_.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Re),(ie=St.current)==null||ie.resolveAskUserQuestion(Re,"(dismissed)"));return}if(A==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let Re=x.getAttribute("data-multi-select")==="true",ze=xo(x);if(ze&&Re){let Xe=Go(x)[er(x)],bt=new Set(Array.isArray(Xe)?Xe:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),vo(x,Array.from(bt)),On(x);return}if(ze){vo(x,Be),On(x),Ce(x);return}if(Re){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let bt=x.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=el(x).length===0);return}Kn(x,Be,{source:"pick",values:[Be]});return}if(A==="submit-multi"){let Be=el(x);if(Be.length===0)return;Kn(x,Be.join(", "),{source:"multi",values:Be});return}if(A==="open-free-text"){let Be=x.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(A==="focus-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(A==="submit-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]'),Re=(oe=Be==null?void 0:Be.value)!=null?oe:"";if(!Re.trim())return;if(xo(x)){vo(x,Re.trim()),On(x),Ce(x);return}Kn(x,Re,{source:"free-text"});return}if(A==="next"||A==="back"){if(!St.current)return;let Be=(Y=x.getAttribute("data-tool-call-id"))!=null?Y:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Xe){let De=Go(x)[er(x)];(typeof De!="string"||De!==Xe)&&vo(x,Xe)}let bt=A==="next"?1:-1,H=er(x)+bt;Oa(x,Re,r,H),On(x);return}if(A==="submit-all"){if(!St.current)return;let Be=(Fe=x.getAttribute("data-tool-call-id"))!=null?Fe:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(qe=(je=ze==null?void 0:ze.value)==null?void 0:je.trim())!=null?qe:"";Xe&&vo(x,Xe);let bt=Na(x,Re);St.current.persistAskUserQuestionProgress(Re,{answers:bt,currentIndex:er(x)});let H=ro(bt);Kn(x,H||"(submitted)",{source:"submit-all",structured:bt});return}if(A==="skip"){if(!St.current)return;let Be=(ut=x.getAttribute("data-tool-call-id"))!=null?ut:"",Re=St.current.getMessages().find(We=>{var Ye;return((Ye=We.toolCall)==null?void 0:Ye.id)===Be});if(!Re)return;let ze=xo(x),Xe=er(x),bt=Cs(x),H=Xe>=bt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be),(st=Re.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Re),St.current.resolveAskUserQuestion(Re,"(dismissed)"));return}vo(x,"");let De=x.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),H){let We=Na(x,Re),Ye=ro(We);Kn(x,Ye||"(skipped)",{source:"submit-all",structured:We});return}Oa(x,Re,r,Xe+1),On(x);return}}),Vn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(xo(x)){vo(x,A.trim()),On(x),Ce(x);return}Kn(x,A,{source:"free-text"})}});let $r=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Vn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",$r);let Gn=null,Ft=null,Jn=null,jr=null,Ds=()=>{};function as(){jr==null||jr(),jr=null}let Ns=()=>{var U;if(!Gn||!Ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===Ft)return;let A=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${A}px`,Ft.style.zIndex="5";let W=x.offsetWidth-A/2;Ft.style.left=`${Math.max(0,W)}px`},Wo=()=>{},Sr=()=>{var h,x,A,W,U;if(!vt||!rr(r))return;Ci(e,r),Ai(e,r),Wo();let l=(W=(A=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:A.narrowHostMaxWidth)!=null?W:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),vt.update(Nn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(U=vt.backdrop)==null||U.classList.add("persona-hidden")):Nn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Ds()};if(rr(r)){X.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Se),vt=Vg(r,{onSelect:h=>{var x;return(x=St.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{wn=!0,Sr()}}),vt.element.classList.add("persona-hidden"),Gn=m,m.appendChild(l),m.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(m),Ds=()=>{var x,A,W,U;if(!Gn||!vt)return;if(!(((W=(A=(x=r.features)==null?void 0:x.artifacts)==null?void 0:A.layout)==null?void 0:W.resizable)===!0)){Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Ft){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,ie=(U=D.defaultView)!=null?U:window,oe=Y=>{var ut,st;if(!vt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),as();let ve=Y.clientX,Oe=vt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,je=Be=>{let Re=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Xe=ze?0:Xg(Gn,ie),bt=ze?0:_.getBoundingClientRect().width||6,H=Oe-(Be.clientX-ve),De=Qg(H,Re,Xe,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);vt.element.style.width=`${De}px`,vt.element.style.maxWidth="none",Ns()},qe=()=>{D.removeEventListener("pointermove",je),D.removeEventListener("pointerup",qe),D.removeEventListener("pointercancel",qe),jr=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};jr=qe,D.addEventListener("pointermove",je),D.addEventListener("pointerup",qe),D.addEventListener("pointercancel",qe);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",oe),Ft=_,Gn.insertBefore(_,vt.element),Jn=()=>{_.removeEventListener("pointerdown",oe)}}if(Ft){let _=Nn.artifacts.length>0&&!wn;Ft.classList.toggle("persona-hidden",!_),Ns()}},Wo=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe;if(!P||!vt||((oe=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?oe:!1)||dn(r)&&nr(r).reveal==="emerge")return;let x=(Y=e.ownerDocument.defaultView)!=null?Y:window,A=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,W=(je=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?je:640;if(A&&x.innerWidth<=W||!Jg(r,P))return;let U=(st=(ut=(qe=r.launcher)==null?void 0:qe.width)!=null?ut:r.launcherWidth)!=null?st:tr,_=(Xe=(ze=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:ze.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!wn?(X.style.width=_,X.style.maxWidth=_):(X.style.width=U,X.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Sr()}),Dn.observe(X))}else X.appendChild(Se),R()&&it&&(Ve.peekBanner&&it.appendChild(Ve.peekBanner),it.appendChild(He));e.appendChild(ge),it&&e.appendChild(it);let oo=()=>{var De,We,Ye,Pt,_e,Kt,wt,an,Rn,Ht,mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo,et;if(R()){X.style.width="100%",X.style.maxWidth="100%";let Nt=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Bt=ge.dataset.state==="expanded",Vt=(Ye=Nt.expandedSize)!=null?Ye:"anchored";if(!(Bt&&Vt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let mt=(_e=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:_e.panel,jt=ma(r),gn=(un,Zn)=>{var ho;return un==null||un===""?Zn:(ho=Ms(jt,un))!=null?ho:un},jn="1px solid var(--persona-border)",Ir="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))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=gn(mt==null?void 0:mt.border,jn),Se.style.borderRadius=gn(mt==null?void 0:mt.borderRadius,pn),Se.style.boxShadow=gn(mt==null?void 0:mt.shadow,Ir),Se.style.overflow="hidden";return}let l=dn(r),m=(wt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=l||m||((Rn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Rn:!1),x=((Ht=r.launcher)==null?void 0:Ht.enabled)===!1,A=(_n=(mn=r.theme)==null?void 0:mn.components)==null?void 0:_n.panel,W=ma(r),U=(Nt,Bt)=>{var Vt;return Nt==null||Nt===""?Bt:(Vt=Ms(W,Nt))!=null?Vt:Nt},_=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,ie=(Fo=(Oo=r.launcher)==null?void 0:Oo.mobileBreakpoint)!=null?Fo:640,oe=_.innerWidth<=ie,Y=D&&oe&&P,ve=($o=(_o=r.launcher)==null?void 0:_o.position)!=null?$o:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Fe=(hs=(fs=r.launcher)==null?void 0:fs.zIndex)!=null?hs:xn,je=m||Y?"none":"1px solid var(--persona-border)",qe=Y?"none":m?Oe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(qe="none",je="none");let ut=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=U(A==null?void 0:A.border,je),Be=U(A==null?void 0:A.shadow,qe),Re=U(A==null?void 0:A.borderRadius,ut),ze=we.scrollTop;e.style.cssText="",ge.style.cssText="",X.style.cssText="",Se.style.cssText="",we.style.cssText="",He.style.cssText="",J&&(we.style.display="none");let Xe=()=>{var Bt;if(ze<=0)return;((Bt=we.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(ze,Vt))})};if(Y){ge.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"),ge.style.cssText=`
40
+ `,q.addEventListener("click",()=>{u=_,L.forEach((w,U)=>{let Q=U<_;w.classList.toggle("selected",Q),w.setAttribute("aria-checked",U===_-1?"true":"false")})}),L.push(q),T.appendChild(q)}h.appendChild(T);let P=null;if(p){let _=document.createElement("div");_.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=r,P.rows=3,P.setAttribute("aria-label","Additional comments"),_.appendChild(P),h.appendChild(_)}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=i,D.addEventListener("click",()=>{n?.(),c.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=a,z.addEventListener("click",async()=>{if(u===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let _=P?.value.trim()||void 0;await t(u,_),c.remove()}catch(_){z.disabled=!1,z.textContent=a,console.error("[CSAT Feedback] Failed to submit:",_)}}),R.appendChild(D),R.appendChild(z),h.appendChild(R),c.appendChild(h),c}function ac(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:r="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let h=null,f=document.createElement("div");f.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,b.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,b.appendChild(T),f.appendChild(b);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let P=document.createElement("div");P.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,P.appendChild(R),P.appendChild(D);let z=document.createElement("div");z.className="persona-feedback-numbers";let _=[];for(let B=0;B<=10;B++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-number-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`Rating ${B} out of 10`),$.textContent=String(B),$.dataset.rating=String(B),B<=6?$.classList.add("persona-feedback-detractor"):B<=8?$.classList.add("persona-feedback-passive"):$.classList.add("persona-feedback-promoter"),$.addEventListener("click",()=>{h=B,_.forEach((pe,ye)=>{pe.classList.toggle("selected",ye===B),pe.setAttribute("aria-checked",ye===B?"true":"false")})}),_.push($),z.appendChild($)}L.appendChild(P),L.appendChild(z),f.appendChild(L);let q=null;if(p){let B=document.createElement("div");B.className="persona-feedback-comment-container",q=document.createElement("textarea"),q.className="persona-feedback-comment",q.placeholder=r,q.rows=3,q.setAttribute("aria-label","Additional comments"),B.appendChild(q),f.appendChild(B)}let w=document.createElement("div");w.className="persona-feedback-actions";let U=document.createElement("button");U.type="button",U.className="persona-feedback-btn persona-feedback-btn-skip",U.textContent=i,U.addEventListener("click",()=>{n?.(),u.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(h===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let B=q?.value.trim()||void 0;await t(h,B),u.remove()}catch(B){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",B)}}),w.appendChild(U),w.appendChild(Q),f.appendChild(w),u.appendChild(f),u}var Lr="persona-chat-history",Ex=30*1e3,Mx=641,kx={"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 Lx(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let s=o.getAsFile();if(!s)continue;if(s.name){t.push(s);continue}let r=kx[s.type]??"png";t.push(new File([s],`clipboard-image-${Date.now()}.${r}`,{type:s.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function pi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Px(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function Rx(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var ic=e=>!e||typeof e!="object"?{}:{...e},tf=e=>e.map(t=>({...t,streaming:!1})),nf=(e,t,n)=>{let o=e?.markdown?pr(e.markdown):null,s=ns(e?.sanitize);return e?.postprocessMessage&&s&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),r=>{let a=r.text??"",i=r.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:r.message,streaming:r.streaming});c!==null&&(a=c.text,c.persist||(r.message.__skipPersist=!0),c.resubmit&&!r.streaming&&n&&n())}let p=Fn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...r,text:a,raw:i??r.text??""});d=s?s(c):c}else if(o){let c=r.streaming?$d(a):a,u=o(c);d=s&&p?s(u):u}else d=_n(a);return d}};function of(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",s=e?.iconColor??"rgba(59, 130, 246, 0.6)",r=e?.iconStrokeWidth??.5,a=oe(n,o,s,r);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var lc=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=wl(t),s=ii.getForInstance(o.plugins),{plugin:r,teardown:a}=_u();o.components&&Pn.registerAll(o.components);let i=Yu(),d=o.persistState===!1?null:o.storageAdapter??tc(),c={},u=null,h=!1,f=l=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:x}=g;return x&&(h=!0),y}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(g=>f(g??{messages:[],metadata:{}}));else{let y=f(l??{messages:[],metadata:{}});y.metadata&&(c=ic(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=f({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let b=()=>c,C=l=>{c=l({...c})??{},Di()},T=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[kr.message,kr.messageAndClick],P=ci({parsers:T,handlers:L,getSessionMetadata:b,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});P.syncFromMetadata();let R=o.launcher?.enabled??!0,D=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,_=D,q=R,w=o.layout?.header?.layout,U=!1,Q=()=>mo(o),B=()=>R||Q(),$=Q()?!1:R?D:!0,pe=!1,ye=null,Te=()=>{pe=!0,ye&&clearTimeout(ye),ye=setTimeout(()=>{pe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),pe=!1)},1e4)},De=nf(o,P,Te),re=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},me=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=Y?new Hs(me):null,Pe=o.features?.eventStream?.maxEvents??2e3,Oe=Y?new Ws(Pe,fe):null,je=Y?new Bs:null,Ne=null,we=!1,Le=null,ot=0;fe?.open().then(()=>Oe?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ie={onCopy:l=>{i.emit("message:copy",l),N?.isClientTokenMode()&&N.submitMessageFeedback(l.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),N?.isClientTokenMode()&&N.submitMessageFeedback(l.messageId,l.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(l)}},Re=o.statusIndicator??{},xt=l=>l==="idle"?Re.idleText??Ht.idle:l==="connecting"?Re.connectingText??Ht.connecting:l==="connected"?Re.connectedText??Ht.connected:l==="error"?Re.errorText??Ht.error:l==="paused"?Re.pausedText??Ht.paused:l==="resuming"?Re.resumingText??Ht.resuming:Ht[l];function yt(l,g,y,x){if(x==="idle"&&y.idleLink){l.textContent="";let S=document.createElement("a");S.href=y.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=g,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=g}let rt=Eu({config:o,showClose:B()}),{wrapper:Ee,panel:he,pillRoot:lt}=rt.shell,Ie=rt.panelElements,{container:ge,body:le,messagesWrapper:ve,suggestions:Ct,textarea:O,sendButton:te,sendButtonWrapper:Fe,composerForm:Me,statusText:E,introTitle:J,introSubtitle:v,closeButton:A,iconHolder:M,headerTitle:W,headerSubtitle:K,header:H,footer:j,actionsRow:se,leftActions:et,rightActions:We}=Ie,ct=Ie.setSendButtonMode,V=Ie.micButton,Ue=Ie.micButtonWrapper,Ae=Ie.attachmentButton,He=Ie.attachmentButtonWrapper,ke=Ie.attachmentInput,Xe=Ie.attachmentPreviewsContainer;ge.classList.add("persona-relative"),le.classList.add("persona-relative");let bo=12,vo=()=>ce.label??"",xi=()=>ce.iconName??"arrow-down",Fs=()=>ce.enabled!==!1,Qt=()=>Z.mode??"anchor-top",Un=()=>Qt()==="follow"||Qt()==="anchor-top"&&Nr,bc=()=>Z.anchorTopOffset??16,Ff=()=>Z.restorePosition??"bottom",vc=()=>Z.pauseOnInteraction===!0,xc=()=>Z.showActivityWhilePinned!==!1,Cc=()=>Z.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 Pr=m("span","persona-flex persona-items-center"),Ci=m("span",""),xo=m("span","");xo.setAttribute("data-persona-scroll-to-bottom-count",""),xo.style.display="none",It.append(Pr,Ci,xo),ge.appendChild(It);let zn=m("div","persona-stream-anchor-spacer");zn.setAttribute("aria-hidden","true"),zn.setAttribute("data-persona-anchor-spacer",""),zn.style.flexShrink="0",zn.style.pointerEvents="none",zn.style.height="0px",le.appendChild(zn);let Co=m("div","persona-sr-only");Co.setAttribute("aria-live","polite"),Co.setAttribute("aria-atomic","true"),Co.setAttribute("role","status"),Co.setAttribute("data-persona-live-region",""),Object.assign(Co.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"}),ge.appendChild(Co);let Rr=null,_s=null,wc=l=>{!Cc()||!l||(_s=l,Rr===null&&(Rr=setTimeout(()=>{Rr=null,_s&&Cc()&&(Co.textContent=_s),_s=null},400)))},Yo=()=>{let g=j.style.display==="none"?0:j.offsetHeight;It.style.bottom=`${g+bo}px`};Yo();let Ac=()=>{let l=!!vo();It.setAttribute("aria-label",vo()||"Jump to latest"),It.title=vo(),It.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Pr.innerHTML="";let g=oe(xi(),"14px","currentColor",2);g?(Pr.appendChild(g),Pr.style.display=""):Pr.style.display="none",Ci.textContent=vo(),Ci.style.display=l?"":"none"};Ac();let kt=null,Sc=null,Tc=s.find(l=>l.renderHeader);if(Tc?.renderHeader){let l=Tc.renderHeader({config:o,defaultRenderer:()=>{let g=ho({config:o,showClose:B()});return Ar(ge,g,o),g.header},onClose:()=>ht(!1,"user")});if(l){let g=ge.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),H=l,rt.header.element=l)}}let wi=()=>{if(!Oe)return;if(we=!0,!Ne&&Oe&&(Ne=qu({buffer:Oe,getFullHistory:()=>Oe.getAllFromStore(),onClose:()=>Ir(),config:o,plugins:s,getThroughput:()=>je?.getMetric()??{status:"idle"}})),Ne&&(le.style.display="none",j.parentNode?.insertBefore(Ne.element,j),Ne.update()),at){at.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(y=>y&&at.classList.add(y))}let l=()=>{if(!we)return;let g=Date.now();g-ot>=200&&(Ne?.update(),ot=g),Le=requestAnimationFrame(l)};ot=0,Le=requestAnimationFrame(l),tn(),i.emit("eventStream:opened",{timestamp:Date.now()})},Ir=()=>{if(we){if(we=!1,Ne&&Ne.element.remove(),le.style.display="",at){at.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(g=>g&&at.classList.remove(g))}Le!==null&&(cancelAnimationFrame(Le),Le=null),tn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},at=null;if(Y){let l=o.features?.eventStream?.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");at=m("button",g),at.style.width="28px",at.style.height="28px",at.style.color=Jt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let y=oe("activity","18px","currentColor",1.5);y&&at.appendChild(y);let x=Ie.clearChatButtonWrapper,S=Ie.closeButtonWrapper,k=x||S;k&&k.parentNode===H?H.insertBefore(at,k):H.appendChild(at),at.addEventListener("click",()=>{we?Ir():wi()})}let _f=l=>{let g=o.attachments;if(!g?.enabled)return;let y=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!y){y=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let S=l.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(y,S):l.insertBefore(y,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let S=m("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(g.allowedTypes??$n).join(","),S.multiple=(g.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),l.appendChild(S)}},Ec=s.find(l=>l.renderComposer);if(Ec?.renderComposer){let l=o.composer,g=Ec.renderComposer({config:o,defaultRenderer:()=>Rs({config:o}).footer,onSubmit:y=>{if(!N||N.isStreaming())return;let x=y.trim(),S=kt?.hasAttachments()??!1;if(!x&&!S)return;td();let k;S&&(k=[],k.push(...kt.getContentParts()),x&&k.push(Ea(x))),N.sendMessage(x,{contentParts:k}),S&&kt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{ke?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Sc?.()}:void 0});g&&(rt.replaceComposer(g),j=rt.composer.footer)}let $f=l=>{let g=(...de)=>{for(let ne of de){let Ce=l.querySelector(ne);if(Ce)return Ce}return null},y=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),X=l.querySelector("[data-persona-composer-status]");y&&(Me=y),x&&(O=x),S&&(te=S),k&&(V=k,Ue=k.parentElement),X&&(E=X);let F=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(Ct=F);let G=g("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Ae=G,He=G.parentElement),ke=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Xe=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)};_f(j),$f(j);let qn=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(qn&&(ve.style.maxWidth=qn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),qn&&Me&&!Q()&&(Me.style.maxWidth=qn,Me.style.marginLeft="auto",Me.style.marginRight="auto"),qn&&Ct&&!Q()&&(Ct.style.maxWidth=qn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qn&&Xe&&!Q()&&(Xe.style.maxWidth=qn,Xe.style.marginLeft="auto",Xe.style.marginRight="auto"),o.attachments?.enabled&&ke&&Xe){kt=yr.fromConfig(o.attachments),kt.setPreviewsContainer(Xe),ke.addEventListener("change",y=>{let x=y.target;kt?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,g=of(l);ge.appendChild(g)}(()=>{let l=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return Ct;case"composer":return Me;case"footer-bottom":return E;default:return null}},y=(x,S)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")H.insertBefore(S,H.firstChild);else if(x==="header-right")H.appendChild(S);else{let k=H.querySelector(".persona-flex-col");k?k.parentNode?.insertBefore(S,k.nextSibling):H.appendChild(S)}break;case"body-top":{let k=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");k?k.replaceWith(S):le.insertBefore(S,le.firstChild);break}case"body-bottom":le.appendChild(S);break;case"footer-top":Ct.replaceWith(S);break;case"footer-bottom":E.replaceWith(S);break;default:break}};for(let[x,S]of Object.entries(l))if(S)try{let k=S({config:o,defaultContent:()=>g(x)});k&&y(x,k)}catch(k){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,k)}})();let Mc=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let x=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let k=y.getAttribute("data-bubble-type");if(k==="reasoning")Tr.has(S)?Tr.delete(S):Tr.add(S),Ru(S,x);else if(k==="tool")Er.has(S)?Er.delete(S):Er.add(S),Iu(S,x,o);else if(k==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Jo.get(S)??F;Jo.set(S,!G),Du(S,x,o)}To.delete(S)};ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Mc(l))}),ve.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Mc(l))}),ve.addEventListener("copy",l=>{let{clipboardData:g}=l;if(!g)return;let y=ve.getRootNode(),x=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let S=x.toString(),k=au(S);!k||k===S||(g.setData("text/plain",k),l.preventDefault())});let Ai=new Map,kc=null,Lc="idle",jf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Uf=(l,g)=>{let{icon:y,label:x}=jf[g];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",g==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",g!=="idle"),l.classList.toggle("persona-message-action-loading",g==="loading");let S=oe(y,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Pc=()=>{ve.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Uf(g,x&&x===kc?Lc:"idle")})};ve.addEventListener("click",l=>{let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.closest("[data-actions-for]");if(!x)return;let S=x.getAttribute("data-actions-for");if(!S)return;let k=y.getAttribute("data-action");if(k==="copy"){let F=N.getMessages().find(G=>G.id===S);if(F&&ie.onCopy){let G=F.content||"";navigator.clipboard.writeText(G).then(()=>{y.classList.add("persona-message-action-success");let ae=oe("check",14,"currentColor",2);ae&&(y.innerHTML="",y.appendChild(ae)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let de=oe("copy",14,"currentColor",2);de&&(y.innerHTML="",y.appendChild(de))},2e3)}).catch(ae=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ae)}),ie.onCopy(F)}}else if(k==="read-aloud")N.toggleReadAloud(S);else if(k==="upvote"||k==="downvote"){let F=(Ai.get(S)??null)===k,G=k==="upvote"?"thumbs-up":"thumbs-down";if(F){Ai.delete(S),y.classList.remove("persona-message-action-active");let ae=oe(G,14,"currentColor",2);ae&&(y.innerHTML="",y.appendChild(ae))}else{let ae=k==="upvote"?"downvote":"upvote",de=x.querySelector(`[data-action="${ae}"]`);if(de){de.classList.remove("persona-message-action-active");let it=oe(ae==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);it&&(de.innerHTML="",de.appendChild(it))}Ai.set(S,k),y.classList.add("persona-message-action-active");let ne=oe(G,14,"currentColor",2);ne&&(ne.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ne)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ke=N.getMessages().find(bt=>bt.id===S);Ke&&ie.onFeedback&&ie.onFeedback({type:k,messageId:Ke.id,message:Ke})}}}),ve.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.closest(".persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let k=y.getAttribute("data-approval-action");if(!k)return;let X=k==="approve"?"approved":"denied",G=N.getMessages().find(de=>de.id===S);if(!G?.approval)return;let ae=x.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(ne=>{ne.disabled=!0,ne.style.opacity="0.5",ne.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?N.resolveWebMcpApproval(S,X):N.resolveApproval(G.approval,X)});let Qe=null,Wr=null,Hr=()=>{},Br="none",$s=null,gn={artifacts:[],selectedId:null},Wn=!1,mn=!1,Dr=!1,Zo=!1,Rc=()=>Zo||gn.artifacts.some(l=>No(o.features?.artifacts,l.artifactType)==="panel"),js=()=>gn.artifacts.length>0&&!Wn&&Rc(),gt={current:null},Si=(l,g)=>{let y=N.getArtifactById(g),x=y?.markdown,S=y?.title||"artifact",k=y?.file,X=y?.artifactType??"markdown";if(!x){let ae=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ae){let ne=N.getMessages().find(Ce=>Ce.id===ae);if(ne?.rawContent)try{let Ce=JSON.parse(ne.rawContent);x=Ce?.props?.markdown,S=Ce?.props?.title||S,Ce?.props?.file&&typeof Ce.props.file=="object"&&(k=Ce.props.file),!y&&typeof Ce?.props?.artifactType=="string"&&(X=Ce.props.artifactType)}catch{}}}return{markdown:x,title:S,file:k,artifactType:X}};ve.addEventListener("click",l=>{let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:k,title:X,file:F}=Si(y,x);if(!k)return;let{filename:G,mime:ae,content:de}=Up({title:X,markdown:k,file:F}),ne=new Blob([de],{type:ae}),Ce=URL.createObjectURL(ne),Ke=document.createElement("a");Ke.href=Ce,Ke.download=G,Ke.click(),URL.revokeObjectURL(Ce)}),ve.addEventListener("click",l=>{let y=l.target.closest("[data-artifact-custom-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.getAttribute("data-artifact-custom-action");if(!x)return;let S=y.closest("[data-artifact-inline]"),k=S?null:y.closest("[data-open-artifact]"),X=S?S.getAttribute("data-artifact-inline"):k?.getAttribute("data-open-artifact")??null,G=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(bt=>bt.id===x);if(!G)return;let{markdown:ae,title:de,file:ne,artifactType:Ce}=Si(y,X??""),Ke={artifactId:X,title:de,artifactType:Ce,markdown:ae,file:ne};try{Promise.resolve(G.onClick(Ke)).catch(()=>{})}catch{}}),ve.addEventListener("click",l=>{let y=l.target.closest("[data-copy-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.getAttribute("data-copy-artifact");if(!x)return;let S=N.getArtifactById(x),k="";if(S)k=As(S);else{let{markdown:X,file:F,artifactType:G}=Si(y,x);G==="markdown"&&(k=As({id:x,artifactType:"markdown",status:"complete",markdown:X??"",...F?{file:F}:{}}))}k&&navigator.clipboard.writeText(k).then(()=>{let X=oe("check",16,"currentColor",2);X&&(y.replaceChildren(X),setTimeout(()=>{let F=oe("copy",16,"currentColor",2);F&&y.replaceChildren(F)},1500))}).catch(()=>{})}),ve.addEventListener("click",l=>{let y=l.target.closest("[data-expand-artifact-inline]");if(!y)return;l.preventDefault(),l.stopPropagation();let x=y.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Wn=!1,Zo=!0,mn=!0,Dr=!0,N.selectArtifact(x),Hn())}),ve.addEventListener("click",l=>{let g=l.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let y=g.closest("[data-open-artifact]");if(!y)return;let x=y.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Wn=!1,Zo=!0,N.selectArtifact(x),Hn())}),ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),g.click())});let er=Ie.composerOverlay,tr=(l,g,y)=>{let x=g.trim();if(!x||!gt.current)return;let S=l.getAttribute("data-tool-call-id")??"",k=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:x,answers:y.structured,values:y.values??(y.source==="multi"?x.split(", "):[x]),isFreeText:k,source:y.source},bubbles:!0,composed:!0})),$o(er,S);let X=gt.current.getMessages().find(F=>F.toolCall?.id===S);X?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(X,y.structured??x):gt.current.sendMessage(x)},wo=l=>{let g=gt.current;if(!g)return;let y=l.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(S=>S.toolCall?.id===y);x&&g.persistAskUserQuestionProgress(x,{answers:ya(l,x),currentIndex:un(l)})},Ic=l=>Object.entries(l).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Ti=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=un(l),y=fr(l);if(g>=y-1)return;let x=gt.current?.getMessages().find(S=>S.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(ba(l,x,o,g+1),wo(l))};er.addEventListener("click",l=>{let y=l.target.closest("[data-ask-user-action]");if(!y)return;let x=y.closest("[data-persona-ask-sheet-for]");if(!x)return;let S=y.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let k=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),$o(er,k);let X=gt.current?.getMessages().find(F=>F.toolCall?.id===k);X?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(X),gt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(S==="pick"){let k=y.getAttribute("data-option-label");if(!k)return;let X=x.getAttribute("data-multi-select")==="true",F=oo(x);if(F&&X){let G=_o(x)[un(x)],ae=new Set(Array.isArray(G)?G:[]);ae.has(k)?ae.delete(k):ae.add(k),ro(x,Array.from(ae)),wo(x);return}if(F){ro(x,k),wo(x),Ti(x);return}if(X){let G=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",G?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!G);let ae=x.querySelector('[data-ask-user-action="submit-multi"]');ae&&(ae.disabled=al(x).length===0);return}tr(x,k,{source:"pick",values:[k]});return}if(S==="submit-multi"){let k=al(x);if(k.length===0)return;tr(x,k.join(", "),{source:"multi",values:k});return}if(S==="open-free-text"){let k=x.querySelector('[data-ask-free-text-row="true"]');k&&(k.classList.remove("persona-hidden"),k.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let X=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(oo(x)){ro(x,X.trim()),wo(x),Ti(x);return}tr(x,X,{source:"free-text"});return}if(S==="next"||S==="back"){if(!gt.current)return;let k=x.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(ne=>ne.toolCall?.id===k);if(!X)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let ne=_o(x)[un(x)];(typeof ne!="string"||ne!==G)&&ro(x,G)}let ae=S==="next"?1:-1,de=un(x)+ae;ba(x,X,o,de),wo(x);return}if(S==="submit-all"){if(!gt.current)return;let k=x.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(ne=>ne.toolCall?.id===k);if(!X)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&ro(x,G);let ae=ya(x,X);gt.current.persistAskUserQuestionProgress(X,{answers:ae,currentIndex:un(x)});let de=Ic(ae);tr(x,de||"(submitted)",{source:"submit-all",structured:ae});return}if(S==="skip"){if(!gt.current)return;let k=x.getAttribute("data-tool-call-id")??"",X=gt.current.getMessages().find(Ce=>Ce.toolCall?.id===k);if(!X)return;let F=oo(x),G=un(x),ae=fr(x),de=G>=ae-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:k},bubbles:!0,composed:!0})),$o(er,k),X.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(X),gt.current.resolveAskUserQuestion(X,"(dismissed)"));return}ro(x,"");let ne=x.querySelector('[data-ask-free-text-input="true"]');if(ne&&(ne.value=""),de){let Ce=ya(x,X),Ke=Ic(Ce);tr(x,Ke||"(skipped)",{source:"submit-all",structured:Ce});return}ba(x,X,o,G+1),wo(x);return}}),er.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let y=l.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let x=y.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let S=y.value;if(S.trim()){if(oo(x)){ro(x,S.trim()),wo(x),Ti(x);return}tr(x,S,{source:"free-text"})}});let Wc=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let g=l.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let y=er.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),k=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];k&&(l.preventDefault(),k.click())};document.addEventListener("keydown",Wc);let Vn=null,wt=null,Or=null,Us=null,Ei=()=>{},Hc=!1,zs="",qs="";function Mi(){Us?.(),Us=null}let Bc=()=>{if(!Vn||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),g=e.ownerDocument.defaultView??window,y=g.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){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 x=Vn.firstElementChild;if(!x||x===wt)return;let S=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${S}px`,wt.style.zIndex="5";let k=Ql(Vn,g),X=x.offsetWidth+k/2-S/2;wt.style.left=`${Math.max(0,X)}px`},Vs=()=>{},zf=()=>{let l=e.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!g||l.innerWidth>y?!1:R||Bt(o)},Ks=()=>!Xt(o)||!js()||e.classList.contains("persona-artifact-narrow-host")||zf()||(e.ownerDocument.defaultView??window).innerWidth<Mx?"none":Xl(o)?"detached":"welded",Hn=()=>{if(!Qe||!Xt(o))return;Ds(e,o),Os(e,o),Vs();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l);let y=js();Qe.setVisible(y),Qe.update(gn),Wn?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),mn=!1,Dr=!1):gn.artifacts.length>0&&Rc()?(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)):(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),Qe.backdrop?.classList.add("persona-hidden"),mn=!1,Dr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Qe.setExpandToggleVisible(x),Qe.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Qe.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Qe.setTabFade(o.features?.artifacts?.layout?.tabFade),Qe.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Dr&&(mn=!1),mn!==Hc){let k=Qe.element;mn?(zs=k.style.width,qs=k.style.maxWidth,k.style.removeProperty("width"),k.style.removeProperty("max-width")):(zs&&(k.style.width=zs),qs&&(k.style.maxWidth=qs),zs="",qs=""),Hc=mn}e.classList.toggle("persona-artifact-expanded",mn),Qe.setExpanded(mn);let S=Ks();S!==Br&&(Br=S,Hr()),Ei()};if(Xt(o)){he.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ge),Qe=Vu(o,{onSelect:y=>gt.current?.selectArtifact(y),onDismiss:()=>{Wn=!0,Hn()},onToggleExpand:()=>{let y=!mn,x=gn.selectedId??gn.artifacts[gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:y})!==!0&&(mn=y,y||(Dr=!1),Hn())}}),Qe.element.classList.add("persona-hidden"),Vn=g,g.appendChild(l),g.appendChild(Qe.element),Qe.backdrop&&he.appendChild(Qe.backdrop),he.appendChild(g),Ei=()=>{if(!Vn||!Qe)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Or?.(),Or=null,Mi(),wt&&(wt.remove(),wt=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!wt){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let S=e.ownerDocument,k=S.defaultView??window,X=F=>{if(!Qe||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||k.innerWidth<=640)return;F.preventDefault(),Mi();let G=F.clientX,ae=Qe.element.getBoundingClientRect().width,de=o.features?.artifacts?.layout,ne=Ke=>{let bt=Vn.getBoundingClientRect().width,it=e.classList.contains("persona-artifact-welded-split"),qt=Ql(Vn,k),Dt=it?0:x.getBoundingClientRect().width||6,I=ae-(Ke.clientX-G),_e=Xu(I,bt,qt,Dt,de?.resizableMinWidth,de?.resizableMaxWidth);Qe.element.style.width=`${_e}px`,Qe.element.style.maxWidth="none",Bc()},Ce=()=>{S.removeEventListener("pointermove",ne),S.removeEventListener("pointerup",Ce),S.removeEventListener("pointercancel",Ce),Us=null;try{x.releasePointerCapture(F.pointerId)}catch{}};Us=Ce,S.addEventListener("pointermove",ne),S.addEventListener("pointerup",Ce),S.addEventListener("pointercancel",Ce);try{x.setPointerCapture(F.pointerId)}catch{}};x.addEventListener("pointerdown",X),wt=x,Vn.insertBefore(x,Qe.element),Or=()=>{x.removeEventListener("pointerdown",X)}}if(wt){let x=js();wt.classList.toggle("persona-hidden",!x),Bc()}},Vs=()=>{if(!R||!Qe||(o.launcher?.sidebarMode??!1)||Bt(o)&&sn(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640;if(S&&x.innerWidth<=k||!Ju(o,R))return;let X=o.launcher?.width??o.launcherWidth??fn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";js()?(he.style.width=F,he.style.maxWidth=F):(he.style.width=X,he.style.maxWidth=X)},typeof ResizeObserver<"u"&&(Wr=new ResizeObserver(()=>{Hn()}),Wr.observe(he))}else he.appendChild(ge);Q()&&lt&&(Ie.peekBanner&&lt.appendChild(Ie.peekBanner),lt.appendChild(j)),e.appendChild(Ee),lt&&e.appendChild(lt);let Gs=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},Yt=Ee.dataset.state==="expanded",la=Rt.expandedSize??"anchored";if(!(Yt&&la!=="fullscreen")){ge.style.background="",ge.style.border="",ge.style.borderRadius="",ge.style.overflow="",ge.style.boxShadow="";return}let Jr=o.theme?.components?.panel,ca=Vo(o),cr=(Nn,Wo)=>Nn==null||Nn===""?Wo:Gt(ca,Nn)??Nn,Xr="1px solid var(--persona-border)",Qi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ge.style.background="var(--persona-surface, #ffffff)",ge.style.border=cr(Jr?.border,Xr),ge.style.borderRadius=cr(Jr?.borderRadius,Io),ge.style.boxShadow=cr(Jr?.shadow,Qi),ge.style.overflow="hidden";return}let l=Bt(o),g=o.launcher?.sidebarMode??!1,y=l||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,k=o.theme?.components?.panel,X=Vo(o),F=(Rt,Yt)=>Rt==null||Rt===""?Yt:Gt(X,Rt)??Rt,G=e.ownerDocument.defaultView??window,ae=o.launcher?.mobileFullscreen??!0,de=o.launcher?.mobileBreakpoint??640,ne=G.innerWidth<=de,Ce=ae&&ne&&R,Ke=l&&ae&&ne,bt=o.launcher?.position??"bottom-left",it=bt==="bottom-left"||bt==="top-left",qt=o.launcher?.zIndex??Ut,Dt="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)))",_e="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Se=S&&!Ce&&!Ke;Se?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let $e=Se?Dt:g||Ce?"none":Dt,Mt=Se?I:Ce?"none":g?it?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":I;l&&!Ce&&!Se&&(Mt="none",$e="none");let pt=Se?_e:g||Ce?"0":_e,St=F(k?.border,$e),vt=F(k?.shadow,Mt),$t=F(k?.borderRadius,pt),Po=Ks(),ut=Po==="detached",ue=Po==="welded";e.classList.toggle("persona-artifact-detached-split",ut),e.classList.toggle("persona-artifact-welded-split",ue);let Tt="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)))))",st=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Xt(o)&&Xl(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",st);let qe=ut||st?"none":vt,Ye=ut?Dt:ue?"none":St,Pt=ut?_e:$t;st&&(Ye="none",Pt="0");let Be=k?.borderRadius!=null&&k.borderRadius!=="",Ze=st&&!Be?"0":$t,nn=le.scrollTop;e.style.cssText="",Ee.style.cssText="",he.style.cssText="",ge.style.cssText="",le.style.cssText="",j.style.cssText="",we&&(le.style.display="none");let Ro=()=>{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(Ce){Ee.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Ee.style.cssText=`
35
41
  position: fixed !important;
36
42
  inset: 0 !important;
37
43
  width: 100% !important;
@@ -41,9 +47,9 @@ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
41
47
  padding: 0 !important;
42
48
  display: flex !important;
43
49
  flex-direction: column !important;
44
- z-index: ${Fe} !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: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
56
62
  padding: 0 !important;
57
63
  box-shadow: none !important;
58
64
  border-radius: 0 !important;
59
- `,Se.style.cssText=`
65
+ `,ge.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: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
67
73
  overflow: hidden !important;
68
74
  border-radius: 0 !important;
69
75
  border: none !important;
70
- `,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0",$=!0,Xe();return}let bt=(jo=(Jt=r==null?void 0:r.launcher)==null?void 0:Jt.width)!=null?jo:r==null?void 0:r.launcherWidth,H=bt!=null?bt:tr;if(!m&&!l)x&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=H,X.style.maxWidth=H);else if(l)if(nr(r).reveal==="emerge"){let Bt=nr(r).width;X.style.width=Bt,X.style.maxWidth=Bt}else X.style.width="100%",X.style.maxWidth="100%";if(Wo(),X.style.boxShadow=Be,X.style.borderRadius=Re,Se.style.border=st,Se.style.borderRadius=Re,l&&!Y&&(A==null?void 0:A.border)===void 0&&(Se.style.border="none",nr(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",x&&(ge.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",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0"),ge.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"),!m&&!x&&!l&&((go=hr[ve])!=null?go:hr["bottom-right"]).split(" ").forEach(Bt=>ge.classList.add(Bt)),m){let Nt=(Vr=(fo=r.launcher)==null?void 0:fo.sidebarWidth)!=null?Vr:"420px";ge.style.cssText=`
71
- position: fixed !important;
72
- top: 0 !important;
73
- bottom: 0 !important;
74
- width: ${Nt} !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: ${Fe} !important;
82
- ${Oe?"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",j.style.flexShrink="0",U=!0,Ro();return}let ia=o?.launcher?.width??o?.launcherWidth??fn;if(!g&&!l)x&&y?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=ia,he.style.maxWidth=ia);else if(l)if(sn(o).reveal==="emerge"&&!S){let Yt=sn(o).width;he.style.width=Yt,he.style.maxWidth=Yt}else he.style.width="100%",he.style.maxWidth="100%";if(Vs(),he.style.boxShadow=qe,he.style.borderRadius=Ze,ut?he.style.border="none":ue&&(he.style.border=St),ge.style.border=Ye,ge.style.borderRadius=Pt,ge.style.boxShadow=ut&&!st?Tt:"",st&&(ge.style.background="transparent",le.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),ue){let Rt=o.features?.artifacts?.layout;$s=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||$t}else $s=null;if(l&&!Ce&&!Se&&!ut&&!ue&&k?.border===void 0&&(ge.style.border="none",sn(o).side==="right"?ge.style.borderLeft="1px solid var(--persona-border)":ge.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&ue&&k?.border===void 0&&(sn(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.height="100%",x&&(Ee.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%",ut||(he.style.overflow="hidden"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",j.style.flexShrink="0"),x&&(Se||ut||st)&&!l&&(st||(Ee.style.padding="var(--persona-panel-inset)"),Ee.style.background="var(--persona-panel-canvas-bg)"),Ee.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!x&&!l&&(wn[bt]??wn["bottom-right"]).split(" ").forEach(Yt=>Ee.classList.add(Yt)),g){let Rt=o.launcher?.sidebarWidth??"420px";S?Ee.style.cssText=`
77
+ position: fixed !important;
78
+ top: var(--persona-panel-inset) !important;
79
+ bottom: var(--persona-panel-inset) !important;
80
+ width: ${Rt} !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
+ ${it?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
89
+ `:Ee.style.cssText=`
90
+ position: fixed !important;
91
+ top: 0 !important;
92
+ bottom: 0 !important;
93
+ width: ${Rt} !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
+ ${it?"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: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
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"),Se.style.cssText=`
113
+ box-shadow: ${qe} !important;
114
+ border-radius: ${Ze} !important;
115
+ ${ut?"border: none !important;":ue?`border: ${St} !important;`:""}
116
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),ge.style.cssText=`
97
117
  display: flex !important;
98
118
  flex-direction: column !important;
99
119
  flex: 1 1 0% !important;
@@ -102,29 +122,32 @@ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
102
122
  min-height: 0 !important;
103
123
  max-height: 100% !important;
104
124
  overflow: hidden !important;
105
- border-radius: ${Re} !important;
106
- border: ${st} !important;
107
- `,He.style.cssText=`
125
+ border-radius: ${Pt} !important;
126
+ border: ${Ye} !important;
127
+ ${ut&&!st?`box-shadow: ${Tt} !important;`:""}
128
+ ${st?"background: transparent !important;":""}
129
+ `,j.style.cssText=`
108
130
  flex-shrink: 0 !important;
109
131
  border-top: none !important;
110
132
  padding: 8px 16px 12px 16px !important;
111
- `}if(!x&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Bt=m?"":"padding-top: 1.25em !important;",Vt=m?"":`z-index: ${(et=(Uo=r.launcher)==null?void 0:Uo.zIndex)!=null?et:xn} !important;`;ge.style.cssText+=Nt+Bt+Vt}Xe()};oo(),es(e,r),Ci(e,r),Ai(e,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",$r)}),lt.push(()=>{ir!==null&&clearTimeout(ir)});let rn=null,on=null;lt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Dn&&lt.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ne&&lt.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Me==null||Me.destroy(),Me=null,V==null||V.destroy(),V=null,fe=null});let Tr=null,Os=()=>{Tr&&(Tr(),Tr=null),r.colorScheme==="auto"&&(Tr=xl(()=>{es(e,r)}))};Os(),lt.push(()=>{Tr&&(Tr(),Tr=null)}),lt.push(a);let Ur=(Sd=r.features)==null?void 0:Sd.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let l=ks(Ur.type,Ur.plugins);l&&(li(l,e),lt.push(()=>hg(e)))}let Ho=Fg(qt),Er=null,F,is=l=>{var x,A;if(!F)return;let m=l!=null?l:F.getMessages(),h=((A=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:A.enabled)!==!1?rl(m):null;h?Ho.render(h,F,be,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(W=>W.role==="user")?Ho.render([],F,be,m):Ho.render(r.suggestionChips,F,be,m,r.suggestionChipsConfig)},cr=!1,Mr=ig(),qr=new Map,kr=new Map,dr=new Map,ls=0,Ma=Vo()!==null,hn=ni(),Cn=0,pr=null,An=!1,Bo=!1,ur=0,yn=null,Lr=null,cs=!1,Do=!1,ds=null,so=!0,ao=!1,ot=null,w=4,z=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(Ed=(Td=r.voiceRecognition)==null?void 0:Td.autoResume)!=null?Ed:!1,rt=l=>{i.emit("voice:state",{active:K.active,source:l,timestamp:Date.now()})},ct=()=>{v(l=>({...l,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},Di=()=>{var x,A;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=Kl(p.voiceState),m=!!l.active,h=Number((A=l.timestamp)!=null?A:0);K.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<Lw&&setTimeout(()=>{var W,U;K.active||(K.manuallyDeactivated=!1,((U=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:U.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("restore"),F.isVoiceActive()&&ms()}):La("restore"))},1e3)},io=()=>F?nf(F.getMessages()).filter(l=>!l.__skipPersist):[];function Pn(l){if(!(c!=null&&c.save))return;let h={messages:l?nf(l):F?io():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};try{let x=c.save(h);x instanceof Promise&&x.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let Qt=null,lo=()=>ge.querySelector("#persona-scroll-container")||we,Xn=()=>{Qt!==null&&(cancelAnimationFrame(Qt),Qt=null),An=!1},Sn=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!1,Xn()},In=()=>cr&&Ni()&&(Ot()!=="anchor-top"||sr()),Tn=()=>{let l=xt()||"Jump to latest",m=In();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ur>0?(Hn.textContent=String(ur),Hn.style.display="",zt.setAttribute("aria-label",`${l} (${ur} new)`)):(Hn.textContent="",Hn.style.display="none",zt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},sc=()=>{ur!==0&&(ur=0,Tn())},Ni=()=>en()?!hn.isFollowing():!Co(we,z),Fn=()=>{if(!Xt()||J){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Se&&Se.appendChild(zt),zn();let m=Br(we)>0&&Ni();m?Tn():sc(),zt.style.display=m?"":"none"},Fs=()=>{hn.pause()&&(Sn(),Fn())},co=()=>{hn.resume(),sc(),Fn()},po=(l=!1)=>{en()&&hn.isFollowing()&&(!l&&!cr||(pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!0,pr=requestAnimationFrame(()=>{pr=null,Bo=!1,hn.isFollowing()&&Ff(lo(),l?220:140)})))},ac=(l,m,h,x=()=>!0)=>{let A=l.scrollTop,W=m(),U=W-A;if(Xn(),Math.abs(U)<1){An=!0,l.scrollTop=W,Cn=l.scrollTop,An=!1;return}let _=performance.now();An=!0;let D=oe=>1-Math.pow(1-oe,3),ie=oe=>{if(!x()){Xn();return}let Y=m();Y!==W&&(W=Y,U=W-A);let ve=oe-_,Oe=Math.min(ve/h,1),Fe=D(Oe),je=A+U*Fe;l.scrollTop=je,Cn=l.scrollTop,Oe<1?Qt=requestAnimationFrame(ie):(l.scrollTop=W,Cn=l.scrollTop,Qt=null,An=!1)};Qt=requestAnimationFrame(ie)},Ff=(l,m=500)=>{let h=Br(l)-l.scrollTop;if(Math.abs(h)<1){Cn=l.scrollTop;return}if(Math.abs(h)>=q){Xn(),An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1;return}ac(l,()=>Br(l),m,()=>hn.isFollowing())},ic=()=>{let l=lo();An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1,Fn()},lc=l=>{let m=0,h=l;for(;h&&h!==we;)m+=h.offsetTop,h=h.offsetParent;return m},cc=()=>{var W;if(Nr()!=="last-user-turn")return!1;let l=(W=F==null?void 0:F.getMessages())!=null?W:[];if(l.length<2)return!1;let m=[...l].reverse().find(U=>U.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=we.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,lc(x)-xr()),Br(we));return An=!0,we.scrollTop=A,Cn=we.scrollTop,An=!1,Ot()==="follow"&&!Co(we,z)&&hn.pause(),Fn(),!0},dc=l=>{kn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},_s=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),Xn(),yn=null,kn.style.height="0px"},_f=l=>{Lr!==null&&cancelAnimationFrame(Lr),Lr=requestAnimationFrame(()=>{var D;Lr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=lc(h),A=(D=yn==null?void 0:yn.spacerHeight)!=null?D:0,W=we.scrollHeight-A,{targetScrollTop:U,spacerHeight:_}=ug({anchorOffsetTop:x,topOffset:xr(),viewportHeight:we.clientHeight,contentHeight:W});yn={initialSpacerHeight:_,contentHeightAtAnchor:W,spacerHeight:_},dc(_),ac(we,()=>U,220)})},$f=()=>{if(en()){if(!hn.isFollowing()||Co(we,1))return;po(!cr);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,m=mg({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});m!==yn.spacerHeight&&dc(m)}Fn()},jf=l=>{let m=Ot();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(so=!1,ao=!0,_f(l))},Uf=()=>{if(Ot()==="anchor-top"){if(ao){so=!1;return}so=!0,_s(),co(),po(!0)}},qf=l=>{let m=new Map;l.forEach(h=>{let x=G.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Do&&(Ot()!=="anchor-top"||sr())&&Ni()&&(ur+=1,Tn(),Fn(),Qr(ur===1?"1 new message below.":`${ur} new messages below.`))),h.role==="assistant"&&(x!=null&&x.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),G.clear(),m.forEach((h,x)=>{G.set(x,h)})},zf=(l,m,h)=>{var st,Be,Re,ze,Xe,bt;let x=document.createElement("div"),W=(()=>{var De;let H=o.find(We=>We.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),U=(H,De)=>De==null?!1:typeof De=="string"?(H.textContent=De,!0):(H.appendChild(De),!0),_=new Set,D=new Set,ie=o.some(H=>H.renderAskUserQuestion),oe=[],Y=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Fe=[];if(m.forEach(H=>{var mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo;_.add(H.id);let De=ie&&yo(H),We=Oe&&H.variant==="approval"&&!!H.approval,Ye=!De&&H.role==="assistant"&&!H.variant&&ve&&Ul(H);if(!We&&dr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),dr.delete(H.id)}if(!Ye&&kr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),kr.delete(H.id)}let Pt=yo(H)?`:${(mn=H.agentMetadata)!=null&&mn.askUserQuestionAnswered?"a":"u"}:${(_n=H.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=ag(H,ls)+Pt,Kt=De||We||Ye?null:lg(Mr,H.id,_e);if(Kt){x.appendChild(Kt.cloneNode(!0)),yo(H)&&((Ge=H.toolCall)!=null&&Ge.id)&&((It=H.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=H.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let wt=null,an=o.find(et=>!!(H.variant==="reasoning"&&et.renderReasoning||H.variant==="tool"&&et.renderToolCall||!H.variant&&et.renderMessage)),Rn=(Oo=r.layout)==null?void 0:Oo.messages;if(yo(H)&&((Fo=H.agentMetadata)==null?void 0:Fo.askUserQuestionAnswered)===!0){qr.delete(H.id);let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Fa(H)&&(($o=(_o=r.features)==null?void 0:_o.suggestReplies)==null?void 0:$o.enabled)!==!1)return;if(yo(H)&&((hs=(fs=r.features)==null?void 0:fs.askUserQuestion)==null?void 0:hs.enabled)!==!1){let et=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(et&&St.current){let Nt=qr.get(H.id),Bt=Nt!==_e,Vt=null;if(Bt){let{payload:jt,complete:gn}=bo(H),jn=H.id,Ir=()=>{var pn;return(pn=St.current)==null?void 0:pn.getMessages().find(un=>un.id===jn)};Vt=et.renderAskUserQuestion({message:H,payload:jt,complete:gn,resolve:pn=>{var Zn;let un=Ir();un&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(un,pn))},dismiss:()=>{var un,Zn,ho;let pn=Ir();(un=pn==null?void 0:pn.agentMetadata)!=null&&un.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(pn),(ho=St.current)==null||ho.resolveAskUserQuestion(pn,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Bt&&Vt===null&&!$t){((Jt=H.agentMetadata)==null?void 0:Jt.awaitingLocalTool)===!0&&!((jo=H.agentMetadata)!=null&&jo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),oe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}else{((go=H.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=H.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}}else if(We){let et=(Vr=o.find($t=>typeof $t.renderApproval=="function"))!=null?Vr:s,Bt=dr.get(H.id)!==_e,Vt=null;if(Bt&&(et!=null&&et.renderApproval)){let $t=H.id,mt=(jt,gn)=>{var Ir,pn,un;let jn=(Ir=St.current)==null?void 0:Ir.getMessages().find(Zn=>Zn.id===$t);jn!=null&&jn.approval&&(jn.approval.toolType==="webmcp"?(pn=St.current)==null||pn.resolveWebMcpApproval(jn.id,jt):(un=St.current)==null||un.resolveApproval(jn.approval,jt,gn))};Vt=et.renderApproval({message:H,defaultRenderer:()=>vi(H,r),config:r,approve:jt=>mt("approved",jt),deny:jt=>mt("denied",jt)})}if(Bt&&Vt===null){let $t=l.querySelector(`#wrapper-${H.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),dr.delete(H.id),wt=vi(H,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${H.id}`,$t.setAttribute("data-wrapper-id",H.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),x.appendChild($t),Fe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}}else if(an)if(H.variant==="reasoning"&&H.reasoning&&an.renderReasoning){if(!Le)return;wt=an.renderReasoning({message:H,defaultRenderer:()=>Pl(H,r),config:r})}else if(H.variant==="tool"&&H.toolCall&&an.renderToolCall){if(!Pe)return;wt=an.renderToolCall({message:H,defaultRenderer:()=>Rl(H,r),config:r})}else an.renderMessage&&(wt=an.renderMessage({message:H,defaultRenderer:()=>{let et=Ca(H,h,Rn,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r});return H.role!=="user"&&Nl(et,H,r,F),et},config:r}));if(!wt&&Ye){let et=ql(H);if(et){let Nt=kr.get(H.id),Bt=Nt!==_e,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Bt){let mt=jl(et,{config:r,message:H,transform:h});if(mt)if(Vt){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),jt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),x.appendChild(mt),Y.push({messageId:H.id,fingerprint:_e,bubble:$t});return}}}if(!wt)if(H.variant==="reasoning"&&H.reasoning){if(!Le)return;wt=Pl(H,r)}else if(H.variant==="tool"&&H.toolCall){if(!Pe)return;wt=Rl(H,r)}else if(H.variant==="approval"&&H.approval){if(r.approval===!1)return;wt=vi(H,r)}else{let et=(Uo=r.layout)==null?void 0:Uo.messages;et!=null&&et.renderUserMessage&&H.role==="user"?wt=et.renderUserMessage({message:H,config:r,streaming:!!H.streaming}):et!=null&&et.renderAssistantMessage&&H.role==="assistant"?wt=et.renderAssistantMessage({message:H,config:r,streaming:!!H.streaming}):wt=Ca(H,h,et,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r}),H.role!=="user"&&wt&&Nl(wt,H,r,F)}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${H.id}`,Ht.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ht.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Ht.classList.add("persona-w-full"),Ht.appendChild(wt),cg(Mr,H.id,_e,Ht),x.appendChild(Ht)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Jo(Ve.composerOverlay,We)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let H=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){De.push(We);return}De.length>1&&H.push(De),De=[]}),De.length>1&&H.push(De),H.forEach((We,Ye)=>{var mn,_n;let Pt=We.map(Ge=>Array.from(x.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Ye}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Ye}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Rn=(_n=(mn=r.toolCall)==null?void 0:mn.renderGroupedSummary)==null?void 0:_n.call(mn,{messages:We,toolCalls:We.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:an,config:r});U(wt,Rn)||(wt.textContent=an);let Ht=document.createElement("div");Ht.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,Ht),_e.appendChild(Kt),Pt[0].before(_e),Pt.forEach((Ge,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ge),Ht.appendChild($n)})})}dg(Mr,_);let je=m.some(H=>H.role==="assistant"&&H.streaming),qe=m[m.length-1],ut=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(cr&&m.some(H=>H.role==="user")&&!je&&!ut){let H={config:r,streaming:!0,location:"standalone",defaultRenderer:Ps},De=o.find(Ye=>Ye.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(H)),We===null&&((Re=r.loadingIndicator)!=null&&Re.render)&&(We=r.loadingIndicator.render(H)),We===null&&(We=Ps()),We){let Ye=document.createElement("div"),Pt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ye.className=Pt?["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(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.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(Ye),x.appendChild(_e)}}if(!cr&&m.length>0){let H=m[m.length-1],De={config:r,lastMessage:H,messageCount:m.length},We=o.find(Pt=>Pt.renderIdleIndicator),Ye=null;if(We!=null&&We.renderIdleIndicator&&(Ye=We.renderIdleIndicator(De)),Ye===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(Ye=r.loadingIndicator.renderIdle(De)),Ye){let Pt=document.createElement("div"),_e=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.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(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),x.appendChild(Kt)}}if(ei(l,x),oe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of oe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),qr.set(H,De))}if(qr.size>0)for(let H of qr.keys())_.has(H)||qr.delete(H);if(Y.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Y){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),kr.set(H,De))}if(kr.size>0)for(let H of kr.keys())_.has(H)||kr.delete(H);if(Fe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Fe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),dr.set(H,De))}if(dr.size>0)for(let H of dr.keys())_.has(H)||dr.delete(H)},$s=(l,m,h)=>{zf(l,m,h),no()},js=null,Vf=()=>{var h;if(js)return;let l=x=>{let A=x.composedPath();A.includes(ge)||it&&A.includes(it)||_t(!1,"user")};js=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},pc=()=>{var m;if(!js)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",js,!0),js=null};lt.push(()=>pc());let Us=null,Kf=()=>{var h;if(Us)return;let l=x=>{x.key==="Escape"&&(x.isComposing||_t(!1,"user"))};Us=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},uc=()=>{var m;if(!Us)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Us,!0),Us=null};lt.push(()=>uc());let qs=!1,mc=new Set,Gf=()=>{var m,h,x,A;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},ps=()=>{var ut,st,Be,Re;if(!R())return;let l=Ve.peekBanner,m=Ve.peekTextNode;if(!l||!m)return;if(O){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=F==null?void 0:F.getMessages())!=null?ut:[],x;for(let ze=h.length-1;ze>=0;ze--){let Xe=h[ze];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,W=!!x.streaming,U=Gf(),_=si(U),D=_.type!=="none"?ks(_.type,U==null?void 0:U.plugins):null,ie=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,x))===!0,oe=D!==null&&(W||ie);oe&&D&&!mc.has(D.name)&&(li(D,e),mc.add(D.name));let Y=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Be=m.dataset.personaPeekStreamClass)!=null?Be:null;ve&&ve!==Y&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Y&&ve!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),oe?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Oe=oe?ai(A,_.buffer,D,x,W):A;if(oe&&_.placeholder==="skeleton"&&W&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Xe=ya();Xe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Xe),ei(m,ze)}else{let ze=Math.max(0,Oe.length-100),Xe=Oe.length>100?Oe.slice(-100):Oe,bt=Kr(Xe);if(!oe||!D){let H=Oe.length>100?`\u2026${Xe}`:Xe;m.textContent!==H&&(m.textContent=H)}else{let H=bt;(D.wrap==="char"||D.wrap==="word")&&(H=ha(bt,D.wrap,`peek-${x.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=H,D.useCaret&&Xe.length>0){let We=ii(),Ye=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Ye[Ye.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):De.appendChild(We)}ei(m,De),(Re=D.onAfterRender)==null||Re.call(D,{container:m,bubble:l,messageId:x.id,message:x,speed:_.speed,duration:_.duration})}}let qe=cr||qs;l.classList.toggle("persona-pill-peek--visible",qe)};if(R()){let l=Ve.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",x),lt.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{qs||(qs=!0,ps())},h=()=>{qs&&(qs=!1,ps())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),lt.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",m),it.addEventListener("pointerleave",h),lt.push(()=>{it.removeEventListener("pointerenter",m),it.removeEventListener("pointerleave",h)}))}let Jf=l=>{var ve,Oe,Fe,je,qe,ut,st,Be;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Fe=m.expandedSize)!=null?Fe:"anchored",x=(je=m.bottomOffset)!=null?je:"16px",A=m.collapsedMaxWidth,W=(qe=m.expandedMaxWidth)!=null?qe:"880px",U=(ut=m.expandedTopOffset)!=null?ut:"5vh",_=(st=m.modalMaxWidth)!=null?st:"880px",D=(Be=m.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ie="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Y=ge.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",it){let Re=it.style;Re.bottom=x,Re.width=A!=null?A:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=ie,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${x} + ${oe})`,Y.top=U,Y.width=W,Y.maxWidth=ie}},zs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je;if(!N())return;if(R()){let ut=(oe=((ie=(D=r.launcher)==null?void 0:D.composerBar)!=null?ie:{}).expandedSize)!=null?oe:"anchored",st=O?"expanded":"collapsed";ge.dataset.state=st,ge.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Jf(O),Se.style.display=O?"flex":"none",oo(),O?(Vf(),Kf()):(pc(),uc()),ps();return}let l=dn(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,x=(je=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?je:!0,A=m.innerWidth<=h,W=x&&A&&P,U=nr(r).reveal;O?(ge.style.removeProperty("display"),ge.style.display=l?"flex":"",ge.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"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!W?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.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")),Zt?Zt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},_t=(l,m="user")=>{var W,U;if(!N()||O===l)return;let h=O;O=l,zs();let x=(()=>{var Fe,je,qe,ut,st,Be,Re,ze,Xe,bt;let _=(je=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?je:!1,D=(qe=e.ownerDocument.defaultView)!=null?qe:window,ie=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,Y=D.innerWidth<=oe,ve=dn(r)&&ie&&Y,Oe=R()&&((bt=(Xe=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Xe.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return _||ie&&Y&&P||ve||Oe})();if(O&&x){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=Cl(D,(U=(W=r.launcher)==null?void 0:W.zIndex)!=null?U:xn))}on||(on=Al(e.ownerDocument))}else O||(rn==null||rn(),rn=null,on==null||on(),on=null);O&&(Vs(),cc()||(Ot()==="follow"?po(!0):ic()));let A={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",A):!O&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()})},Oi=l=>{me(l?"stop":"send"),B&&(B.disabled=l),Ho.buttons.forEach(m=>{m.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Fi=()=>{K.active||be&&be.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Fi(),200)});let gc=()=>{var h,x,A,W,U,_,D,ie,oe,Y,ve;yr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",br.textContent=(W=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",be.placeholder=(_=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?_:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&oe)&&!(F!=null&&F.isStreaming())&&(pe.textContent=(ve=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"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 l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let No=null,Xf=()=>{No==null&&(No=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(No),No=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=ja(m-x))})},100))};F=new da(r,{onMessagesChanged(l){var A,W;$s(Ze,l,ee),Xf(),is(l),po(!cr),qf(l);let m=[...l].reverse().find(U=>U.role==="user"),h=[...l].reverse().find(U=>U.role==="assistant");l.length===0&&(_s(),so=!0,ao=!1),!cs||Do?(cs=!0,ds=(A=m==null?void 0:m.id)!=null?A:null,ot=(W=h==null?void 0:h.id)!=null?W:null):m&&m.id!==ds?(ds=m.id,jf(m.id)):h&&h.id!==ot&&Uf(),h&&(ot=h.id);let x=K.lastUserMessageId;m&&m.id!==x&&(K.lastUserMessageId=m.id,i.emit("user:message",m)),K.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Pn(l),ps()},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Wt(fn,(A=>{var W,U,_,D,ie,oe;return A==="idle"?(W=m.idleText)!=null?W:nn.idle:A==="connecting"?(U=m.connectingText)!=null?U:nn.connecting:A==="connected"?(_=m.connectedText)!=null?_:nn.connected:A==="error"?(D=m.errorText)!=null?D:nn.error:A==="paused"?(ie=m.pausedText)!=null?ie:nn.paused:A==="resuming"?(oe=m.resumingText)!=null?oe:nn.resuming:nn[A]})(l),m,l)},onStreamingChanged(l){cr=l,Oi(l),F&&$s(Ze,F.getMessages(),ee),l||po(!0),Fn(),Qr(l?"Responding\u2026":"Response complete."),ps()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":zr(),ms();break;case"processing":zr(),th();break;case"speaking":zr(),nh();break;default:l==="idle"&&F.isBargeInActive()?(zr(),ms(),B==null||B.setAttribute("aria-label","End voice session")):(K.active=!1,zr(),rt("system"),ct());break}},onArtifactsState(l){Nn=l,Sr(),Pn()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),St.current=F,lt.push(()=>F.cancel());let _i=null;if(F.onReadAloudChange((l,m)=>{var A;eo=l,to=m,no();let h=l!=null?l:_i;l&&(_i=l);let x=h&&(A=F.getMessages().find(W=>W.id===h))!=null?A:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(_i=null)}),cs=!0,((kd=(Md=r.voiceRecognition)==null?void 0:Md.provider)==null?void 0:kd.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&F.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Q==null||Q.processEvent(l,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let fc=()=>{r.resume&&typeof r.reconnectStream=="function"&&F.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=Kl(l.metadata),L.syncFromMetadata()),(m=l.messages)!=null&&m.length){Do=!0;try{F.hydrateMessages(l.messages)}finally{Do=!1}}(h=l.artifacts)!=null&&h.length&&F.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>fc()):fc();let hc=()=>{var m,h,x;!R()||O||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||_t(!0,"auto")},yc=l=>{var A;if(l.preventDefault(),F.isStreaming()){F.cancel(),Q==null||Q.reset(),Me==null||Me.update();return}let m=be.value.trim(),h=(A=At==null?void 0:At.hasAttachments())!=null?A:!1;if(!m&&!h)return;hc();let x;h&&(x=[],x.push(...At.getContentParts()),m&&x.push(Ka(m))),be.value="",be.style.height="auto",ka(),F.sendMessage(m,{contentParts:x}),h&&At.clearAttachments()},Qf=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},$i={...ti},ji=!1,ka=()=>{$i={...ti}},Yf=()=>F.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),Zf=l=>{if(!be)return;ji=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),ji=!1;let m=be.value.length;be.setSelectionRange(m,m)},bc=()=>{ji||ka()},xc=l=>{if(be){if(Qf()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=be.selectionStart===0&&be.selectionEnd===0,h=sg({direction:l.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:be.value,atStart:m,state:$i});if($i=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Zf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}ka(),l.preventDefault(),pe.click()}}},vc=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(Se)&&(F.cancel(),Q==null||Q.reset(),Me==null||Me.update(),ka(),l.preventDefault(),l.stopImmediatePropagation())},wc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let m=Iw(l.clipboardData);m.length!==0&&(l.preventDefault(),await At.handleFiles(m))},Qn=null,Pr=!1,us=null,pt=null,Cc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,La=(l="user")=>{var W,U,_,D,ie,oe,Y;if(Pr||F.isStreaming())return;let m=Cc();if(!m)return;Qn=new m;let x=(U=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?U:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let A=be.value;Qn.onresult=ve=>{let Oe="",Fe="";for(let qe=0;qe<ve.results.length;qe++){let ut=ve.results[qe],st=ut[0].transcript;ut.isFinal?Oe+=st+" ":Fe=st}let je=A+Oe+Fe;be.value=je,us&&clearTimeout(us),(Oe||Fe)&&(us=window.setTimeout(()=>{let qe=be.value.trim();qe&&Qn&&Pr&&(uo(),be.value="",be.style.height="auto",F.sendMessage(qe,{viaVoice:!0}))},x))},Qn.onerror=ve=>{ve.error!=="no-speech"&&uo()},Qn.onend=()=>{if(Pr){let ve=be.value.trim();ve&&ve!==A.trim()&&(be.value="",be.style.height="auto",F.sendMessage(ve,{viaVoice:!0})),uo()}};try{if(Qn.start(),Pr=!0,K.active=!0,l!=="system"&&(K.manuallyDeactivated=!1),rt(l),ct(),B){let ve=(_=r.voiceRecognition)!=null?_:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(oe=ve.iconSize)!=null?oe:(ie=r.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let Oe=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,je=ve.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let qe=B.querySelector("svg");qe&&qe.setAttribute("stroke",Fe)}je&&(B.style.borderColor=je),B.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Pr){if(Pr=!1,us&&(clearTimeout(us),us=null),Qn){try{Qn.stop()}catch{}Qn=null}if(K.active=!1,rt(l),ct(),B){if(B.classList.remove("persona-voice-recording"),pt){B.style.backgroundColor=pt.backgroundColor,B.style.color=pt.color,B.style.borderColor=pt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",pt.color||"currentColor"),pt=null}B.setAttribute("aria-label","Start voice recognition")}}},eh=(l,m)=>{var st,Be,Re,ze,Xe,bt,H,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",A=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||x||A))return null;let U=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",ie=(ze=m==null?void 0:m.size)!=null?ze:"40px",oe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ie,Y=parseFloat(oe)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:m==null?void 0:m.backgroundColor,Oe=(H=l==null?void 0:l.iconColor)!=null?H:m==null?void 0:m.textColor;_.style.width=oe,_.style.height=oe,_.style.minWidth=oe,_.style.minHeight=oe,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let je=ye(D,Y,Oe||"currentColor",1.5);je?_.appendChild(je):_.textContent="\u{1F3A4}",ve?_.style.backgroundColor=ve:_.style.backgroundColor="",l!=null&&l.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l!=null&&l.borderColor&&(_.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),U.appendChild(_);let qe=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&qe){let Ye=y("div","persona-send-button-tooltip");Ye.textContent=qe,U.appendChild(Ye)}return{micButton:_,micButtonWrapper:U}},Ui=()=>{var m,h,x,A,W;if(!B||pt)return;let l=(m=r.voiceRecognition)!=null?m:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(A=l.iconSize)!=null?A:(x=r.sendButton)==null?void 0:x.size)!=null?W:"40")||24}},qi=(l,m)=>{var W,U,_,D,ie;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let x=(ie=pt==null?void 0:pt.iconSize)!=null?ie:parseFloat((D=(_=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?_:(U=r.sendButton)==null?void 0:U.size)!=null?D:"40")||24,A=ye(l,x,m,1.5);A&&B.appendChild(A)},Pa=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ms=()=>{var A;if(!B)return;Ui();let l=(A=r.voiceRecognition)!=null?A:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Pa(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=B.querySelector("svg");W&&W.setAttribute("stroke",h)}x&&(B.style.borderColor=x),B.setAttribute("aria-label","Stop voice recognition")},th=()=>{var _,D,ie,oe,Y,ve,Oe,Fe;if(!B)return;Ui();let l=(_=r.voiceRecognition)!=null?_:{},m=F.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",x=(oe=(ie=l.processingIconColor)!=null?ie:pt==null?void 0:pt.color)!=null?oe:"",A=(ve=(Y=l.processingBackgroundColor)!=null?Y:pt==null?void 0:pt.backgroundColor)!=null?ve:"",W=(Fe=(Oe=l.processingBorderColor)!=null?Oe:pt==null?void 0:pt.borderColor)!=null?Fe:"";Pa(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=A,B.style.borderColor=W;let U=x||"currentColor";B.style.color=U,qi(h,U),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},nh=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re;if(!B)return;Ui();let l=(ie=r.voiceRecognition)!=null?ie:{},m=F.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(oe=l.speakingIconName)!=null?oe:h,A=(Fe=l.speakingIconColor)!=null?Fe:m==="barge-in"?(ve=(Y=l.recordingIconColor)!=null?Y:pt==null?void 0:pt.color)!=null?ve:"":(Oe=pt==null?void 0:pt.color)!=null?Oe:"",W=(ut=l.speakingBackgroundColor)!=null?ut:m==="barge-in"?(je=l.recordingBackgroundColor)!=null?je:"var(--persona-voice-recording-bg, #ef4444)":(qe=pt==null?void 0:pt.backgroundColor)!=null?qe:"",U=(Re=l.speakingBorderColor)!=null?Re:m==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=pt==null?void 0:pt.borderColor)!=null?Be:"";Pa(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=W,B.style.borderColor=U;let _=A||"currentColor";B.style.color=_,qi(x,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},zr=()=>{var l,m,h;B&&(Pa(),pt&&(B.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",B.style.color=(m=pt.color)!=null?m:"",B.style.borderColor=(h=pt.borderColor)!=null?h:"",qi(pt.iconName,pt.color||"currentColor"),pt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ia=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=F.getVoiceStatus(),x=F.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()});return}F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),K.manuallyDeactivated=!F.isVoiceActive(),ct(),rt("user"),F.isVoiceActive()?ms():zr()});return}if(Pr){let h=be.value.trim();K.manuallyDeactivated=!0,ct(),uo("user"),h&&(be.value="",be.style.height="auto",F.sendMessage(h))}else K.manuallyDeactivated=!1,ct(),La("user")};wr=Ia,B&&(B.addEventListener("click",Ia),lt.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),zr()):uo("system"),B&&B.removeEventListener("click",Ia)}));let rh=i.on("assistant:complete",()=>{Ne&&(K.active||K.manuallyDeactivated||Ne==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!K.active&&!K.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("auto"),F.isVoiceActive()&&ms()}):La("auto"))},600))});lt.push(rh);let oh=i.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});lt.push(oh);let Ac=()=>{_t(!O,"user")},Zt=null,sn=null;if(P&&!R()){let{instance:l,element:m}=Ml({config:r,plugins:o,onToggle:Ac});Zt=l,l||(sn=m)}Zt?e.appendChild(Zt.element):sn&&e.appendChild(sn),zs(),is(),gc(),Oi(F.isStreaming()),cc()||(Ot()==="follow"?po(!0):ic()),Di(),k&&(!P||R()?setTimeout(()=>Fi(),0):O&&setTimeout(()=>Fi(),200));let Vs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe,bt,H,De,We,Ye,Pt,_e;if(R()){zn(),zs();return}let l=dn(r),m=(ie=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ie:!1,h=l||m||((Y=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Y:!1),x=(ve=e.ownerDocument.defaultView)!=null?ve:window,A=(Fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Fe:!0,W=(qe=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?qe:640,U=x.innerWidth<=W,_=A&&U&&P;try{if(_){oo(),es(e,r);return}if($&&($=!1,oo(),es(e,r)),!P&&!l){X.style.height="",X.style.width="";return}if(!m&&!l){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:tr;X.style.width=wt,X.style.maxWidth=wt}if(Wo(),!h){let Kt=x.innerHeight,wt=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Rn=Math.max(200,Kt-wt),Ht=Math.min(640,Rn),mn=Math.max(200,Ht-an);X.style.height=`${mn}px`}}finally{if(zn(),zs(),O&&P){let wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?bt:640),an=(De=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?De:!1,Rn=(Ye=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Ye:!0,Ht=dn(r)&&Rn&&wt,mn=an||Rn&&wt&&P||Ht;if(mn&&!on){let _n=e.getRootNode(),Ge=_n instanceof ShadowRoot?_n.host:e.closest(".persona-host");Ge&&!rn&&(rn=Cl(Ge,(_e=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?_e:xn)),on=Al(e.ownerDocument)}else mn||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Vs();let Sc=(Ld=e.ownerDocument.defaultView)!=null?Ld:window;if(Sc.addEventListener("resize",Vs),lt.push(()=>Sc.removeEventListener("resize",Vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{zn()});l.observe(He),lt.push(()=>l.disconnect())}Cn=we.scrollTop;let Tc=Br(we),sh=()=>{let l=we.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:we.ownerDocument.getSelection()},zi=()=>pg(sh(),we),Ec=()=>{let l=we.scrollTop,m=Br(we),h=m<Tc;if(Tc=m,!en()){Cn=l,Fn();return}let{action:x,nextLastScrollTop:A}=ri({following:hn.isFollowing(),currentScrollTop:l,lastScrollTop:Cn,nearBottom:Co(we,z),userScrollThreshold:w,isAutoScrolling:An||Bo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Cn=A,x==="resume"){zi()||co();return}x==="pause"&&Fs()};if(we.addEventListener("scroll",Ec,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Ec)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{$f()});l.observe(Ze),l.observe(we),lt.push(()=>l.disconnect())}let Mc=()=>{en()&&hn.isFollowing()&&zi()&&Fs()},kc=we.ownerDocument;kc.addEventListener("selectionchange",Mc),lt.push(()=>{kc.removeEventListener("selectionchange",Mc)});let ah=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Lc=l=>{or()&&en()&&hn.isFollowing()&&ah.has(l.key)&&Fs()},Pc=l=>{if(!or()||!en()||!hn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&Fs()};we.addEventListener("keydown",Lc),we.addEventListener("focusin",Pc),lt.push(()=>{we.removeEventListener("keydown",Lc),we.removeEventListener("focusin",Pc)});let Ic=l=>{if(!en())return;let m=oi({following:hn.isFollowing(),deltaY:l.deltaY,nearBottom:Co(we,z),resumeWhenNearBottom:!0});m==="pause"?Fs():m==="resume"&&!zi()&&co()};we.addEventListener("wheel",Ic,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",Ic)),zt.addEventListener("click",()=>{_s(),we.scrollTop=we.scrollHeight,Cn=we.scrollTop,co(),po(!0),Fn()}),lt.push(()=>zt.remove()),lt.push(()=>{Sn(),_s()});let Rc=()=>{Ue&&(Er&&(Ue.removeEventListener("click",Er),Er=null),N()?(Ue.style.display="",Er=()=>{_t(!1,"user")},Ue.addEventListener("click",Er)):Ue.style.display="none")};Rc(),(()=>{let{clearChatButton:l}=Ve;l&&l.addEventListener("click",()=>{F.clearMessages(),Mr.clear(),co(),Jo(Ve.composerOverlay);try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()})})(),Ct&&Ct.addEventListener("submit",yc),be==null||be.addEventListener("keydown",xc),be==null||be.addEventListener("input",bc),be==null||be.addEventListener("paste",wc);let Wc=(Pd=e.ownerDocument)!=null?Pd:document;Wc.addEventListener("keydown",vc,!0);let Hc="persona-attachment-drop-active",Ks=0,Vi=()=>{Ks=0,Se.classList.remove(Hc)},gs=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Bc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks++,Ks===1&&Se.classList.add(Hc))},Dc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks--,Ks<=0&&Vi())},Nc=l=>{!Mi(l.dataTransfer)||!gs()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Oc=l=>{var h;if(!Mi(l.dataTransfer)||!gs())return;l.preventDefault(),l.stopPropagation(),Vi();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&At.handleFiles(m)},mo=!0;Se.addEventListener("dragenter",Bc,mo),Se.addEventListener("dragleave",Dc,mo),e.addEventListener("dragover",Nc,mo),e.addEventListener("drop",Oc,mo);let Ra=e.ownerDocument,Fc=l=>{gs()&&l.preventDefault()},_c=l=>{gs()&&l.preventDefault()};Ra.addEventListener("dragover",Fc),Ra.addEventListener("drop",_c),lt.push(()=>{Ct&&Ct.removeEventListener("submit",yc),be==null||be.removeEventListener("keydown",xc),be==null||be.removeEventListener("input",bc),be==null||be.removeEventListener("paste",wc),Wc.removeEventListener("keydown",vc,!0)}),lt.push(()=>{Se.removeEventListener("dragenter",Bc,mo),Se.removeEventListener("dragleave",Dc,mo),e.removeEventListener("dragover",Nc,mo),e.removeEventListener("drop",Oc,mo),Ra.removeEventListener("dragover",Fc),Ra.removeEventListener("drop",_c),Vi()}),lt.push(()=>{F.cancel()}),Zt?lt.push(()=>{Zt==null||Zt.destroy()}):sn&&lt.push(()=>{sn==null||sn.remove()});let tn={update(l){var jn,Ir,pn,un,Zn,ho,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu;let m=r.toolCall,h=r.messageActions,x=(jn=r.layout)==null?void 0:jn.messages,A=r.colorScheme,W=r.loadingIndicator,U=r.iterationDisplay,_=(Ir=r.features)==null?void 0:Ir.showReasoning,D=(pn=r.features)==null?void 0:pn.showToolCalls,ie=(un=r.features)==null?void 0:un.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Y=(Nd=(ho=r.features)==null?void 0:ho.streamAnimation)==null?void 0:Nd.type;r={...r,...l},oo(),es(e,r),Ci(e,r),Ai(e,r),Sr(),r.colorScheme!==A&&Os();let ve=Si.getForInstance(r.plugins);o.length=0,o.push(...ve),P=(Fd=(Od=r.launcher)==null?void 0:Od.enabled)!=null?Fd:!0,E=($d=(_d=r.launcher)==null?void 0:_d.autoExpand)!=null?$d:!1,Le=(Ud=(jd=r.features)==null?void 0:jd.showReasoning)!=null?Ud:!0,Pe=(zd=(qd=r.features)==null?void 0:qd.showToolCalls)!=null?zd:!0,Ae=(Kd=(Vd=r.features)==null?void 0:Vd.scrollToBottom)!=null?Kd:{};let Oe=Ot();re=(Jd=(Gd=r.features)==null?void 0:Gd.scrollBehavior)!=null?Jd:{},Oe!==Ot()&&(_s(),co()),Yr(),Fn();let Fe=ne;if(ne=(Qd=(Xd=r.features)==null?void 0:Xd.showEventStreamToggle)!=null?Qd:!1,ne&&!Fe){if(V||(fe=new Sa(ae),V=new Aa($e,fe),Q=Q!=null?Q:new Ta,fe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),F.setSSEEventCallback((te,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,te,Tt),Q==null||Q.processEvent(te,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let te=(Zd=(Yd=r.features)==null?void 0:Yd.eventStream)==null?void 0:Zd.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");yt=y("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=ye("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let at=Ve.clearChatButtonWrapper,kt=Ve.closeButtonWrapper,ln=at||kt;ln&&ln.parentNode===ke?ke.insertBefore(yt,ln):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}}else!ne&&Fe&&(lr(),yt&&(yt.remove(),yt=null),V==null||V.clear(),fe==null||fe.destroy(),V=null,fe=null,Q==null||Q.reset(),Q=null);if(((ep=r.launcher)==null?void 0:ep.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((tp=r.launcher)==null?void 0:tp.enabled)===!1&&sn&&(sn.remove(),sn=null),((np=r.launcher)==null?void 0:np.enabled)!==!1&&!Zt&&!sn){let{instance:te,element:Tt}=Ml({config:r,plugins:o,onToggle:Ac});Zt=te,te||(sn=Tt),e.appendChild(Tt)}Zt&&Zt.update(r),ue&&((rp=r.launcher)==null?void 0:rp.title)!==void 0&&(ue.textContent=r.launcher.title),Te&&((op=r.launcher)==null?void 0:op.subtitle)!==void 0&&(Te.textContent=r.launcher.subtitle);let je=(sp=r.layout)==null?void 0:sp.header;if((je==null?void 0:je.layout)!==j&&ke){let te=je?va(r,je,{showClose:N(),onClose:()=>_t(!1,"user")}):Eo({config:r,showClose:N(),onClose:()=>_t(!1,"user")});tt.replaceHeader(te),ke=tt.header.element,M=tt.header.iconHolder,ue=tt.header.headerTitle,Te=tt.header.headerSubtitle,Ue=tt.header.closeButton,j=je==null?void 0:je.layout}else if(je&&(M&&(M.style.display=je.showIcon===!1?"none":""),ue&&(ue.style.display=je.showTitle===!1?"none":""),Te&&(Te.style.display=je.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=je.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let te=je.showClearChat;if(te!==void 0){Ve.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Tt}=Ve;Tt&&!Tt.classList.contains("persona-absolute")&&(te?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((ap=r.layout)==null?void 0:ap.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((ip=r.layout)==null?void 0:ip.showFooter)!==!1;He&&(He.style.display=st?"":"none"),zn(),Fn(),P!==I?P?_t(E,"auto"):(O=!0,zs()):E!==C&&_t(E,"auto"),C=E,I=P,Vs(),Rc();let ze=JSON.stringify(l.toolCall)!==JSON.stringify(m),Xe=JSON.stringify(r.messageActions)!==JSON.stringify(h),bt=JSON.stringify((lp=r.layout)==null?void 0:lp.messages)!==JSON.stringify(x),H=((cp=r.loadingIndicator)==null?void 0:cp.render)!==(W==null?void 0:W.render)||((dp=r.loadingIndicator)==null?void 0:dp.renderIdle)!==(W==null?void 0:W.renderIdle)||((pp=r.loadingIndicator)==null?void 0:pp.showBubble)!==(W==null?void 0:W.showBubble),De=r.iterationDisplay!==U,We=((mp=(up=r.features)==null?void 0:up.showReasoning)!=null?mp:!0)!==(_!=null?_:!0)||((fp=(gp=r.features)==null?void 0:gp.showToolCalls)!=null?fp:!0)!==(D!=null?D:!0)||JSON.stringify((hp=r.features)==null?void 0:hp.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((yp=r.features)==null?void 0:yp.reasoningDisplay)!==JSON.stringify(oe);(ze||Xe||bt||H||De||We)&&F&&(ls++,$s(Ze,F.getMessages(),ee));let Pt=(xp=(bp=r.features)==null?void 0:bp.streamAnimation)==null?void 0:xp.type;if(Pt!==Y&&Pt&&Pt!=="none"){let te=ks(Pt,(wp=(vp=r.features)==null?void 0:vp.streamAnimation)==null?void 0:wp.plugins);te&&li(te,e)}let _e=(Cp=r.launcher)!=null?Cp:{},Kt=(Ap=_e.headerIconHidden)!=null?Ap:!1,wt=(Tp=(Sp=r.layout)==null?void 0:Sp.header)==null?void 0:Tp.showIcon,an=Kt||wt===!1,Rn=_e.headerIconName,Ht=(Ep=_e.headerIconSize)!=null?Ep:"48px";if(M){let te=Se.querySelector(".persona-border-b-persona-divider"),Tt=te==null?void 0:te.querySelector(".persona-flex-col");if(an)M.style.display="none",te&&Tt&&!te.contains(Tt)&&te.insertBefore(Tt,te.firstChild);else{if(M.style.display="",M.style.height=Ht,M.style.width=Ht,te&&Tt&&(te.contains(M)?M.nextSibling!==Tt&&(M.remove(),te.insertBefore(M,Tt)):te.insertBefore(M,Tt)),Rn){let at=parseFloat(Ht)||24,kt=ye(Rn,at*.6,"currentColor",1);kt?M.replaceChildren(kt):M.textContent=(Mp=_e.agentIconText)!=null?Mp:"\u{1F4AC}"}else if(_e.iconUrl){let at=M.querySelector("img");if(at)at.src=_e.iconUrl,at.style.height=Ht,at.style.width=Ht;else{let kt=document.createElement("img");kt.src=_e.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Ht,kt.style.width=Ht,M.replaceChildren(kt)}}else{let at=M.querySelector("svg"),kt=M.querySelector("img");(at||kt)&&M.replaceChildren(),M.textContent=(kp=_e.agentIconText)!=null?kp:"\u{1F4AC}"}let Ut=M.querySelector("img");Ut&&(Ut.style.height=Ht,Ut.style.width=Ht)}}let mn=(Pp=(Lp=r.layout)==null?void 0:Lp.header)==null?void 0:Pp.showTitle,_n=(Rp=(Ip=r.layout)==null?void 0:Ip.header)==null?void 0:Rp.showSubtitle;if(ue&&(ue.style.display=mn===!1?"none":""),Te&&(Te.style.display=_n===!1?"none":""),Ue){((Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(Bp=_e.closeButtonSize)!=null?Bp:"32px",Ut=(Dp=_e.closeButtonPlacement)!=null?Dp:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=Ve,kt=Ut==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==ln)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(at);else{let dt=(Op=(Np=_e.clearChat)==null?void 0:Np.placement)!=null?Op:"inline",cn=(_p=(Fp=_e.clearChat)==null?void 0:Fp.enabled)!=null?_p:!0;at.className=cn&&dt==="inline"?"":"persona-ml-auto";let Wn=Se.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(at)}if(Ue.style.color=_e.closeButtonColor||Mn.actionIconColor,_e.closeButtonBackgroundColor?(Ue.style.backgroundColor=_e.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let dt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${cn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");_e.closeButtonBorderRadius?(Ue.style.borderRadius=_e.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(Ue.style.paddingLeft=_e.closeButtonPaddingX,Ue.style.paddingRight=_e.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),_e.closeButtonPaddingY?(Ue.style.paddingTop=_e.closeButtonPaddingY,Ue.style.paddingBottom=_e.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let bn=($p=_e.closeButtonIconName)!=null?$p:"x",mr=(jp=_e.closeButtonIconText)!=null?jp:"\xD7";Ue.innerHTML="";let En=ye(bn,"28px","currentColor",1);En?Ue.appendChild(En):Ue.textContent=mr;let Yt=(Up=_e.closeButtonTooltipText)!=null?Up:"Close chat",Un=(qp=_e.closeButtonShowTooltip)!=null?qp:!0;if(Ue.setAttribute("aria-label",Yt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ue)return;let qo=Ue.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Wn),Ue.addEventListener("focus",cn),Ue.addEventListener("blur",Wn),at._cleanupTooltip=()=>{Wn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Wn)),Ue&&(Ue.removeEventListener("focus",cn),Ue.removeEventListener("blur",Wn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:It}=Ve;if(Ge){let te=(zp=_e.clearChat)!=null?zp:{},Tt=(Vp=te.enabled)!=null?Vp:!0,Ut=(Gp=(Kp=r.layout)==null?void 0:Kp.header)==null?void 0:Gp.showClearChat,at=Ut!==void 0?Ut:Tt,kt=(Jp=te.placement)!=null?Jp:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:ln}=Ve;!R()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=kt==="top-right",mr=It.classList.contains("persona-absolute");if(!R()&&bn!==mr&&at){if(It.remove(),bn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Se.style.position="relative",Se.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Yt=Se.querySelector(".persona-border-b-persona-divider"),Un=Ve.closeButtonWrapper;Yt&&Un&&Un.parentElement===Yt?Yt.insertBefore(It,Un):Yt&&Yt.appendChild(It)}let En=Ve.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(bn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(at){if(!R()){let dt=(Xp=te.size)!=null?Xp:"32px";Ge.style.height=dt,Ge.style.width=dt}let ln=(Qp=te.iconName)!=null?Qp:"refresh-cw",bn=(Yp=te.iconColor)!=null?Yp:"";Ge.style.color=bn||Mn.actionIconColor,Ge.innerHTML="";let mr=R()?"14px":"20px",En=ye(ln,mr,"currentColor",2);if(En&&Ge.appendChild(En),te.backgroundColor?(Ge.style.backgroundColor=te.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let dt=te.borderWidth||"0px",cn=te.borderColor||"transparent";Ge.style.border=`${dt} solid ${cn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");te.borderRadius?(Ge.style.borderRadius=te.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),te.paddingX?(Ge.style.paddingLeft=te.paddingX,Ge.style.paddingRight=te.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),te.paddingY?(Ge.style.paddingTop=te.paddingY,Ge.style.paddingBottom=te.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(Zp=te.tooltipText)!=null?Zp:"Clear chat",Un=(eu=te.showTooltip)!=null?eu:!0;if(Ge.setAttribute("aria-label",Yt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ge)return;let qo=Ge.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",cn),It.addEventListener("mouseleave",Wn),Ge.addEventListener("focus",cn),Ge.addEventListener("blur",Wn),It._cleanupTooltip=()=>{Wn(),It&&(It.removeEventListener("mouseenter",cn),It.removeEventListener("mouseleave",Wn)),Ge&&(Ge.removeEventListener("focus",cn),Ge.removeEventListener("blur",Wn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],Oo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick];L=Ei({parsers:$n,handlers:Oo,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=rf(r,L,de),F.updateConfig(r),$s(Ze,F.getMessages(),ee),is(),gc(),Oi(F.isStreaming());let Fo=((tu=r.voiceRecognition)==null?void 0:tu.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((ru=(nu=r.voiceRecognition)==null?void 0:nu.provider)==null?void 0:ru.type)==="runtype";if(Fo&&(_o||$o))if(!B||!xe){let te=eh(r.voiceRecognition,r.sendButton);te&&(B=te.micButton,xe=te.micButtonWrapper,ht.insertBefore(xe,vn),B.addEventListener("click",Ia),B.disabled=F.isStreaming())}else{let te=(ou=r.voiceRecognition)!=null?ou:{},Tt=(su=r.sendButton)!=null?su:{},Ut=(au=te.iconName)!=null?au:"mic",at=(iu=Tt.size)!=null?iu:"40px",kt=(lu=te.iconSize)!=null?lu:at,ln=parseFloat(kt)||24;B.style.width=kt,B.style.height=kt,B.style.minWidth=kt,B.style.minHeight=kt;let bn=(du=(cu=te.iconColor)!=null?cu:Tt.textColor)!=null?du:"currentColor";B.innerHTML="";let mr=ye(Ut,ln,bn,2);mr?B.appendChild(mr):B.textContent="\u{1F3A4}";let En=(pu=te.backgroundColor)!=null?pu:Tt.backgroundColor;En?B.style.backgroundColor=En:B.style.backgroundColor="",bn?B.style.color=bn:B.style.color="var(--persona-text, #111827)",te.borderWidth?(B.style.borderWidth=te.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),te.borderColor?B.style.borderColor=te.borderColor:B.style.borderColor="",te.paddingX?(B.style.paddingLeft=te.paddingX,B.style.paddingRight=te.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),te.paddingY?(B.style.paddingTop=te.paddingY,B.style.paddingBottom=te.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Yt=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Un=(uu=te.tooltipText)!=null?uu:"Start voice recognition";if(((mu=te.showTooltip)!=null?mu:!1)&&Un)if(Yt)Yt.textContent=Un,Yt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Un,xe==null||xe.insertBefore(cn,B)}else Yt&&(Yt.style.display="none");xe.style.display="",B.disabled=F.isStreaming()}else B&&xe&&(xe.style.display="none",((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():Pr&&uo());if(((hu=r.attachments)==null?void 0:hu.enabled)===!0)if(!ft||!ce){let te=(yu=r.attachments)!=null?yu:{},Ut=(xu=((bu=r.sendButton)!=null?bu:{}).size)!=null?xu:"40px";Lt||(Lt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,be)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((vu=te.allowedTypes)!=null?vu:Gr).join(","),Je.multiple=((wu=te.maxFiles)!=null?wu:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),Ct.insertBefore(Je,be)),ft=y("div","persona-send-button-wrapper"),ce=y("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",(Cu=te.buttonTooltipText)!=null?Cu:"Attach file");let at=(Au=te.buttonIconName)!=null?Au:"paperclip",kt=Ut,ln=parseFloat(kt)||40,bn=Math.round(ln*.6);ce.style.width=kt,ce.style.height=kt,ce.style.minWidth=kt,ce.style.minHeight=kt,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 mr=ye(at,bn,"currentColor",1.5);mr?ce.appendChild(mr):ce.textContent="\u{1F4CE}",ce.addEventListener("click",Un=>{Un.preventDefault(),Je==null||Je.click()}),ft.appendChild(ce);let En=(Su=te.buttonTooltipText)!=null?Su:"Attach file",Yt=y("div","persona-send-button-tooltip");Yt.textContent=En,ft.appendChild(Yt),Qe.append(ft),!At&&Je&&Lt&&(At=Es.fromConfig(te),At.setPreviewsContainer(Lt),Je.addEventListener("change",async()=>{At&&(Je!=null&&Je.files)&&(await At.handleFileSelect(Je.files),Je.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(of(te.dropOverlay))}else{ft.style.display="";let te=(Tu=r.attachments)!=null?Tu:{};Je&&(Je.accept=((Eu=te.allowedTypes)!=null?Eu:Gr).join(","),Je.multiple=((Mu=te.maxFiles)!=null?Mu:4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else ft&&(ft.style.display="none"),At&&At.clearAttachments(),(ku=Se.querySelector(".persona-attachment-drop-overlay"))==null||ku.remove();let Jt=(Lu=r.sendButton)!=null?Lu:{},jo=(Pu=Jt.useIcon)!=null?Pu:!1,go=(Iu=Jt.iconText)!=null?Iu:"\u2191",fo=Jt.iconName,Vr=(Ru=Jt.tooltipText)!=null?Ru:"Send message",Uo=(Wu=Jt.showTooltip)!=null?Wu:!1,et=(Hu=Jt.size)!=null?Hu:"40px",Nt=Jt.backgroundColor,Bt=Jt.textColor;if(jo){if(pe.style.width=et,pe.style.height=et,pe.style.minWidth=et,pe.style.minHeight=et,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Bt?pe.style.color=Bt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let te=parseFloat(et)||24,Tt=(Bt==null?void 0:Bt.trim())||"currentColor",Ut=ye(fo,te,Tt,2);Ut?pe.appendChild(Ut):pe.textContent=go}else pe.textContent=go;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Du=(Bu=r.copy)==null?void 0:Bu.sendButtonLabel)!=null?Du:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.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",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Bt?pe.style.color=Bt:pe.classList.add("persona-text-white");Jt.borderWidth?(pe.style.borderWidth=Jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Jt.borderColor?pe.style.borderColor=Jt.borderColor:pe.style.borderColor="",Jt.paddingX?(pe.style.paddingLeft=Jt.paddingX,pe.style.paddingRight=Jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Jt.paddingY?(pe.style.paddingTop=Jt.paddingY,pe.style.paddingBottom=Jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=vn==null?void 0:vn.querySelector(".persona-send-button-tooltip");if(Uo&&Vr)if(Vt)Vt.textContent=Vr,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Vr,vn==null||vn.insertBefore(te,pe)}else Vt&&(Vt.style.display="none");let $t=($u=(Nu=r.layout)==null?void 0:Nu.contentMaxWidth)!=null?$u:R()?(_u=(Fu=(Ou=r.launcher)==null?void 0:Ou.composerBar)==null?void 0:Fu.contentMaxWidth)!=null?_u:"720px":void 0;$t?(Ze.style.maxWidth=$t,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(ju=r.statusIndicator)!=null?ju:{},jt=(Uu=mt.visible)!=null?Uu:!0;if(fn.style.display=jt?"":"none",F){let te=F.getStatus();Wt(fn,(Ut=>{var at,kt,ln,bn;return Ut==="idle"?(at=mt.idleText)!=null?at:nn.idle:Ut==="connecting"?(kt=mt.connectingText)!=null?kt:nn.connecting:Ut==="connected"?(ln=mt.connectedText)!=null?ln:nn.connected:Ut==="error"?(bn=mt.errorText)!=null?bn:nn.error:nn[Ut]})(te),mt,te)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(gn)},open(){N()&&_t(!0,"api")},close(){N()&&_t(!1,"api")},toggle(){N()&&_t(!O,"api")},reconnect(){F.reconnectNow()},clearChat(){wn=!1,F.clearMessages(),Mr.clear(),co();try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let m=c.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()},setMessage(l){return!be||F.isStreaming()?!1:(!O&&N()&&_t(!0,"system"),be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let m=(l==null?void 0:l.trim())||be.value.trim();return m?(!O&&N()&&_t(!0,"system"),be.value="",be.style.height="auto",F.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return F.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(F.isVoiceActive()||(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("user"),F.isVoiceActive()&&ms()})),!0):Pr?!0:Cc()?(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),La("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()}),!0):!1:Pr?(K.manuallyDeactivated=!0,ct(),uo("user"),!0):!1},injectMessage(l){return!O&&N()&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!O&&N()&&_t(!0,"system");let m=F.injectAssistantMessage(l);return Z&&(Z=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),m},injectUserMessage(l){return!O&&N()&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!O&&N()&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!O&&N()&&_t(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!O&&N()&&_t(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!O&&N()&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,m){return F.connectStream(l,m)},__pushEventStreamEvent(l){V&&(Q==null||Q.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ne||!V||Fr()},hideEventStream(){J&&lr()},isEventStreamVisible(){return J},showArtifacts(){rr(r)&&(wn=!1,Sr(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){rr(r)&&(wn=!0,Sr())},upsertArtifact(l){return rr(r)?(wn=!1,F.upsertArtifact(l)):null},selectArtifact(l){rr(r)&&F.selectArtifact(l)},clearArtifacts(){rr(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return P&&!O&&!R()||!be?!1:(be.focus(),!0)},async resolveApproval(l,m,h){let A=F.getMessages().find(W=>{var U;return W.variant==="approval"&&((U=W.approval)==null?void 0:U.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){F.resolveWebMcpApproval(A.id,m);return}return F.resolveApproval(A.approval,m,h)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return N()&&O},isVoiceActive(){return K.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:N()&&O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()}},showCSATFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=zl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitCSATFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Vl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitNPSFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return F.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return F.submitNPSFeedback(l,m)},destroy(){No!=null&&(clearInterval(No),No=null),lt.forEach(l=>l()),ge.remove(),it==null||it.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Er&&Ue.removeEventListener("click",Er)}};if((((Id=n==null?void 0:n.debugTools)!=null?Id:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,lt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),lt.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let _=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.showEventStream()},D=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.showArtifacts()},x=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.hideArtifacts()},A=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},W=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},U=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",U),lt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",U)})}let Yn=Rw(r.persistState);if(Yn&&N()){let l=Ww(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,x=`${Yn.keyPrefix}widget-voice-mode`;if(l){let A=((Rd=Yn.persist)==null?void 0:Rd.openState)&&l.getItem(m)==="true",W=((Wd=Yn.persist)==null?void 0:Wd.voiceState)&&l.getItem(h)==="true",U=((Hd=Yn.persist)==null?void 0:Hd.voiceState)&&l.getItem(x)==="true";if(A&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(W||U)tn.startVoiceRecognition();else if((_=Yn.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Bd=Yn.persist)!=null&&Bd.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(Dd=Yn.persist)!=null&&Dd.voiceState&&(i.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(x,_.viaVoice?"true":"false")})),Yn.clearOnChatClear){let _=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},D=()=>_();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return f&&N()&&setTimeout(()=>{tn.open()},0),ps(),Ma||Gu().then(()=>{F&&(ls++,Mr.clear(),$s(Ze,F.getMessages(),ee))}).catch(()=>{}),tn};var Hw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Bw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Dw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},sf=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Yl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},af=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Yl(e)},Jl=e=>{e.style.transition=""},Xl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Ql=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ki=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ow=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Fw=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},lf=(e,t,n,r,o,s,a)=>{var b,v,S,T,L,P;let i=nr(s),d=i.reveal==="push";Ow(e,t,n,r,d),Fw(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",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=e.ownerDocument.defaultView,p=(v=(b=s==null?void 0:s.launcher)==null?void 0:b.mobileFullscreen)!=null?v:!0,u=(T=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?T:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xl(t),Jl(r),af(r),Ql(n),ki(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",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((P=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?P:xn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),af(r),Bw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xl(t),Jl(r),Ql(n),ki(o,r);let E=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":k;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Jl(r),Yl(r),ki(o,r);let E=Hw(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-E:0:a?0:-E;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${k+E}px`,t.style.transition=C,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xl(t),Yl(r),Ql(n),ki(o,r);let E=i.reveal==="emerge";E?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${k}`,r.style.width=k,r.style.maxWidth=k,r.style.minWidth=k,r.style.minHeight="0",Dw(r,i.maxHeight),r.style.overflow=E||I?"hidden":"visible",r.style.transition=C,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},_w=(e,t)=>{let n=e.ownerDocument.createElement("div");return sf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){sf(n,r)},destroy(){n.remove()}}},$w=(e,t)=>{var P,E,k,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.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=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(E=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||E?(C=(k=t==null?void 0:t.launcher)==null?void 0:k.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},b=()=>{g(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{lf(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,S=()=>{lf(a,i,d,c,p,t,u),b(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Nw(a,nr(t)))},T=a.ownerDocument.defaultView,L=()=>{S()};return T==null||T.addEventListener("resize",L),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:p,shell:a,syncWidgetState(I){let j=I.launcherEnabled?I.open:!0;u!==j&&(u=j,S())},updateConfig(I){var j,$;t=I,(($=(j=t==null?void 0:t.launcher)==null?void 0:j.enabled)!=null?$:!0)===!1&&(u=!0),S()},destroy(){T==null||T.removeEventListener("resize",L),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Li=(e,t)=>dn(t)?$w(e,t):_w(e,t);var Zl={},jw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Uw=()=>{try{if(typeof Zl!="undefined"&&Zl.url)return new URL("../widget.css",Zl.url).href}catch{}return null},cf=(e,t)=>{let n=Uw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},df=e=>{var S;let t=jw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Li(t,o),a,i=[],d=(T,L)=>{var C,I;let E=!((I=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?I:!0)||dn(L),k=r.createElement("div");if(k.setAttribute("data-persona-root","true"),E&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),n){let j=T.attachShadow({mode:"open"});j.appendChild(k),cf(j,r)}else T.appendChild(k),cf(T,r);return t.id&&k.setAttribute("data-persona-instance",t.id),k},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let T=d(s.host,o);a=Gl(T,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(S=e.onChatReady)==null||S.call(e);let g=T=>{f(),s.destroy(),s=Li(t,T),o=T,u()},b={update(T){var I,j,$,R,N,O;let L={...o,...T,launcher:{...(I=o==null?void 0:o.launcher)!=null?I:{},...(j=T==null?void 0:T.launcher)!=null?j:{},dock:{...(R=($=o==null?void 0:o.launcher)==null?void 0:$.dock)!=null?R:{},...(O=(N=T==null?void 0:T.launcher)==null?void 0:N.dock)!=null?O:{}}}},P=dn(o),E=dn(L),k=To(o),C=To(L);if(P!==E||k!==C){g(L);return}o=L,s.updateConfig(o),a.update(T),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(b,{get(T,L,P){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,P);let E=a[L];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var ff=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qw=new Set(["button","a","input","select","textarea","details","summary"]),zw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ec=/\b(product|card|item|listing|result)\b/i,nc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vw=3e3,Kw=100;function hf(e){let t=typeof e.className=="string"?e.className:"";if(ec.test(t)||e.id&&ec.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ec.test(r.value))return!0}return!1}function yf(e){var t;return nc.test(((t=e.textContent)!=null?t:"").trim())}function bf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Gw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function pf(e){let t=e.match(nc);return t?t[0]:null}function uf(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Jw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Xw="commerce-card",Qw="result-card";function mf(e){return!hf(e)||!yf(e)||!bf(e)&&!Gw(e)?0:5200}function gf(e){var r;return!hf(e)||yf(e)||!bf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xf=[{id:Xw,scoreElement(e){return mf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||nc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(mf(e)===0)return null;let{title:n,href:r}=uf(e),o=(p=(c=pf(((d=e.textContent)!=null?d:"").trim()))!=null?c:pf(t.text))!=null?p:"",s=Jw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
- `)}},{id:Qw,scoreElement(e){return gf(e)},formatSummary(e,t){if(gf(e)===0)return null;let{title:n,href:r}=uf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
- `)}}];function Yw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Zw(e){var p,u,f,g,b,v,S,T,L,P,E,k,C;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(b=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?b:".persona-host",o=(S=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?S:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(P=t.root)!=null?P:e.root,i=(E=t.mode)!=null?E:"structured",d=(k=t.maxCandidates)!=null?k:Math.max(500,n*10),c=(C=e.rules)!=null?C:xf;return i==="simple"&&e.rules&&e.rules.length>0?(Yw(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function tc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var eC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function tC(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||qw.has(t)||n&&zw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function nC(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function wf(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${tc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of eC){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${tc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>tc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function rC(e){return e==="static"?Kw:Vw}function Cf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:wf(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:tC(e),attributes:nC(e)}}function oC(e,t,n,r){let o=rC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function sC(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function aC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(ff.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!vf(c)){i=a.nextNode();continue}let u=Cf(c,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(S=>S==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:b,formattingRule:v}=oC(c,u,e.rules,n);o.push({el:c,domIndex:s,enriched:u,score:b,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;sC(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function iC(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(ff.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!vf(d)){s=o.nextNode();continue}let p=Cf(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function lC(e={}){var r;let t=Zw(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?iC(t,n):aC(t,n):[]}var Pi=100;function cC(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
114
- ${a.map(i=>`- ${i.split(`
133
+ ${st?"background: transparent !important;":""}
134
+ `}if(!x&&!l){let Rt="max-height: -moz-available !important; max-height: stretch !important;",Yt=g?"":"padding-top: 1.25em !important;",la=g?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Ee.style.cssText+=Rt+Yt+la}Ro()};Gs(),br(e,o),Ds(e,o),Os(e,o),Hr=()=>{Gs(),br(e,o),Ds(e,o),Os(e,o),$s?e.style.setProperty("--persona-artifact-welded-outer-radius",$s):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",Wc)}),Ve.push(()=>{Rr!==null&&clearTimeout(Rr)});let An=null,Sn=null;Ve.push(()=>{An?.(),An=null,Sn?.(),Sn=null}),Wr&&Ve.push(()=>{Wr?.disconnect(),Wr=null}),Ve.push(()=>{Or?.(),Or=null,Mi(),wt&&(wt.remove(),wt=null),Qe?.element.style.removeProperty("width"),Qe?.element.style.removeProperty("maxWidth")}),Y&&Ve.push(()=>{Le!==null&&(cancelAnimationFrame(Le),Le=null),Ne?.destroy(),Ne=null,Oe?.destroy(),Oe=null,fe=null});let Ao=null,Dc=()=>{Ao&&(Ao(),Ao=null),o.colorScheme==="auto"&&(Ao=vs(()=>{br(e,o)}))};Dc(),Ve.push(()=>{Ao&&(Ao(),Ao=null)}),Ve.push(a);let Js=o.features?.streamAnimation;if(Js?.type&&Js.type!=="none"){let l=wr(Js.type,Js.plugins);l&&(Ja(l,e),Ve.push(()=>bu(e)))}let Xs=$u(Ct),So=null,N,ki=l=>{if(!N)return;let g=l??N.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?cl(g):null;y?Xs.render(y,N,O,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?Xs.render([],N,O,g):Xs.render(o.suggestionChips,N,O,g,o.suggestionChipsConfig)},hn=!1,To=cu(),nr=new Map,Eo=new Map,Kn=new Map,Li=0,qf=Fn()!==null,en=Ua(),ln=0,Gn=null,cn=!1,Qs=!1,Jn=0,yn=null,Mo=null,Pi=!1,Ys=!1,Ri=null,Nr=!0,Ii=!1,Wi=null,Vf=4,Zs=24,Kf=80,Hi=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Oc=o.voiceRecognition?.autoResume??!1,Bn=l=>{i.emit("voice:state",{active:Je.active,source:l,timestamp:Date.now()})},bn=()=>{C(l=>({...l,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},Gf=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=ic(c.voiceState),g=!!l.active,y=Number(l.timestamp??0);Je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<Ex&&setTimeout(()=>{Je.active||(Je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Je.active=N.isVoiceActive(),Bn("restore"),N.isVoiceActive()&&ir()}):oa("restore"))},1e3)},Jf=()=>N?tf(N.getMessages()).filter(l=>!l.__skipPersist):[],ea=null,Nc=(l,g)=>{typeof console<"u"&&console.error(l,g)},Bi=(l,g)=>{let y=()=>{try{let X=l();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(F=>{Nc(g,F)})}catch(X){return Nc(g,X),null}},x=ea,S=x?x.then(()=>y()??void 0):y();if(!S)return;let k=S.finally(()=>{ea===k&&(ea=null)});ea=k};function Di(l){if(!d?.save)return;let y={messages:l?tf(l):N?Jf():[],metadata:c,artifacts:gn.artifacts,selectedArtifactId:gn.selectedId};Bi(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let or=null,Fc=()=>Ee.querySelector("#persona-scroll-container")||le,Fr=()=>{or!==null&&(cancelAnimationFrame(or),or=null),cn=!1},_c=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Qs=!1,Fr()},Xf=()=>hn&&Ni()&&(Qt()!=="anchor-top"||xc()),Oi=()=>{let l=vo()||"Jump to latest",g=Xf();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Jn>0?(xo.textContent=String(Jn),xo.style.display="",It.setAttribute("aria-label",`${l} (${Jn} new)`)):(xo.textContent="",xo.style.display="none",It.setAttribute("aria-label",g?`${l} (response streaming below)`:l))},$c=()=>{Jn!==0&&(Jn=0,Oi())},Ni=()=>Un()?!en.isFollowing():!fo(le,Zs),tn=()=>{if(!Fs()||we){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==ge&&ge.appendChild(It),Yo();let g=Rn(le)>0&&Ni();g?Oi():$c(),It.style.display=g?"":"none"},_r=()=>{en.pause()&&(_c(),tn())},Xn=()=>{en.resume(),$c(),tn()},Qn=(l=!1)=>{Un()&&en.isFollowing()&&(!l&&!hn||(Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Qs=!0,Gn=requestAnimationFrame(()=>{Gn=null,Qs=!1,en.isFollowing()&&Qf(Fc(),l?220:140)})))},jc=(l,g,y,x=()=>!0)=>{let S=l.scrollTop,k=g(),X=k-S;if(Fr(),Math.abs(X)<1){cn=!0,l.scrollTop=k,ln=l.scrollTop,cn=!1;return}let F=performance.now();cn=!0;let G=de=>1-Math.pow(1-de,3),ae=de=>{if(!x()){Fr();return}let ne=g();ne!==k&&(k=ne,X=k-S);let Ce=de-F,Ke=Math.min(Ce/y,1),bt=G(Ke),it=S+X*bt;l.scrollTop=it,ln=l.scrollTop,Ke<1?or=requestAnimationFrame(ae):(l.scrollTop=k,ln=l.scrollTop,or=null,cn=!1)};or=requestAnimationFrame(ae)},Qf=(l,g=500)=>{let y=Rn(l)-l.scrollTop;if(Math.abs(y)<1){ln=l.scrollTop;return}if(Math.abs(y)>=Kf){Fr(),cn=!0,l.scrollTop=Rn(l),ln=l.scrollTop,cn=!1;return}jc(l,()=>Rn(l),g,()=>en.isFollowing())},Uc=()=>{let l=Fc();cn=!0,l.scrollTop=Rn(l),ln=l.scrollTop,cn=!1,tn()},zc=l=>{let g=0,y=l;for(;y&&y!==le;)g+=y.offsetTop,y=y.offsetParent;return g},qc=()=>{if(Ff()!=="last-user-turn")return!1;let l=N?.getMessages()??[];if(l.length<2)return!1;let g=[...l].reverse().find(k=>k.role==="user");if(!g)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${y}"]`);if(!x)return!1;let S=Math.min(Math.max(0,zc(x)-bc()),Rn(le));return cn=!0,le.scrollTop=S,ln=le.scrollTop,cn=!1,Qt()==="follow"&&!fo(le,Zs)&&en.pause(),tn(),!0},Vc=l=>{zn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},$r=()=>{Mo!==null&&(cancelAnimationFrame(Mo),Mo=null),Fr(),yn=null,zn.style.height="0px"},Yf=l=>{Mo!==null&&cancelAnimationFrame(Mo),Mo=requestAnimationFrame(()=>{Mo=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=le.querySelector(`[data-message-id="${g}"]`);if(!y)return;let x=zc(y),S=yn?.spacerHeight??0,k=le.scrollHeight-S,{targetScrollTop:X,spacerHeight:F}=gu({anchorOffsetTop:x,topOffset:bc(),viewportHeight:le.clientHeight,contentHeight:k});yn={initialSpacerHeight:F,contentHeightAtAnchor:k,spacerHeight:F},Vc(F),jc(le,()=>X,220)})},Zf=()=>{if(Un()){if(!en.isFollowing()||fo(le,1))return;Qn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let l=le.scrollHeight-yn.spacerHeight,g=mu({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});g!==yn.spacerHeight&&Vc(g)}tn()},eg=l=>{let g=Qt();g==="follow"?(Xn(),Qn(!0)):g==="anchor-top"&&(Nr=!1,Ii=!0,Yf(l))},tg=()=>{if(Qt()==="anchor-top"){if(Ii){Nr=!1;return}Nr=!0,$r(),Xn(),Qn(!0)}},ng=l=>{let g=new Map;l.forEach(y=>{let x=Hi.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!x&&y.role==="assistant"&&(i.emit("assistant:message",y),!Ys&&(Qt()!=="anchor-top"||xc())&&Ni()&&(Jn+=1,Oi(),tn(),wc(Jn===1?"1 new message below.":`${Jn} new messages below.`))),y.role==="assistant"&&x?.streaming&&y.streaming===!1&&i.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(x?y.approval.status!=="pending"&&i.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):i.emit("approval:requested",{approval:y.approval,message:y}))}),Hi.clear(),g.forEach((y,x)=>{Hi.set(x,y)})},og=(l,g,y)=>{let x=document.createElement("div"),k=(()=>{let I=s.find(_e=>_e.renderLoadingIndicator);if(I?.renderLoadingIndicator)return I.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(I,_e)=>_e==null?!1:typeof _e=="string"?(I.textContent=_e,!0):(I.appendChild(_e),!0),F=new Set,G=new Set,ae=s.some(I=>I.renderAskUserQuestion),de=[],ne=[],Ce=o.enableComponentStreaming!==!1,Ke=o.approval!==!1,bt=[];if(g.forEach(I=>{F.add(I.id);let _e=ae&&to(I),Se=Ke&&I.variant==="approval"&&!!I.approval,$e=!_e&&I.role==="assistant"&&!I.variant&&Ce&&di(I);!Se&&Kn.has(I.id)&&(l.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Kn.delete(I.id)),!$e&&Eo.has(I.id)&&(l.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Eo.delete(I.id));let Mt=to(I)?`:${I.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${I.agentMetadata?.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=lu(I,Li)+Mt,St=_e||Se||$e?null:du(To,I.id,pt);if(St){x.appendChild(St.cloneNode(!0)),to(I)&&I.toolCall?.id&&I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(G.add(I.toolCall.id),is(I,o,Ie.composerOverlay));return}let vt=null,$t=s.find(ue=>!!(I.variant==="reasoning"&&ue.renderReasoning||I.variant==="tool"&&ue.renderToolCall||!I.variant&&ue.renderMessage)),Po=o.layout?.messages;if(to(I)&&I.agentMetadata?.askUserQuestionAnswered===!0){nr.delete(I.id),l.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime");return}if(va(I)&&o.features?.suggestReplies?.enabled!==!1)return;if(to(I)&&o.features?.askUserQuestion?.enabled!==!1){let ue=s.find(Tt=>typeof Tt.renderAskUserQuestion=="function");if(ue&&gt.current){let Tt=nr.get(I.id),Vt=Tt!==pt,Ot=null;if(Vt){let{payload:Ye,complete:Pt}=no(I),Be=I.id,Ze=()=>gt.current?.getMessages().find(nn=>nn.id===Be);Ot=ue.renderAskUserQuestion({message:I,payload:Ye,complete:Pt,resolve:nn=>{let Ro=Ze();Ro&&gt.current?.resolveAskUserQuestion(Ro,nn)},dismiss:()=>{let nn=Ze();nn?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(nn),gt.current?.resolveAskUserQuestion(nn,"(dismissed)"))},config:o})}let st=Tt!=null;if(Vt&&Ot===null&&!st){I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(G.add(I.toolCall.id),is(I,o,Ie.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"),x.appendChild(qe),de.push({messageId:I.id,fingerprint:pt,bubble:Ot});return}else{I.agentMetadata?.awaitingLocalTool===!0&&!I.agentMetadata?.askUserQuestionAnswered&&(G.add(I.toolCall.id),is(I,o,Ie.composerOverlay));return}}else if(Se){let ue=s.find(st=>typeof st.renderApproval=="function")??r,Vt=Kn.get(I.id)!==pt,Ot=null;if(Vt&&ue?.renderApproval){let st=I.id,qe=(Ye,Pt)=>{let Be=gt.current?.getMessages().find(Ze=>Ze.id===st);Be?.approval&&(Be.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(Be.id,Ye):gt.current?.resolveApproval(Be.approval,Ye,Pt))};Ot=ue.renderApproval({message:I,defaultRenderer:()=>si(I,o),config:o,approve:Ye=>qe("approved",Ye),deny:Ye=>qe("denied",Ye)})}if(Vt&&Ot===null)l.querySelector(`#wrapper-${I.id}`)?.removeAttribute("data-preserve-runtime"),Kn.delete(I.id),vt=si(I,o);else{let st=document.createElement("div");st.className="persona-flex",st.id=`wrapper-${I.id}`,st.setAttribute("data-wrapper-id",I.id),st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),x.appendChild(st),bt.push({messageId:I.id,fingerprint:pt,bubble:Ot});return}}else if($t)if(I.variant==="reasoning"&&I.reasoning&&$t.renderReasoning){if(!re)return;vt=$t.renderReasoning({message:I,defaultRenderer:()=>jl(I,o),config:o})}else if(I.variant==="tool"&&I.toolCall&&$t.renderToolCall){if(!be)return;vt=$t.renderToolCall({message:I,defaultRenderer:()=>zl(I,o),config:o})}else $t.renderMessage&&(vt=$t.renderMessage({message:I,defaultRenderer:()=>{let ue=Is(I,y,Po,o.messageActions,ie,{loadingIndicatorRenderer:k,widgetConfig:o});return I.role!=="user"&&Yl(ue,I,o,N),ue},config:o}));if(!vt&&$e){let ue=rc(I);if(ue){let Tt=Eo.get(I.id),Vt=Tt!==pt,Ot=o.wrapComponentDirectiveInBubble!==!1&&Pn.getOptions(ue.component)?.bubbleChrome!==!1,st=null;if(Vt){let qe=oc(ue,{config:o,message:I,transform:y});if(qe&&ue.component==="PersonaArtifactInline"){let Ye=qe.hasAttribute("data-artifact-inline")?qe:qe.querySelector("[data-artifact-inline]"),Pt=Ye?.getAttribute("data-artifact-inline")??"",Be=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Pt):Pt,Ze=Pt?l.querySelector(`#wrapper-${I.id}`)?.querySelector(`[data-artifact-inline="${Be}"]`)??null:null;Ye&&Ze&&Ze!==Ye&&ou(Ze)&&(Ye===qe?qe=Ze:Ye.replaceWith(Ze))}if(qe)if(Ot){let Ye=document.createElement("div");if(Ye.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(" "),Ye.id=`bubble-${I.id}`,Ye.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let Pt=document.createElement("div");Pt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Pt.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ye.appendChild(Pt)}Ye.appendChild(qe),st=Ye}else{let Ye=document.createElement("div");if(Ye.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ye.id=`bubble-${I.id}`,Ye.setAttribute("data-message-id",I.id),Ye.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let Pt=document.createElement("div");Pt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Pt.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Ye.appendChild(Pt)}Ye.appendChild(qe),st=Ye}}if(st||Tt!=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"),Ot||qe.classList.add("persona-w-full"),x.appendChild(qe),ne.push({messageId:I.id,fingerprint:pt,bubble:st});return}}}if(!vt)if(I.variant==="reasoning"&&I.reasoning){if(!re)return;vt=jl(I,o)}else if(I.variant==="tool"&&I.toolCall){if(!be)return;vt=zl(I,o)}else if(I.variant==="approval"&&I.approval){if(o.approval===!1)return;vt=si(I,o)}else{let ue=o.layout?.messages;ue?.renderUserMessage&&I.role==="user"?vt=ue.renderUserMessage({message:I,config:o,streaming:!!I.streaming}):ue?.renderAssistantMessage&&I.role==="assistant"?vt=ue.renderAssistantMessage({message:I,config:o,streaming:!!I.streaming}):vt=Is(I,y,ue,o.messageActions,ie,{loadingIndicatorRenderer:k,widgetConfig:o}),I.role!=="user"&&vt&&Yl(vt,I,o,N)}let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-${I.id}`,ut.setAttribute("data-wrapper-id",I.id),I.role==="user"&&ut.classList.add("persona-justify-end"),vt?.getAttribute("data-persona-component-directive")==="true"&&ut.classList.add("persona-w-full"),ut.appendChild(vt),pu(To,I.id,pt,ut),x.appendChild(ut)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(_e=>{let Se=_e.getAttribute("data-persona-ask-sheet-for");Se&&!G.has(Se)&&$o(Ie.composerOverlay,Se)}),o.features?.toolCallDisplay?.grouped){let I=[],_e=[];g.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&be){_e.push(Se);return}Se.variant==="reasoning"&&!re||(_e.length>1&&I.push(_e),_e=[])}),_e.length>1&&I.push(_e),I.forEach((Se,$e)=>{let Mt=Se.map(Tt=>Array.from(x.children).find(Vt=>Vt instanceof HTMLElement&&Vt.getAttribute("data-wrapper-id")===Tt.id)).filter(Tt=>!!Tt);if(Mt.length<2)return;let pt=document.createElement("div");pt.className="persona-flex",pt.id=`wrapper-tool-group-${$e}-${Se[0].id}`,pt.setAttribute("data-wrapper-id",`tool-group-${$e}-${Se[0].id}`);let St=document.createElement("div");St.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",St.setAttribute("data-persona-tool-group","true");let vt=document.createElement("div");vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let $t=`Called ${Se.length} tools`,Po=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(Tt=>Tt.toolCall).filter(Tt=>!!Tt),defaultSummary:$t,config:o});X(vt,Po)||(vt.textContent=$t);let ut=document.createElement("div");ut.className="persona-tool-group-stack persona-flex persona-flex-col";let ue=o.features?.toolCallDisplay?.groupedMode==="summary";St.appendChild(vt),ue||St.appendChild(ut),pt.appendChild(St),Mt[0].before(pt),Mt.forEach((Tt,Vt)=>{if(ue){Tt.remove();return}let Ot=document.createElement("div");Ot.className="persona-tool-group-item persona-relative",Ot.setAttribute("data-persona-tool-group-item","true"),Vt<Mt.length-1&&Ot.setAttribute("data-persona-tool-group-connector","true"),Ot.appendChild(Tt),ut.appendChild(Ot)})})}uu(To,F);let it=g.some(I=>I.role==="assistant"&&I.streaming),qt=g[g.length-1],Dt=qt?.role==="assistant"&&!qt.streaming&&qt.variant!=="approval";if(hn&&g.some(I=>I.role==="user")&&!it&&!Dt){let I={config:o,streaming:!0,location:"standalone",defaultRenderer:Sr},_e=s.find($e=>$e.renderLoadingIndicator),Se=null;if(_e?.renderLoadingIndicator&&(Se=_e.renderLoadingIndicator(I)),Se===null&&o.loadingIndicator?.render&&(Se=o.loadingIndicator.render(I)),Se===null&&(Se=Sr()),Se){let $e=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;$e.className=Mt?["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(Se);let pt=document.createElement("div");pt.className="persona-flex",pt.id="wrapper-typing-indicator",pt.setAttribute("data-wrapper-id","typing-indicator"),pt.appendChild($e),x.appendChild(pt)}}if(!hn&&g.length>0){let I=g[g.length-1],_e={config:o,lastMessage:I,messageCount:g.length},Se=s.find(Mt=>Mt.renderIdleIndicator),$e=null;if(Se?.renderIdleIndicator&&($e=Se.renderIdleIndicator(_e)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(_e)),$e){let Mt=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;Mt.className=pt?["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(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild($e);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-idle-indicator",St.setAttribute("data-wrapper-id","idle-indicator"),St.appendChild(Mt),x.appendChild(St)}}if($a(l,x),de.length>0)for(let{messageId:I,fingerprint:_e,bubble:Se}of de){let $e=l.querySelector(`#wrapper-${I}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),nr.set(I,_e))}if(nr.size>0)for(let I of nr.keys())F.has(I)||nr.delete(I);if(ne.length>0)for(let{messageId:I,fingerprint:_e,bubble:Se}of ne){let $e=l.querySelector(`#wrapper-${I}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),Eo.set(I,_e))}if(Eo.size>0)for(let I of Eo.keys())F.has(I)||Eo.delete(I);if(bt.length>0)for(let{messageId:I,fingerprint:_e,bubble:Se}of bt){let $e=l.querySelector(`#wrapper-${I}`);$e&&Se!==null&&($e.replaceChildren(Se),$e.setAttribute("data-bubble-fp",_e),Kn.set(I,_e))}if(Kn.size>0)for(let I of Kn.keys())F.has(I)||Kn.delete(I)},jr=(l,g,y)=>{og(l,g,y),Pc()},Ur=null,rg=()=>{if(Ur)return;let l=y=>{let x=y.composedPath();x.includes(Ee)||lt&&x.includes(lt)||ht(!1,"user")};Ur=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},Kc=()=>{if(!Ur)return;(e.ownerDocument??document).removeEventListener("pointerdown",Ur,!0),Ur=null};Ve.push(()=>Kc());let zr=null,sg=()=>{if(zr)return;let l=y=>{y.key==="Escape"&&(y.isComposing||ht(!1,"user"))};zr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},Gc=()=>{if(!zr)return;(e.ownerDocument??document).removeEventListener("keydown",zr,!0),zr=null};Ve.push(()=>Gc());let qr=!1,Jc=new Set,ag=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},rr=()=>{if(!Q())return;let l=Ie.peekBanner,g=Ie.peekTextNode;if(!l||!g)return;if($){l.classList.remove("persona-pill-peek--visible");return}let y=N?.getMessages()??[],x;for(let Dt=y.length-1;Dt>=0;Dt--){let I=y[Dt];if(I.role==="assistant"&&I.content){x=I;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let S=x.content,k=!!x.streaming,X=ag(),F=Va(X),G=F.type!=="none"?wr(F.type,X?.plugins):null,ae=G?.isAnimating?.(x)===!0,de=G!==null&&(k||ae);de&&G&&!Jc.has(G.name)&&(Ja(G,e),Jc.add(G.name));let ne=de&&G?.containerClass?G.containerClass:null,Ce=g.dataset.personaPeekStreamClass??null;Ce&&Ce!==ne&&(g.classList.remove(Ce),delete g.dataset.personaPeekStreamClass),ne&&Ce!==ne&&(g.classList.add(ne),g.dataset.personaPeekStreamClass=ne),de?(g.style.setProperty("--persona-stream-step",`${F.speed}ms`),g.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ke=de?Ka(S,F.buffer,G,x,k):S;if(de&&F.placeholder==="skeleton"&&k&&(!Ke||!Ke.trim())){let Dt=document.createElement("div"),I=Ms();I.classList.add("persona-pill-peek__skeleton"),Dt.appendChild(I),$a(g,Dt)}else{let Dt=Math.max(0,Ke.length-100),I=Ke.length>100?Ke.slice(-100):Ke,_e=_n(I);if(!de||!G){let Se=Ke.length>100?`\u2026${I}`:I;g.textContent!==Se&&(g.textContent=Se)}else{let Se=_e;(G.wrap==="char"||G.wrap==="word")&&(Se=Es(_e,G.wrap,`peek-${x.id}`,{skipTags:G.skipTags,startIndex:Dt}));let $e=document.createElement("div");if($e.innerHTML=Se,G.useCaret&&I.length>0){let Mt=Ga(),pt=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=pt[pt.length-1];St?.parentNode?St.parentNode.insertBefore(Mt,St.nextSibling):$e.appendChild(Mt)}$a(g,$e),G.onAfterRender?.({container:g,bubble:l,messageId:x.id,message:x,speed:F.speed,duration:F.duration})}}let qt=hn||qr;l.classList.toggle("persona-pill-peek--visible",qt)};if(Q()){let l=Ie.peekBanner;if(l){let x=S=>{S.preventDefault(),S.stopPropagation(),ht(!0,"user")};l.addEventListener("pointerdown",x),Ve.push(()=>{l.removeEventListener("pointerdown",x)})}let g=()=>{qr||(qr=!0,rr())},y=()=>{qr&&(qr=!1,rr())};he.addEventListener("pointerenter",g),he.addEventListener("pointerleave",y),Ve.push(()=>{he.removeEventListener("pointerenter",g),he.removeEventListener("pointerleave",y)}),lt&&(lt.addEventListener("pointerenter",g),lt.addEventListener("pointerleave",y),Ve.push(()=>{lt.removeEventListener("pointerenter",g),lt.removeEventListener("pointerleave",y)}))}let ig=l=>{let g=o.launcher?.composerBar??{},y=g.expandedSize??"anchored",x=g.bottomOffset??"16px",S=g.collapsedMaxWidth,k=g.expandedMaxWidth??"880px",X=g.expandedTopOffset??"5vh",F=g.modalMaxWidth??"880px",G=g.modalMaxHeight??"min(90vh, 800px)",ae="calc(100vw - 32px)",de="var(--persona-pill-area-height, 80px)",ne=Ee.style;if(ne.left="",ne.right="",ne.top="",ne.bottom="",ne.transform="",ne.width="",ne.maxWidth="",ne.height="",ne.maxHeight="",lt){let Ce=lt.style;Ce.bottom=x,Ce.width=S??""}if(l&&y!=="fullscreen"){if(y==="modal"){ne.top="50%",ne.left="50%",ne.transform="translate(-50%, -50%)",ne.bottom="auto",ne.right="auto",ne.width=F,ne.maxWidth=ae,ne.maxHeight=G,ne.height=G;return}ne.left="50%",ne.transform="translateX(-50%)",ne.bottom=`calc(${x} + ${de})`,ne.top=X,ne.width=k,ne.maxWidth=ae}},Vr=()=>{if(!B())return;if(Q()){let ae=(o.launcher?.composerBar??{}).expandedSize??"anchored",de=$?"expanded":"collapsed";Ee.dataset.state=de,Ee.dataset.expandedSize=ae,lt&&(lt.dataset.state=de,lt.dataset.expandedSize=ae),Ee.style.removeProperty("display"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),ig($),ge.style.display=$?"flex":"none",Gs(),$?(rg(),sg()):(Kc(),Gc()),rr();return}let l=Bt(o),g=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,S=g.innerWidth<=y,k=x&&S&&R,X=sn(o).reveal;$?(Ee.style.removeProperty("display"),Ee.style.display=l?"flex":"",Ee.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":zt&&(zt.style.display="none")):(l?l&&(X==="overlay"||X==="push")&&!k?(Ee.style.removeProperty("display"),Ee.style.display="flex",Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.setProperty("display","none","important"),Ee.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Ee.style.display="",Ee.classList.add("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),_t?_t.element.style.display=l?"none":"":zt&&(zt.style.display=l?"none":""))},ht=(l,g="user")=>{if(!B()||$===l)return;let y=$;$=l,Vr();let x=(()=>{let k=o.launcher?.sidebarMode??!1,X=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,ae=X.innerWidth<=G,de=Bt(o)&&F&&ae,ne=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return k||F&&ae&&R||de||ne})();if($&&x){if(!An){let k=e.getRootNode(),X=k instanceof ShadowRoot?k.host:e.closest(".persona-host");X&&(An=Bl(X,o.launcher?.zIndex??Ut))}Sn||(Sn=Dl(e.ownerDocument))}else $||(An?.(),An=null,Sn?.(),Sn=null);$&&(Kr(),qc()||(Qt()==="follow"?Qn(!0):Uc()));let S={open:$,source:g,timestamp:Date.now()};$&&!y?i.emit("widget:opened",S):!$&&y&&i.emit("widget:closed",S),i.emit("widget:state",{open:$,launcherEnabled:R,voiceActive:Je.active,streaming:N.isStreaming()})},Fi=l=>{ct(l?"stop":"send"),V&&(V.disabled=l),Xs.buttons.forEach(g=>{g.disabled=l}),j.dataset.personaComposerStreaming=l?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},_i=()=>{Je.active||O&&O.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>_i(),200)});let Xc=()=>{J.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",O.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let y=o.copy?.showWelcomeCard!==!1;l.style.display=y?"":"none",y?(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)&&!N?.isStreaming()&&(te.textContent=o.copy?.sendButtonLabel??"Send"),O.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',O.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(g=>({...g,sessionId:l}))}});let ko=null,lg=()=>{ko==null&&(ko=setInterval(()=>{let l=ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(ko),ko=null;return}let g=Date.now();l.forEach(y=>{let x=Number(y.getAttribute("data-tool-elapsed"));x&&(y.textContent=Ca(g-x))})},100))},$i=(l,g)=>{if(Object.is(l,g))return!0;if(l===null||g===null||typeof l!="object"||typeof g!="object")return!1;if(Array.isArray(l)||Array.isArray(g))return!Array.isArray(l)||!Array.isArray(g)||l.length!==g.length?!1:l.every((X,F)=>$i(X,g[F]));let y=l,x=g,S=Object.keys(y),k=Object.keys(x);return S.length===k.length&&S.every(X=>Object.prototype.hasOwnProperty.call(x,X)&&$i(y[X],x[X]))},Qc=l=>{let{content:g,rawContent:y,llmContent:x,...S}=l;return S},ji=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!di(l),cg=(l,g,y)=>{if(l.length!==g.length)return!1;let x=l[y.index],S=g[y.index];return!x||!S||x.id!==y.id||S.id!==y.id?!1:(!Object.is(x.content,S.content)||!Object.is(x.rawContent,S.rawContent)||!Object.is(x.llmContent,S.llmContent))&&ji(x)&&ji(S)&&$i(Qc(x),Qc(S))},Yc=null,sr=null,Lo=null,Dn=null,ta=l=>{Yc=l;let g,y;sr=null;for(let S=l.length-1;S>=0;S-=1){let k=l[S];if(!g&&k.role==="user"&&(g=k),!y&&k.role==="assistant"&&(y=k),!sr&&ji(k)&&(sr={index:S,id:k.id}),g&&y&&sr)break}jr(ve,l,De),Pl(ve,gn.artifacts,{suppressTransition:hn}),lg(),ki(l),Qn(!hn),ng(l),l.length===0&&($r(),Nr=!0,Ii=!1),!Pi||Ys?(Pi=!0,Ri=g?.id??null,Wi=y?.id??null):g&&g.id!==Ri?(Ri=g.id,eg(g.id)):y&&y.id!==Wi&&tg(),y&&(Wi=y.id);let x=Je.lastUserMessageId;g&&g.id!==x&&(Je.lastUserMessageId=g.id,i.emit("user:message",g)),Je.lastUserMessageWasVoice=!!g?.viaVoice,Di(l),rr()},Ui=()=>{Dn!==null&&(cancelAnimationFrame(Dn),Dn=null);let l=Lo;Lo=null,l&&ta(l)},Zc=()=>{Dn!==null&&cancelAnimationFrame(Dn),Dn=null,Lo=null},dg=l=>{let g=Lo??Yc;if(hn&&g&&sr&&cg(g,l,sr)){Lo=l,Dn===null&&(Dn=requestAnimationFrame(()=>{Dn=null;let y=Lo;Lo=null,y&&ta(y)}));return}if(l.length===0){Zc(),ta(l);return}Ui(),ta(l)};N=new hs(o,{onMessagesChanged(l){dg(l)},onStatusChanged(l){let g=o.statusIndicator??{};yt(E,(x=>x==="idle"?g.idleText??Ht.idle:x==="connecting"?g.connectingText??Ht.connecting:x==="connected"?g.connectedText??Ht.connected:x==="error"?g.errorText??Ht.error:x==="paused"?g.pausedText??Ht.paused:x==="resuming"?g.resumingText??Ht.resuming:Ht[x])(l),g,l)},onStreamingChanged(l){l||(N?.getMessages().length===0?Zc():Ui()),hn=l,Fi(l),N&&jr(ve,N.getMessages(),De),l||Qn(!0),tn(),wc(l?"Responding\u2026":"Response complete."),rr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":On(),ir();break;case"processing":On(),mg();break;case"speaking":On(),hg();break;default:l==="idle"&&N.isBargeInActive()?(On(),ir(),V?.setAttribute("aria-label","End voice session")):(Je.active=!1,On(),Bn("system"),bn());break}},onArtifactsState(l){gn=l,l.artifacts.length===0&&(Zo=!1),Pl(ve,l.artifacts,{suppressTransition:hn}),Hn(),Di()},onReconnect(l){let{executionId:g,lastEventId:y}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:g,after:y}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:g,after:y,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:g,after:y})}}),gt.current=N,Ve.push(()=>N.cancel());let zi=null;if(N.onReadAloudChange((l,g)=>{kc=l,Lc=g,Pc();let y=l??zi;l&&(zi=l);let x=y?N.getMessages().find(S=>S.id===y)??null:null;i.emit("message:read-aloud",{messageId:y,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(zi=null)}),Pi=!0,o.voiceRecognition?.provider?.type==="runtype")try{N.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&N.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Oe||o.onSSEEvent)&&N.setSSEEventCallback((l,g)=>{o.onSSEEvent?.(l,g),je?.processEvent(l,g),Oe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})});let ed=()=>{o.resume&&typeof o.reconnectStream=="function"&&N.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=ic(l.metadata),P.syncFromMetadata()),l.messages?.length){Ys=!0;try{N.hydrateMessages(l.messages)}finally{Ys=!1}}l.artifacts?.length&&N.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>ed()):ed();let td=()=>{!Q()||$||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ht(!0,"auto")},nd=l=>{if(l.preventDefault(),N.isStreaming()){N.cancel(),je?.reset(),Ne?.update();return}let g=O.value.trim(),y=kt?.hasAttachments()??!1;if(!g&&!y)return;td();let x;y&&(x=[],x.push(...kt.getContentParts()),g&&x.push(Ea(g))),O.value="",O.style.height="auto",na(),N.sendMessage(g,{contentParts:x}),y&&kt.clearAttachments()},pg=()=>o.features?.composerHistory!==!1,qi={...ja},Vi=!1,na=()=>{qi={...ja}},ug=()=>N.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),fg=l=>{if(!O)return;Vi=!0,O.value=l,O.dispatchEvent(new Event("input",{bubbles:!0})),Vi=!1;let g=O.value.length;O.setSelectionRange(g,g)},od=()=>{Vi||na()},rd=l=>{if(O){if(pg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let g=O.selectionStart===0&&O.selectionEnd===0,y=iu({direction:l.key==="ArrowUp"?"up":"down",history:ug(),currentValue:O.value,atStart:g,state:qi});if(qi=y.state,y.handled){l.preventDefault(),y.value!==void 0&&fg(y.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(N.isStreaming()){l.preventDefault();return}na(),l.preventDefault(),te.click()}}},sd=l=>{l.key!=="Escape"||l.isComposing||N.isStreaming()&&l.composedPath().includes(ge)&&(N.cancel(),je?.reset(),Ne?.update(),na(),l.preventDefault(),l.stopImmediatePropagation())},ad=async l=>{if(o.attachments?.enabled!==!0||!kt)return;let g=Lx(l.clipboardData);g.length!==0&&(l.preventDefault(),await kt.handleFiles(g))},dn=null,Tn=!1,ar=null,At=null,id=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,oa=(l="user")=>{if(Tn||N.isStreaming())return;let g=id();if(!g)return;dn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;dn.continuous=!0,dn.interimResults=!0,dn.lang="en-US";let S=O.value;dn.onresult=k=>{let X="",F="";for(let ae=0;ae<k.results.length;ae++){let de=k.results[ae],ne=de[0].transcript;de.isFinal?X+=ne+" ":F=ne}let G=S+X+F;O.value=G,ar&&clearTimeout(ar),(X||F)&&(ar=window.setTimeout(()=>{let ae=O.value.trim();ae&&dn&&Tn&&(Yn(),O.value="",O.style.height="auto",N.sendMessage(ae,{viaVoice:!0}))},x))},dn.onerror=k=>{k.error!=="no-speech"&&Yn()},dn.onend=()=>{if(Tn){let k=O.value.trim();k&&k!==S.trim()&&(O.value="",O.style.height="auto",N.sendMessage(k,{viaVoice:!0})),Yn()}};try{if(dn.start(),Tn=!0,Je.active=!0,l!=="system"&&(Je.manuallyDeactivated=!1),Bn(l),bn(),V){let k=o.voiceRecognition??{};At={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:k.iconName??"mic",iconSize:parseFloat(k.iconSize??o.sendButton?.size??"40")||24};let X=k.recordingBackgroundColor,F=k.recordingIconColor,G=k.recordingBorderColor;if(V.classList.add("persona-voice-recording"),V.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let ae=V.querySelector("svg");ae&&ae.setAttribute("stroke",F)}G&&(V.style.borderColor=G),V.setAttribute("aria-label","Stop voice recognition")}}catch{Yn("system")}},Yn=(l="user")=>{if(Tn){if(Tn=!1,ar&&(clearTimeout(ar),ar=null),dn){try{dn.stop()}catch{}dn=null}if(Je.active=!1,Bn(l),bn(),V){if(V.classList.remove("persona-voice-recording"),At){V.style.backgroundColor=At.backgroundColor,V.style.color=At.color,V.style.borderColor=At.borderColor;let g=V.querySelector("svg");g&&g.setAttribute("stroke",At.color||"currentColor"),At=null}V.setAttribute("aria-label","Start voice recognition")}}},gg=(l,g)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",S=l?.provider?.type==="custom";if(!(y||x||S))return null;let X=m("div","persona-send-button-wrapper"),F=m("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 G=l?.iconName??"mic",ae=g?.size??"40px",de=l?.iconSize??ae,ne=parseFloat(de)||24,Ce=l?.backgroundColor??g?.backgroundColor,Ke=l?.iconColor??g?.textColor;F.style.width=de,F.style.height=de,F.style.minWidth=de,F.style.minHeight=de,F.style.fontSize="18px",F.style.lineHeight="1",Ke?F.style.color=Ke:F.style.color="var(--persona-text, #111827)";let it=oe(G,ne,Ke||"currentColor",1.5);it?F.appendChild(it):F.textContent="\u{1F3A4}",Ce?F.style.backgroundColor=Ce:F.style.backgroundColor="",l?.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l?.borderColor&&(F.style.borderColor=l.borderColor),l?.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l?.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),X.appendChild(F);let qt=l?.tooltipText??"Start voice recognition";if((l?.showTooltip??!1)&&qt){let I=m("div","persona-send-button-tooltip");I.textContent=qt,X.appendChild(I)}return{micButton:F,micButtonWrapper:X}},Ki=()=>{if(!V||At)return;let l=o.voiceRecognition??{};At={backgroundColor:V.style.backgroundColor,color:V.style.color,borderColor:V.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Gi=(l,g)=>{if(!V)return;let y=V.querySelector("svg");y&&y.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=oe(l,x,g,1.5);S&&V.appendChild(S)},ra=()=>{V&&V.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ir=()=>{if(!V)return;Ki();let l=o.voiceRecognition??{},g=l.recordingBackgroundColor,y=l.recordingIconColor,x=l.recordingBorderColor;if(ra(),V.classList.add("persona-voice-recording"),V.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",V.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let S=V.querySelector("svg");S&&S.setAttribute("stroke",y)}x&&(V.style.borderColor=x),V.setAttribute("aria-label","Stop voice recognition")},mg=()=>{if(!V)return;Ki();let l=o.voiceRecognition??{},g=N.getVoiceInterruptionMode(),y=l.processingIconName??"loader",x=l.processingIconColor??At?.color??"",S=l.processingBackgroundColor??At?.backgroundColor??"",k=l.processingBorderColor??At?.borderColor??"";ra(),V.classList.add("persona-voice-processing"),V.style.backgroundColor=S,V.style.borderColor=k;let X=x||"currentColor";V.style.color=X,Gi(y,X),V.setAttribute("aria-label","Processing voice input"),g==="none"&&(V.style.cursor="default")},hg=()=>{if(!V)return;Ki();let l=o.voiceRecognition??{},g=N.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=l.speakingIconName??y,S=l.speakingIconColor??(g==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),k=l.speakingBackgroundColor??(g==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),X=l.speakingBorderColor??(g==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");ra(),V.classList.add("persona-voice-speaking"),V.style.backgroundColor=k,V.style.borderColor=X;let F=S||"currentColor";V.style.color=F,Gi(x,F);let G=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";V.setAttribute("aria-label",G),g==="none"&&(V.style.cursor="default"),g==="barge-in"&&V.classList.add("persona-voice-recording")},On=()=>{V&&(ra(),At&&(V.style.backgroundColor=At.backgroundColor??"",V.style.color=At.color??"",V.style.borderColor=At.borderColor??"",Gi(At.iconName,At.color||"currentColor"),At=null),V.style.cursor="",V.setAttribute("aria-label","Start voice recognition"))},sa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=N.getVoiceStatus(),g=N.getVoiceInterruptionMode();if(g==="none"&&(l==="processing"||l==="speaking"))return;if(g==="cancel"&&(l==="processing"||l==="speaking")){N.stopVoicePlayback();return}if(N.isBargeInActive()){N.stopVoicePlayback(),N.deactivateBargeIn().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,bn(),Bn("user"),On()});return}N.toggleVoice().then(()=>{Je.active=N.isVoiceActive(),Je.manuallyDeactivated=!N.isVoiceActive(),bn(),Bn("user"),N.isVoiceActive()?ir():On()});return}if(Tn){let l=O.value.trim();Je.manuallyDeactivated=!0,bn(),Yn("user"),l&&(O.value="",O.style.height="auto",N.sendMessage(l))}else Je.manuallyDeactivated=!1,bn(),oa("user")};Sc=sa,V&&(V.addEventListener("click",sa),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()&&N.toggleVoice(),On()):Yn("system"),V&&V.removeEventListener("click",sa)}));let yg=i.on("assistant:complete",()=>{Oc&&(Je.active||Je.manuallyDeactivated||Oc==="assistant"&&!Je.lastUserMessageWasVoice||setTimeout(()=>{!Je.active&&!Je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?N.toggleVoice().then(()=>{Je.active=N.isVoiceActive(),Bn("auto"),N.isVoiceActive()&&ir()}):oa("auto"))},600))});Ve.push(yg);let bg=i.on("action:resubmit",()=>{setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)});Ve.push(bg);let ld=()=>{ht(!$,"user")},_t=null,zt=null;if(R&&!Q()){let{instance:l,element:g}=Fl({config:o,plugins:s,onToggle:ld});_t=l,l||(zt=g)}_t?e.appendChild(_t.element):zt&&e.appendChild(zt),Vr(),ki(),Xc(),Fi(N.isStreaming()),qc()||(Qt()==="follow"?Qn(!0):Uc()),Gf(),z&&(!R||Q()?setTimeout(()=>_i(),0):$&&setTimeout(()=>_i(),200));let Kr=()=>{if(Q()){Yo(),Vr();return}let l=Bt(o),g=o.launcher?.sidebarMode??!1,y=l||g||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,X=x.innerWidth<=k,F=S&&X&&R;try{if(F){Hr(),Br=Ks();return}let G=!1;U&&(U=!1,Hr(),G=!0);let ae=Ks();if(!G&&ae!==Br&&(Hr(),G=!0),Br=ae,G&&Ei(),!R&&!l){he.style.height="",he.style.width="";return}if(!g&&!l){let ne=o?.launcher?.width??o?.launcherWidth??fn;he.style.width=ne,he.style.maxWidth=ne}if(Vs(),!y){let de=x.innerHeight,ne=64,Ce=o.launcher?.heightOffset??0,Ke=Math.max(200,de-ne),bt=Math.min(640,Ke),it=Math.max(200,bt-Ce);he.style.height=`${it}px`}}finally{if(Yo(),Vr(),$&&R){let ae=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),de=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,Ce=Bt(o)&&ne&&ae,Ke=de||ne&&ae&&R||Ce;if(Ke&&!Sn){let bt=e.getRootNode(),it=bt instanceof ShadowRoot?bt.host:e.closest(".persona-host");it&&!An&&(An=Bl(it,o.launcher?.zIndex??Ut)),Sn=Dl(e.ownerDocument)}else Ke||(An?.(),An=null,Sn?.(),Sn=null)}}};Kr();let cd=e.ownerDocument.defaultView??window;if(cd.addEventListener("resize",Kr),Ve.push(()=>cd.removeEventListener("resize",Kr)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Yo()});l.observe(j),Ve.push(()=>l.disconnect())}ln=le.scrollTop;let dd=Rn(le),vg=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Ji=()=>fu(vg(),le),pd=()=>{let l=le.scrollTop,g=Rn(le),y=g<dd;if(dd=g,!Un()){ln=l,tn();return}let{action:x,nextLastScrollTop:S}=za({following:en.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:fo(le,Zs),userScrollThreshold:Vf,isAutoScrolling:cn||Qs||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=S,x==="resume"){Ji()||Xn();return}x==="pause"&&_r()};if(le.addEventListener("scroll",pd,{passive:!0}),Ve.push(()=>le.removeEventListener("scroll",pd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Zf()});l.observe(ve),l.observe(le),Ve.push(()=>l.disconnect())}let ud=()=>{Un()&&en.isFollowing()&&Ji()&&_r()},fd=le.ownerDocument;fd.addEventListener("selectionchange",ud),Ve.push(()=>{fd.removeEventListener("selectionchange",ud)});let xg=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),gd=l=>{vc()&&Un()&&en.isFollowing()&&xg.has(l.key)&&_r()},md=l=>{if(!vc()||!Un()||!en.isFollowing())return;let g=l.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&_r()};le.addEventListener("keydown",gd),le.addEventListener("focusin",md),Ve.push(()=>{le.removeEventListener("keydown",gd),le.removeEventListener("focusin",md)});let hd=l=>{if(!Un())return;let g=qa({following:en.isFollowing(),deltaY:l.deltaY,nearBottom:fo(le,Zs),resumeWhenNearBottom:!0});g==="pause"?_r():g==="resume"&&!Ji()&&Xn()};le.addEventListener("wheel",hd,{passive:!0}),Ve.push(()=>le.removeEventListener("wheel",hd)),It.addEventListener("click",()=>{$r(),le.scrollTop=le.scrollHeight,ln=le.scrollTop,Xn(),Qn(!0),tn()}),Ve.push(()=>It.remove()),Ve.push(()=>{_c(),$r()});let yd=()=>{A&&(So&&(A.removeEventListener("click",So),So=null),B()?(A.style.display="",So=()=>{ht(!1,"user")},A.addEventListener("click",So)):A.style.display="none")};yd(),(()=>{let{clearChatButton:l}=Ie;l&&l.addEventListener("click",()=>{N.clearMessages(),To.clear(),Xn(),$o(Ie.composerOverlay);try{localStorage.removeItem(Lr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Lr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},P.syncFromMetadata(),Oe?.clear(),je?.reset(),Ne?.update()})})(),Me&&Me.addEventListener("submit",nd),O?.addEventListener("keydown",rd),O?.addEventListener("input",od),O?.addEventListener("paste",ad);let bd=e.ownerDocument??document;bd.addEventListener("keydown",sd,!0);let vd="persona-attachment-drop-active",Gr=0,Xi=()=>{Gr=0,ge.classList.remove(vd)},lr=()=>o.attachments?.enabled===!0&&kt!==null,xd=l=>{!pi(l.dataTransfer)||!lr()||(Gr++,Gr===1&&ge.classList.add(vd))},Cd=l=>{!pi(l.dataTransfer)||!lr()||(Gr--,Gr<=0&&Xi())},wd=l=>{!pi(l.dataTransfer)||!lr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Ad=l=>{if(!pi(l.dataTransfer)||!lr())return;l.preventDefault(),l.stopPropagation(),Xi();let g=Array.from(l.dataTransfer.files??[]);g.length!==0&&kt.handleFiles(g)},Zn=!0;ge.addEventListener("dragenter",xd,Zn),ge.addEventListener("dragleave",Cd,Zn),e.addEventListener("dragover",wd,Zn),e.addEventListener("drop",Ad,Zn);let aa=e.ownerDocument,Sd=l=>{lr()&&l.preventDefault()},Td=l=>{lr()&&l.preventDefault()};aa.addEventListener("dragover",Sd),aa.addEventListener("drop",Td),Ve.push(()=>{Me&&Me.removeEventListener("submit",nd),O?.removeEventListener("keydown",rd),O?.removeEventListener("input",od),O?.removeEventListener("paste",ad),bd.removeEventListener("keydown",sd,!0)}),Ve.push(()=>{ge.removeEventListener("dragenter",xd,Zn),ge.removeEventListener("dragleave",Cd,Zn),e.removeEventListener("dragover",wd,Zn),e.removeEventListener("drop",Ad,Zn),aa.removeEventListener("dragover",Sd),aa.removeEventListener("drop",Td),Xi()}),Ve.push(()=>{N.cancel()}),_t?Ve.push(()=>{_t?.destroy()}):zt&&Ve.push(()=>{zt?.remove()});let Wt={update(l){let g=o.toolCall,y=o.messageActions,x=o.layout?.messages,S=o.colorScheme,k=o.loadingIndicator,X=o.iterationDisplay,F=o.features?.showReasoning,G=o.features?.showToolCalls,ae=o.features?.toolCallDisplay,de=o.features?.reasoningDisplay,ne=o.features?.streamAnimation?.type;o={...o,...l},Gs(),br(e,o),Ds(e,o),Os(e,o),Hn(),o.colorScheme!==S&&Dc();let Ce=ii.getForInstance(o.plugins);s.length=0,s.push(...Ce),R=o.launcher?.enabled??!0,D=o.launcher?.autoExpand??!1,re=o.features?.showReasoning??!0,be=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Ke=Qt();Z=o.features?.scrollBehavior??{},Ke!==Qt()&&($r(),Xn()),Ac(),tn();let bt=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!bt){if(Oe||(fe=new Hs(me),Oe=new Ws(Pe,fe),je=je??new Bs,fe.open().then(()=>Oe?.restore()).catch(()=>{}),N.setSSEEventCallback((ee,tt)=>{o.onSSEEvent?.(ee,tt),je?.processEvent(ee,tt),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(tt)})})),!at&&H){let ee=o.features?.eventStream?.classNames,tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(ee?.toggleButton?" "+ee.toggleButton:"");at=m("button",tt),at.style.width="28px",at.style.height="28px",at.style.color=Jt.actionIconColor,at.type="button",at.setAttribute("aria-label","Event Stream"),at.title="Event Stream";let Et=oe("activity","18px","currentColor",1.5);Et&&at.appendChild(Et);let Ge=Ie.clearChatButtonWrapper,dt=Ie.closeButtonWrapper,jt=Ge||dt;jt&&jt.parentNode===H?H.insertBefore(at,jt):H.appendChild(at),at.addEventListener("click",()=>{we?Ir():wi()})}}else!Y&&bt&&(Ir(),at&&(at.remove(),at=null),Oe?.clear(),fe?.destroy(),Oe=null,fe=null,je?.reset(),je=null);if(o.launcher?.enabled===!1&&_t&&(_t.destroy(),_t=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!_t&&!zt){let{instance:ee,element:tt}=Fl({config:o,plugins:s,onToggle:ld});_t=ee,ee||(zt=tt),e.appendChild(tt)}_t&&_t.update(o),W&&o.launcher?.title!==void 0&&(W.textContent=o.launcher.title),K&&o.launcher?.subtitle!==void 0&&(K.textContent=o.launcher.subtitle);let it=o.layout?.header;if(it?.layout!==w&&H){let ee=it?Ps(o,it,{showClose:B(),onClose:()=>ht(!1,"user")}):ho({config:o,showClose:B(),onClose:()=>ht(!1,"user")});rt.replaceHeader(ee),H=rt.header.element,M=rt.header.iconHolder,W=rt.header.headerTitle,K=rt.header.headerSubtitle,A=rt.header.closeButton,w=it?.layout}else if(it&&(M&&(M.style.display=it.showIcon===!1?"none":""),W&&(W.style.display=it.showTitle===!1?"none":""),K&&(K.style.display=it.showSubtitle===!1?"none":""),A&&(A.style.display=it.showCloseButton===!1?"none":""),Ie.clearChatButtonWrapper)){let ee=it.showClearChat;if(ee!==void 0){Ie.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:tt}=Ie;tt&&!tt.classList.contains("persona-absolute")&&(ee?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}let Dt=o.layout?.showHeader!==!1;H&&(H.style.display=Dt?"":"none");let I=o.layout?.showFooter!==!1;j&&(j.style.display=I?"":"none"),Yo(),tn(),R!==q?R?ht(D,"auto"):($=!0,Vr()):D!==_&&ht(D,"auto"),_=D,q=R,Kr(),yd();let $e=JSON.stringify(l.toolCall)!==JSON.stringify(g),Mt=JSON.stringify(o.messageActions)!==JSON.stringify(y),pt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),St=o.loadingIndicator?.render!==k?.render||o.loadingIndicator?.renderIdle!==k?.renderIdle||o.loadingIndicator?.showBubble!==k?.showBubble,vt=o.iterationDisplay!==X,$t=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(de);($e||Mt||pt||St||vt||$t)&&N&&(Li++,jr(ve,N.getMessages(),De));let ut=o.features?.streamAnimation?.type;if(ut!==ne&&ut&&ut!=="none"){let ee=wr(ut,o.features?.streamAnimation?.plugins);ee&&Ja(ee,e)}let ue=o.launcher??{},Tt=ue.headerIconHidden??!1,Vt=o.layout?.header?.showIcon,Ot=Tt||Vt===!1,st=ue.headerIconName,qe=ue.headerIconSize??"48px";if(M){let ee=ge.querySelector(".persona-border-b-persona-divider"),tt=ee?.querySelector(".persona-flex-col");if(Ot)M.style.display="none",ee&&tt&&!ee.contains(tt)&&ee.insertBefore(tt,ee.firstChild);else{if(M.style.display="",M.style.height=qe,M.style.width=qe,ee&&tt&&(ee.contains(M)?M.nextSibling!==tt&&(M.remove(),ee.insertBefore(M,tt)):ee.insertBefore(M,tt)),st){let Ge=parseFloat(qe)||24,dt=oe(st,Ge*.6,"currentColor",1);dt?M.replaceChildren(dt):M.textContent=ue.agentIconText??"\u{1F4AC}"}else if(ue.iconUrl){let Ge=M.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,M.replaceChildren(dt)}}else{let Ge=M.querySelector("svg"),dt=M.querySelector("img");(Ge||dt)&&M.replaceChildren(),M.textContent=ue.agentIconText??"\u{1F4AC}"}let Et=M.querySelector("img");Et&&(Et.style.height=qe,Et.style.width=qe)}}let Ye=o.layout?.header?.showTitle,Pt=o.layout?.header?.showSubtitle;if(W&&(W.style.display=Ye===!1?"none":""),K&&(K.style.display=Pt===!1?"none":""),A){o.layout?.header?.showCloseButton===!1?A.style.display="none":A.style.display="";let tt=ue.closeButtonSize??"32px",Et=ue.closeButtonPlacement??"inline";A.style.height=tt,A.style.width=tt;let{closeButtonWrapper:Ge}=Ie,dt=Et==="top-right",jt=Ge?.classList.contains("persona-absolute");if(Ge&&dt!==jt)if(Ge.remove(),dt)Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ge.style.position="relative",ge.appendChild(Ge);else{let ze=ue.clearChat?.placement??"inline",Ft=ue.clearChat?.enabled??!0;Ge.className=Ft&&ze==="inline"?"":"persona-ml-auto";let Zt=ge.querySelector(".persona-border-b-persona-divider");Zt&&Zt.appendChild(Ge)}if(A.style.color=ue.closeButtonColor||Jt.actionIconColor,ue.closeButtonBackgroundColor?(A.style.backgroundColor=ue.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let ze=ue.closeButtonBorderWidth||"0px",Ft=ue.closeButtonBorderColor||"transparent";A.style.border=`${ze} solid ${Ft}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");ue.closeButtonBorderRadius?(A.style.borderRadius=ue.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(A.style.paddingLeft=ue.closeButtonPaddingX,A.style.paddingRight=ue.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),ue.closeButtonPaddingY?(A.style.paddingTop=ue.closeButtonPaddingY,A.style.paddingBottom=ue.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let on=ue.closeButtonIconName??"x",vn=ue.closeButtonIconText??"\xD7";A.innerHTML="";let Kt=oe(on,"28px","currentColor",1);Kt?A.appendChild(Kt):A.textContent=vn;let Lt=ue.closeButtonTooltipText??"Close chat",rn=ue.closeButtonShowTooltip??!0;if(A.setAttribute("aria-label",Lt),Ge&&(Ge._cleanupTooltip&&(Ge._cleanupTooltip(),delete Ge._cleanupTooltip),rn&&Lt)){let ze=null,Ft=()=>{if(ze||!A)return;let Ho=A.ownerDocument,Yr=Ho.body;if(!Yr)return;ze=Mn(Ho,"div","persona-clear-chat-tooltip"),ze.textContent=Lt;let Zr=Mn(Ho,"div");Zr.className="persona-clear-chat-tooltip-arrow",ze.appendChild(Zr);let Bo=A.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(lo),ze.style.left=`${Bo.left+Bo.width/2}px`,ze.style.top=`${Bo.top-8}px`,ze.style.transform="translate(-50%, -100%)",Yr.appendChild(ze)},Zt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};Ge.addEventListener("mouseenter",Ft),Ge.addEventListener("mouseleave",Zt),A.addEventListener("focus",Ft),A.addEventListener("blur",Zt),Ge._cleanupTooltip=()=>{Zt(),Ge&&(Ge.removeEventListener("mouseenter",Ft),Ge.removeEventListener("mouseleave",Zt)),A&&(A.removeEventListener("focus",Ft),A.removeEventListener("blur",Zt))}}}let{clearChatButton:Be,clearChatButtonWrapper:Ze}=Ie;if(Be){let ee=ue.clearChat??{},tt=ee.enabled??!0,Et=o.layout?.header?.showClearChat,Ge=Et!==void 0?Et:tt,dt=ee.placement??"inline";if(Ze){Ze.style.display=Ge?"":"none";let{closeButtonWrapper:jt}=Ie;!Q()&&jt&&!jt.classList.contains("persona-absolute")&&(Ge?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let on=dt==="top-right",vn=Ze.classList.contains("persona-absolute");if(!Q()&&on!==vn&&Ge){if(Ze.remove(),on)Ze.className="persona-absolute persona-top-4 persona-z-50",Ze.style.right="48px",ge.style.position="relative",ge.appendChild(Ze);else{Ze.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ze.style.right="";let Lt=ge.querySelector(".persona-border-b-persona-divider"),rn=Ie.closeButtonWrapper;Lt&&rn&&rn.parentElement===Lt?Lt.insertBefore(Ze,rn):Lt&&Lt.appendChild(Ze)}let Kt=Ie.closeButtonWrapper;Kt&&!Kt.classList.contains("persona-absolute")&&(on?Kt.classList.add("persona-ml-auto"):Kt.classList.remove("persona-ml-auto"))}}if(Ge){if(!Q()){let ze=ee.size??"32px";Be.style.height=ze,Be.style.width=ze}let jt=ee.iconName??"refresh-cw",on=ee.iconColor??"";Be.style.color=on||Jt.actionIconColor,Be.innerHTML="";let vn=Q()?"14px":"20px",Kt=oe(jt,vn,"currentColor",2);if(Kt&&Be.appendChild(Kt),ee.backgroundColor?(Be.style.backgroundColor=ee.backgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let ze=ee.borderWidth||"0px",Ft=ee.borderColor||"transparent";Be.style.border=`${ze} solid ${Ft}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");ee.borderRadius?(Be.style.borderRadius=ee.borderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),ee.paddingX?(Be.style.paddingLeft=ee.paddingX,Be.style.paddingRight=ee.paddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),ee.paddingY?(Be.style.paddingTop=ee.paddingY,Be.style.paddingBottom=ee.paddingY):(Be.style.paddingTop="",Be.style.paddingBottom="");let Lt=ee.tooltipText??"Clear chat",rn=ee.showTooltip??!0;if(Be.setAttribute("aria-label",Lt),Ze&&(Ze._cleanupTooltip&&(Ze._cleanupTooltip(),delete Ze._cleanupTooltip),rn&&Lt)){let ze=null,Ft=()=>{if(ze||!Be)return;let Ho=Be.ownerDocument,Yr=Ho.body;if(!Yr)return;ze=Mn(Ho,"div","persona-clear-chat-tooltip"),ze.textContent=Lt;let Zr=Mn(Ho,"div");Zr.className="persona-clear-chat-tooltip-arrow",ze.appendChild(Zr);let Bo=Be.getBoundingClientRect();ze.style.position="fixed",ze.style.zIndex=String(lo),ze.style.left=`${Bo.left+Bo.width/2}px`,ze.style.top=`${Bo.top-8}px`,ze.style.transform="translate(-50%, -100%)",Yr.appendChild(ze)},Zt=()=>{ze&&ze.parentNode&&(ze.parentNode.removeChild(ze),ze=null)};Ze.addEventListener("mouseenter",Ft),Ze.addEventListener("mouseleave",Zt),Be.addEventListener("focus",Ft),Be.addEventListener("blur",Zt),Ze._cleanupTooltip=()=>{Zt(),Ze&&(Ze.removeEventListener("mouseenter",Ft),Ze.removeEventListener("mouseleave",Zt)),Be&&(Be.removeEventListener("focus",Ft),Be.removeEventListener("blur",Zt))}}}}let nn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],Ro=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[kr.message,kr.messageAndClick];P=ci({parsers:nn,handlers:Ro,getSessionMetadata:b,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),De=nf(o,P,Te),N.updateConfig(o),jr(ve,N.getMessages(),De),ki(),Xc(),Fi(N.isStreaming());let Ed=o.voiceRecognition?.enabled===!0,ia=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(Ed&&(ia||Rt))if(!V||!Ue){let ee=gg(o.voiceRecognition,o.sendButton);ee&&(V=ee.micButton,Ue=ee.micButtonWrapper,We.insertBefore(Ue,Fe),V.addEventListener("click",sa),V.disabled=N.isStreaming())}else{let ee=o.voiceRecognition??{},tt=o.sendButton??{},Et=ee.iconName??"mic",Ge=tt.size??"40px",dt=ee.iconSize??Ge,jt=parseFloat(dt)||24;V.style.width=dt,V.style.height=dt,V.style.minWidth=dt,V.style.minHeight=dt;let on=ee.iconColor??tt.textColor??"currentColor";V.innerHTML="";let vn=oe(Et,jt,on,2);vn?V.appendChild(vn):V.textContent="\u{1F3A4}";let Kt=ee.backgroundColor??tt.backgroundColor;Kt?V.style.backgroundColor=Kt:V.style.backgroundColor="",on?V.style.color=on:V.style.color="var(--persona-text, #111827)",ee.borderWidth?(V.style.borderWidth=ee.borderWidth,V.style.borderStyle="solid"):(V.style.borderWidth="",V.style.borderStyle=""),ee.borderColor?V.style.borderColor=ee.borderColor:V.style.borderColor="",ee.paddingX?(V.style.paddingLeft=ee.paddingX,V.style.paddingRight=ee.paddingX):(V.style.paddingLeft="",V.style.paddingRight=""),ee.paddingY?(V.style.paddingTop=ee.paddingY,V.style.paddingBottom=ee.paddingY):(V.style.paddingTop="",V.style.paddingBottom="");let Lt=Ue?.querySelector(".persona-send-button-tooltip"),rn=ee.tooltipText??"Start voice recognition";if((ee.showTooltip??!1)&&rn)if(Lt)Lt.textContent=rn,Lt.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=rn,Ue?.insertBefore(Ft,V)}else Lt&&(Lt.style.display="none");Ue.style.display="",V.disabled=N.isStreaming()}else V&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()&&N.toggleVoice():Tn&&Yn());if(o.attachments?.enabled===!0)if(!He||!Ae){let ee=o.attachments??{},Et=(o.sendButton??{}).size??"40px";Xe||(Xe=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Xe.style.display="none",Me.insertBefore(Xe,O)),ke||(ke=document.createElement("input"),ke.type="file",ke.accept=(ee.allowedTypes??$n).join(","),ke.multiple=(ee.maxFiles??4)>1,ke.style.display="none",ke.setAttribute("aria-label","Attach files"),Me.insertBefore(ke,O)),He=m("div","persona-send-button-wrapper"),Ae=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let Ge=ee.buttonIconName??"paperclip",dt=Et,jt=parseFloat(dt)||40,on=Math.round(jt*.6);Ae.style.width=dt,Ae.style.height=dt,Ae.style.minWidth=dt,Ae.style.minHeight=dt,Ae.style.fontSize="18px",Ae.style.lineHeight="1",Ae.style.backgroundColor="transparent",Ae.style.color="var(--persona-primary, #111827)",Ae.style.border="none",Ae.style.borderRadius="6px",Ae.style.transition="background-color 0.15s ease",Ae.addEventListener("mouseenter",()=>{Ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Ae.addEventListener("mouseleave",()=>{Ae.style.backgroundColor="transparent"});let vn=oe(Ge,on,"currentColor",1.5);vn?Ae.appendChild(vn):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",rn=>{rn.preventDefault(),ke?.click()}),He.appendChild(Ae);let Kt=ee.buttonTooltipText??"Attach file",Lt=m("div","persona-send-button-tooltip");Lt.textContent=Kt,He.appendChild(Lt),et.append(He),!kt&&ke&&Xe&&(kt=yr.fromConfig(ee),kt.setPreviewsContainer(Xe),ke.addEventListener("change",async()=>{kt&&ke?.files&&(await kt.handleFileSelect(ke.files),ke.value="")})),ge.querySelector(".persona-attachment-drop-overlay")||ge.appendChild(of(ee.dropOverlay))}else{He.style.display="";let ee=o.attachments??{};ke&&(ke.accept=(ee.allowedTypes??$n).join(","),ke.multiple=(ee.maxFiles??4)>1),kt&&kt.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}else He&&(He.style.display="none"),kt&&kt.clearAttachments(),ge.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},Jr=Nt.useIcon??!1,ca=Nt.iconText??"\u2191",cr=Nt.iconName,Xr=Nt.tooltipText??"Send message",Qi=Nt.showTooltip??!1,Io=Nt.size??"40px",Nn=Nt.backgroundColor,Wo=Nt.textColor;if(Jr){if(te.style.width=Io,te.style.height=Io,te.style.minWidth=Io,te.style.minHeight=Io,te.style.fontSize="18px",te.style.lineHeight="1",te.innerHTML="",Wo?te.style.color=Wo:te.style.color="var(--persona-button-primary-fg, #ffffff)",cr){let ee=parseFloat(Io)||24,tt=Wo?.trim()||"currentColor",Et=oe(cr,ee,tt,2);Et?te.appendChild(Et):te.textContent=ca}else te.textContent=ca;te.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn?(te.style.backgroundColor=Nn,te.classList.remove("persona-bg-persona-primary")):(te.style.backgroundColor="",te.classList.add("persona-bg-persona-primary"))}else te.textContent=o.copy?.sendButtonLabel??"Send",te.style.width="",te.style.height="",te.style.minWidth="",te.style.minHeight="",te.style.fontSize="",te.style.lineHeight="",te.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",Nn?(te.style.backgroundColor=Nn,te.classList.remove("persona-bg-persona-accent")):te.classList.add("persona-bg-persona-accent"),Wo?te.style.color=Wo:te.classList.add("persona-text-white");Nt.borderWidth?(te.style.borderWidth=Nt.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),Nt.borderColor?te.style.borderColor=Nt.borderColor:te.style.borderColor="",Nt.paddingX?(te.style.paddingLeft=Nt.paddingX,te.style.paddingRight=Nt.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),Nt.paddingY?(te.style.paddingTop=Nt.paddingY,te.style.paddingBottom=Nt.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Qr=Fe?.querySelector(".persona-send-button-tooltip");if(Qi&&Xr)if(Qr)Qr.textContent=Xr,Qr.style.display="";else{let ee=document.createElement("div");ee.className="persona-send-button-tooltip",ee.textContent=Xr,Fe?.insertBefore(ee,te)}else Qr&&(Qr.style.display="none");let da=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);da?(ve.style.maxWidth=da,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",Me&&(Me.style.maxWidth=da,Me.style.marginLeft="auto",Me.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=da,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",Me&&(Me.style.maxWidth="",Me.style.marginLeft="",Me.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let eo=o.statusIndicator??{},Cg=eo.visible??!0;if(E.style.display=Cg?"":"none",N){let ee=N.getStatus();yt(E,(Et=>Et==="idle"?eo.idleText??Ht.idle:Et==="connecting"?eo.connectingText??Ht.connecting:Et==="connected"?eo.connectedText??Ht.connected:Et==="error"?eo.errorText??Ht.error:Ht[Et])(ee),eo,ee)}E.classList.remove("persona-text-left","persona-text-center","persona-text-right");let wg=eo.align==="left"?"persona-text-left":eo.align==="center"?"persona-text-center":"persona-text-right";E.classList.add(wg)},open(){B()&&ht(!0,"api")},close(){B()&&ht(!1,"api")},toggle(){B()&&ht(!$,"api")},reconnect(){N.reconnectNow()},clearChat(){Wn=!1,N.clearMessages(),To.clear(),Xn();try{localStorage.removeItem(Lr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Lr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Lr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},P.syncFromMetadata(),Oe?.clear(),je?.reset(),Ne?.update()},setMessage(l){return!O||N.isStreaming()?!1:(!$&&B()&&ht(!0,"system"),O.value=l,O.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(N.isStreaming())return!1;let g=l?.trim()||O.value.trim();return g?(!$&&B()&&ht(!0,"system"),O.value="",O.style.height="auto",N.sendMessage(g),!0):!1},startVoiceRecognition(){return N.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(N.isVoiceActive()||(!$&&B()&&ht(!0,"system"),Je.manuallyDeactivated=!1,bn(),N.toggleVoice().then(()=>{Je.active=N.isVoiceActive(),Bn("user"),N.isVoiceActive()&&ir()})),!0):Tn?!0:id()?(!$&&B()&&ht(!0,"system"),Je.manuallyDeactivated=!1,bn(),oa("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?N.isVoiceActive()?(N.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,bn(),Bn("user"),On()}),!0):!1:Tn?(Je.manuallyDeactivated=!0,bn(),Yn("user"),!0):!1},injectMessage(l){return!$&&B()&&ht(!0,"system"),N.injectMessage(l)},injectAssistantMessage(l){!$&&B()&&ht(!0,"system");let g=N.injectAssistantMessage(l);return pe&&(pe=!1,ye&&(clearTimeout(ye),ye=null),setTimeout(()=>{N&&!N.isStreaming()&&N.continueConversation()},100)),g},injectUserMessage(l){return!$&&B()&&ht(!0,"system"),N.injectUserMessage(l)},injectSystemMessage(l){return!$&&B()&&ht(!0,"system"),N.injectSystemMessage(l)},injectMessageBatch(l){return!$&&B()&&ht(!0,"system"),N.injectMessageBatch(l)},injectComponentDirective(l){return!$&&B()&&ht(!0,"system"),N.injectComponentDirective(l)},injectTestMessage(l){!$&&B()&&ht(!0,"system"),N.injectTestEvent(l)},async connectStream(l,g){return N.connectStream(l,g)},__pushEventStreamEvent(l){Oe&&(je?.processEvent(l.type,l.payload),Oe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Y||!Oe||wi()},hideEventStream(){we&&Ir()},isEventStreamVisible(){return we},showArtifacts(){Xt(o)&&(Wn=!1,Zo=!0,Hn(),Qe?.setMobileOpen(!0))},hideArtifacts(){Xt(o)&&(Wn=!0,Hn())},upsertArtifact(l){return Xt(o)?(No(o.features?.artifacts,l.artifactType)==="panel"&&(Wn=!1,Zo=!0),N.upsertArtifact(l)):null},selectArtifact(l){Xt(o)&&N.selectArtifact(l)},clearArtifacts(){Xt(o)&&N.clearArtifacts()},getArtifacts(){return N?.getArtifacts()??[]},getSelectedArtifactId(){return N?.getSelectedArtifactId()??null},focusInput(){return R&&!$&&!Q()||!O?!1:(O.focus(),!0)},async resolveApproval(l,g,y){let S=N.getMessages().find(k=>k.variant==="approval"&&k.approval?.id===l);if(!S?.approval)throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){N.resolveWebMcpApproval(S.id,g);return}return N.resolveApproval(S.approval,g,y)},getMessages(){return N.getMessages()},getStatus(){return N.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,g){return i.on(l,g)},off(l,g){i.off(l,g)},isOpen(){return B()&&$},isVoiceActive(){return Je.active},toggleReadAloud(l){N.toggleReadAloud(l)},stopReadAloud(){N.stopSpeaking()},getReadAloudState(l){return N.getReadAloudState(l)},onReadAloudChange(l){return N.onReadAloudChange(l)},getState(){return{open:B()&&$,launcherEnabled:R,voiceActive:Je.active,streaming:N.isStreaming()}},showCSATFeedback(l){!$&&B()&&ht(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=sc({onSubmit:async(x,S)=>{N.isClientTokenMode()&&await N.submitCSATFeedback(x,S),l?.onSubmit?.(x,S)},onDismiss:l?.onDismiss,...l});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!$&&B()&&ht(!0,"system");let g=ve.querySelector(".persona-feedback-container");g&&g.remove();let y=ac({onSubmit:async(x,S)=>{N.isClientTokenMode()&&await N.submitNPSFeedback(x,S),l?.onSubmit?.(x,S)},onDismiss:l?.onDismiss,...l});ve.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return N.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return N.submitNPSFeedback(l,g)},destroy(){Ui(),ko!=null&&(clearInterval(ko),ko=null),Ve.forEach(l=>l()),Ee.remove(),lt?.remove(),_t?.destroy(),zt?.remove(),So&&A.removeEventListener("click",So)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,g={controller:Wt,getMessages:Wt.getMessages,getStatus:Wt.getStatus,getMetadata:Wt.getPersistentMetadata,updateMetadata:Wt.updatePersistentMetadata,clearHistory:()=>Wt.clearChat(),setVoiceActive:y=>y?Wt.startVoiceRecognition():Wt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ve.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&Wt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ve.push(()=>{window.removeEventListener("persona:focusInput",g)}),Y){let F=ae=>{let de=ae.detail;(!de?.instanceId||de.instanceId===l)&&Wt.showEventStream()},G=ae=>{let de=ae.detail;(!de?.instanceId||de.instanceId===l)&&Wt.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",G),Ve.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",G)})}let y=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&Wt.showArtifacts()},x=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&Wt.hideArtifacts()},S=F=>{let G=F.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&Wt.upsertArtifact(G.artifact)},k=F=>{let G=F.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&Wt.selectArtifact(G.id)},X=F=>{let G=F.detail;(!G?.instanceId||G.instanceId===l)&&Wt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",k),window.addEventListener("persona:clearArtifacts",X),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",k),window.removeEventListener("persona:clearArtifacts",X)})}let pn=Px(o.persistState);if(pn&&B()){let l=Rx(pn.storage),g=`${pn.keyPrefix}widget-open`,y=`${pn.keyPrefix}widget-voice`,x=`${pn.keyPrefix}widget-voice-mode`;if(l){let S=pn.persist?.openState&&l.getItem(g)==="true",k=pn.persist?.voiceState&&l.getItem(y)==="true",X=pn.persist?.voiceState&&l.getItem(x)==="true";if(S&&setTimeout(()=>{Wt.open(),setTimeout(()=>{if(k||X)Wt.startVoiceRecognition();else if(pn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),pn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(g,"true")}),i.on("widget:closed",()=>{l.setItem(g,"false")})),pn.persist?.voiceState&&(i.on("voice:state",F=>{l.setItem(y,F.active?"true":"false")}),i.on("user:message",F=>{l.setItem(x,F.viaVoice?"true":"false")})),pn.clearOnChatClear){let F=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(x)},G=()=>F();window.addEventListener("persona:clear-chat",G),Ve.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(h&&B()&&setTimeout(()=>{Wt.open()},0),rr(),!qf){let l=ts(()=>{N&&(Li++,To.clear(),jr(ve,N.getMessages(),De))});Ve.push(l)}return Wt};var rf=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Ix=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Wx=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Hx=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let s=o.offsetHeight>0;o.style.height="100%";let r=o.offsetHeight>0;o.remove(),!(!s||r)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},sf=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},uc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},af=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",uc(e)},cc=e=>{e.style.transition=""},dc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},pc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ui=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Bx=(e,t,n,o,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Dx=(e,t,n,o,s,r)=>{let a=r?t:e;s==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Ox=e=>{let t=Vo(e),n=t.components?.panel,o=(s,r)=>s==null||s===""?r:Gt(t,s)??s;return{inset:o(n?.inset,Ia),canvasBackground:o(n?.canvasBackground,Wa)}},lf=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},Nx=(e,t,n,o,s,r,a,i)=>{let p=sn(r),d=p.reveal==="push",c=i!=null,u=i?.inset??"",h=i?.canvasBackground??"";Bx(e,t,n,o,d),Dx(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,b=r?.launcher?.mobileFullscreen??!0,C=r?.launcher?.mobileBreakpoint??640,T=f!=null?f.innerWidth<=C:!1;if(b&&T&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),dc(t),cc(o),af(o),pc(n),ui(s,o),lf(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(r?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),af(o),Ix(o,p.maxHeight),lf(o,c&&a,u,h),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",dc(t),cc(o),pc(n),ui(s,o);let P=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=P,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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",cc(o),uc(o),ui(s,o);let P=rf(p.width,e.clientWidth),R=Math.max(0,e.clientWidth),D=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?a?-P:0:a?0:-P;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${R+P}px`,t.style.transition=D,t.style.marginLeft=`${z}px`,t.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{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",dc(t),uc(o),pc(n),ui(s,o);let P=p.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.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",z=!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",Wx(o,p.maxHeight),o.style.overflow=P||z?"hidden":"visible",o.style.transition=D,P){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let _=c?`calc(${rf(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;s.style.width=_,s.style.minWidth=_,s.style.maxWidth=_,s.style.boxSizing="border-box"}}},Fx=(e,t)=>{let n=e.ownerDocument.createElement("div");return sf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){sf(n,o)},destroy(){n.remove()}}},_x=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let r=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let h=null,f=()=>{h?.disconnect(),h=null},b=null,C=()=>{b=t?.launcher?.detachedPanel===!0?Ox(t):null};C();let T=()=>{Nx(a,i,p,d,c,t,u,b)},L=null,P=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=vs(()=>{C(),T()}))},R=()=>{f(),sn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(h=new ResizeObserver(()=>{T()}),h.observe(a)))},D=!1,z=()=>{T(),R(),u&&!D&&a.dataset.personaDockMobileFullscreen!=="true"&&(D=!0,Hx(a,sn(t)))},_=a.ownerDocument.defaultView,q=()=>{z()};return _?.addEventListener("resize",q),sn(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),z(),P(),{mode:"docked",host:c,shell:a,syncWidgetState(w){let U=w.launcherEnabled?w.open:!0;u!==U&&(u=U,z())},updateConfig(w){t=w,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),P()},destroy(){_?.removeEventListener("resize",q),L?.(),L=null,f(),o.isConnected&&(r&&r.parentNode===o?o.insertBefore(e,r):o.appendChild(e)),a.remove()}}},fi=(e,t)=>Bt(t)?_x(e,t):Fx(e,t);var $x=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},cf=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},df=e=>{let t=$x(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,s=e.config,r=fi(t,s),a,i=[],p=(T,L)=>{let R=!(L?.launcher?.enabled??!0)||Bt(L),D=o.createElement("div");if(D.setAttribute("data-persona-root","true"),R&&(D.style.height="100%",D.style.display="flex",D.style.flexDirection="column",D.style.flex="1",D.style.minHeight="0"),n){let z=T.attachShadow({mode:"open"});z.appendChild(D),cf(z,o)}else T.appendChild(D),cf(T,o);return t.id&&D.setAttribute("data-persona-instance",t.id),D},d=()=>{r.syncWidgetState(a.getState())},c=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let T=p(r.host,s);a=lc(T,s,{debugTools:e.debugTools}),c()},h=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),e.onChatReady?.();let f=T=>{h(),r.destroy(),r=fi(t,T),s=T,u()},b={update(T){let L={...s,...T,launcher:{...s?.launcher??{},...T?.launcher??{},dock:{...s?.launcher?.dock??{},...T?.launcher?.dock??{}}}},P=Bt(s),R=Bt(L),D=mo(s),z=mo(L);if(P!==R||D!==z){f(L);return}s=L,r.updateConfig(s),a.update(T),d()},destroy(){h(),r.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(b,{get(T,L,P){if(L==="host")return r.host;if(L in T)return Reflect.get(T,L,P);let R=a[L];return typeof R=="function"?R.bind(a):R}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};var mf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),jx=new Set(["button","a","input","select","textarea","details","summary"]),Ux=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),fc=/\b(product|card|item|listing|result)\b/i,mc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,zx=3e3,qx=100;function hf(e){let t=typeof e.className=="string"?e.className:"";if(fc.test(t)||e.id&&fc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&fc.test(o.value))return!0}return!1}function yf(e){return mc.test((e.textContent??"").trim())}function bf(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Vx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function pf(e){let t=e.match(mc);return t?t[0]:null}function uf(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Kx(e){let t=[],n=o=>{let s=o.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var Gx="commerce-card",Jx="result-card";function ff(e){return!hf(e)||!yf(e)||!bf(e)&&!Vx(e)?0:5200}function gf(e){return!hf(e)||yf(e)||!bf(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var vf=[{id:Gx,scoreElement(e){return ff(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||mc.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(ff(e)===0)return null;let{title:n,href:o}=uf(e),s=pf((e.textContent??"").trim())??pf(t.text)??"",r=Kx(e);return[o&&n?`[${n}](${o})${s?`: ${s}`:""}`:n?`${n}${s?`: ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,r.length?`actions: ${r.join(", ")}`:""].filter(Boolean).join(`
135
+ `)}},{id:Jx,scoreElement(e){return gf(e)},formatSummary(e,t){if(gf(e)===0)return null;let{title:n,href:o}=uf(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
136
+ `)}}];function Xx(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Qx(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",s=t.maxTextLength??e.maxTextLength??200,r=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??vf;return i==="simple"&&e.rules&&e.rules.length>0?(Xx(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:s,visibleOnly:r,root:a,rules:d}}function gc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Yx=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Zx(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||jx.has(t)||n&&Ux.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function xf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function eC(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let r=e.getAttribute("type");r&&(t.type=r);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function Cf(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${gc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Yx){let r=e.getAttribute(s);if(r){let a=`${t}[${s}="${gc(r)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>gc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let r=e.parentElement;if(r){let i=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let r=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(r>=0)return`${t}:nth-of-type(${r+1})`}return t}function tC(e){return e==="static"?qx:zx}function wf(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Cf(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:Zx(e),attributes:eC(e)}}function nC(e,t,n,o){let s=tC(t.interactivity),r=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(s+=i,a.formatSummary&&!r&&(r=a))}return{score:s,formattingRule:r}}function oC(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function rC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,s=[],r=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(mf.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!xf(d)){i=a.nextNode();continue}let u=wf(d,e.maxTextLength),h=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(T=>T==="role");if(!h&&!f){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:b,formattingRule:C}=nC(d,u,e.rules,n);s.push({el:d,domIndex:r,enriched:u,score:b,formattingRule:C}),r+=1}i=a.nextNode()}s.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,h=c.enriched.interactivity==="static"?1:0;return u!==h?u-h:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of s){if(p.length>=e.maxElements)break;oC(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,h=c.enriched.interactivity==="static"?1:0;return u!==h?u-h:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let h=d.formattingRule.formatSummary(d.el,d.enriched,n);h&&(c=h)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function sC(e,t){let n=[],o=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),r=s.currentNode;for(;r&&n.length<e.maxElements;){if(r.nodeType===Node.ELEMENT_NODE){let p=r,d=p.tagName.toLowerCase();if(mf.has(d)){r=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){r=s.nextNode();continue}}catch{}if(e.visibleOnly&&!xf(p)){r=s.nextNode();continue}let c=wf(p,e.maxTextLength),u=c.text.length>0,h=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!u&&!h){r=s.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}r=s.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function aC(e={}){let t=Qx(e),n=t.root??document.body;return n?t.mode==="simple"?sC(t,n):rC(t,n):[]}var gi=100;function iC(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let r=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);r.length>0&&o.push(`Structured summaries:
137
+ ${r.map(a=>`- ${a.split(`
115
138
  `).join(`
116
139
  `)}`).join(`
117
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Pi)}" (clickable)`);r.push(`Interactive elements:
118
- ${a.join(`
119
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Pi)}" (navigable)`);r.push(`Navigation links:
120
- ${a.join(`
121
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Pi)}" (input)`);r.push(`Form inputs:
122
- ${a.join(`
123
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Pi)}"`);r.push(`Content:
124
- ${a.join(`
125
- `)}`)}return r.join(`
140
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let r of e)n==="structured"&&r.formattedSummary||s[r.interactivity].push(r);if(s.clickable.length>0){let r=s.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,gi)}" (clickable)`);o.push(`Interactive elements:
141
+ ${r.join(`
142
+ `)}`)}if(s.navigable.length>0){let r=s.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,gi)}" (navigable)`);o.push(`Navigation links:
143
+ ${r.join(`
144
+ `)}`)}if(s.input.length>0){let r=s.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,gi)}" (input)`);o.push(`Form inputs:
145
+ ${r.join(`
146
+ `)}`)}if(s.static.length>0){let r=s.static.map(a=>`- ${a.selector}: "${a.text.substring(0,gi)}"`);o.push(`Content:
147
+ ${r.join(`
148
+ `)}`)}return o.join(`
126
149
 
127
- `)}function dC(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function pC(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function uC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function mC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function gC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function fC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var hC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Af={components:{panel:{borderRadius:"0",shadow:"none"}}},Sf={id:"shop",label:"Shopping Assistant",config:{theme:hC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:tr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Tf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Af}},Ef={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Af}},Mf={shop:Sf,minimal:Tf,fullscreen:Ef};function yC(e){return Mf[e]}var bC=df;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function xC(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var kf=`({ text, message }: any) => {
150
+ `)}function lC(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function cC(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function dC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:In(e.colors.primary,.95),100:In(e.colors.primary,.9),200:In(e.colors.primary,.8),300:In(e.colors.primary,.7),400:In(e.colors.primary,.6),500:e.colors.primary,600:In(e.colors.primary,.8),700:In(e.colors.primary,.7),800:In(e.colors.primary,.6),900:In(e.colors.primary,.5),950:In(e.colors.primary,.45)}}),{...t,palette:n}}}}function pC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function uC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function In(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),r=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function fC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var gC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Af={components:{panel:{borderRadius:"0",shadow:"none"}}},Sf={id:"shop",label:"Shopping Assistant",config:{theme:gC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:fn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Tf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Af}},Ef={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Af}},Mf={shop:Sf,minimal:Tf,fullscreen:Ef};function mC(e){return Mf[e]}var hC=df;function jn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function yC(e){if(e)return{getHeaders:jn(e.getHeaders),onFeedback:jn(e.onFeedback),onCopy:jn(e.onCopy),requestMiddleware:jn(e.requestMiddleware),actionHandlers:jn(e.actionHandlers),actionParsers:jn(e.actionParsers),postprocessMessage:jn(e.postprocessMessage),contextProviders:jn(e.contextProviders),streamParser:jn(e.streamParser)}}var kf=`({ text, message }: any) => {
128
151
  const jsonSource = (message as any).rawContent || text || message.content;
129
152
  if (!jsonSource || typeof jsonSource !== 'string') return null;
130
153
  let cleanJson = jsonSource
@@ -167,7 +190,7 @@ ${a.join(`
167
190
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
168
191
  window.location.href = targetUrl;
169
192
  return { handled: true, displayText: text };
170
- }`,If=`function(action, context) {
193
+ }`,Rf=`function(action, context) {
171
194
  if (action.type !== 'nav_then_click') return;
172
195
  var payload = action.payload || action.raw || {};
173
196
  var url = payload.page;
@@ -184,26 +207,26 @@ ${a.join(`
184
207
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
185
208
  window.location.href = targetUrl;
186
209
  return { handled: true, displayText: text };
187
- }`,vC=`(parsed: any) => {
210
+ }`,bC=`(parsed: any) => {
188
211
  if (!parsed || typeof parsed !== 'object') return null;
189
212
  if (parsed.action === 'nav_then_click') return 'Navigating...';
190
213
  if (parsed.action === 'message') return parsed.text || '';
191
214
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
192
215
  return parsed.text || null;
193
- }`,wC=`function(parsed) {
216
+ }`,vC=`function(parsed) {
194
217
  if (!parsed || typeof parsed !== 'object') return null;
195
218
  if (parsed.action === 'nav_then_click') return 'Navigating...';
196
219
  if (parsed.action === 'message') return parsed.text || '';
197
220
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
198
221
  return parsed.text || null;
199
- }`;function CC(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Ii(e){var t,n;return(n=(t=e.parserType)!=null?t:CC(e.streamParser))!=null?n:"plain"}function Ri(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Wi(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Hi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Bi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function rc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Rf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),Rf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),Rf(e,n,`${r} `),e.push(`${r}},`))}function Ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function AC(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:xC(n.hooks)}:void 0;return t==="esm"?SC(r,o):t==="script-installer"?MC(r,o):t==="script-advanced"?LC(r,o):t==="react-component"?TC(r,o):t==="react-advanced"?EC(r,o):kC(r,o)}function SC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
- `)}function TC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
201
- `)}function EC(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ri(e," ")),r.push(...Wi(e," ",n)),r.push(...Hi(e," ")),r.push(...Bi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${vC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
- `)}function Wf(e){var o;let t=Ii(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function MC(e,t){let n=Wf(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/install.global.js" data-config='${s}'></script>`}function kC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ea(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
- `)}function LC(e,t){let n=t==null?void 0:t.hooks,r=Wf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
222
+ }`;function xC(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function mi(e){return e.parserType??xC(e.streamParser)??"plain"}function hi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,s])=>{typeof s=="string"&&n.push(`${t} ${o}: "${s}",`)}),n.push(`${t}},`)),n}function yi(e,t,n){let o=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),r=n?.onFeedback||n?.onCopy;return(s||r)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function bi(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(o||s)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([r,a])=>{typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`)}),n.push(`${t} },`)),s&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function vi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(r=>r!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(r=>r!=="renderUserMessage"&&r!=="renderAssistantMessage");(o||s)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([r,a])=>{r!=="render"&&(typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),s&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([r,a])=>{r==="renderUserMessage"||r==="renderAssistantMessage"||(r==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):r==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${r}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${r}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function hc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function If(e,t,n){Object.entries(t).forEach(([o,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${n}${o}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${n}${o}: {`),If(e,s,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(s)},`)}})}function yo(e,t,n,o){n&&(e.push(`${o}${t}: {`),If(e,n,`${o} `),e.push(`${o}},`))}function Ns(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function CC(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let s=n?{...n,hooks:yC(n.hooks)}:void 0;return t==="esm"?wC(o,s):t==="script-installer"?TC(o,s):t==="script-advanced"?MC(o,s):t==="react-component"?AC(o,s):t==="react-advanced"?SC(o,s):EC(o,s)}function wC(e,t){let n=t?.hooks,o=mi(e),s=o!=="plain",r=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ns(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&yo(r,"theme",e.theme," "),e.launcher&&yo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...hi(e," ")),r.push(...yi(e," ",n)),r.push(...bi(e," ")),r.push(...vi(e," ")),r.push(...hc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push("});"),r.join(`
223
+ `)}function AC(e,t){let n=t?.hooks,o=mi(e),s=o!=="plain",r=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ns(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&yo(r,"theme",e.theme," "),e.launcher&&yo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...hi(e," ")),r.push(...yi(e," ",n)),r.push(...bi(e," ")),r.push(...vi(e," ")),r.push(...hc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage in your app:"),r.push("// import { ChatWidget } from './components/ChatWidget';"),r.push("//"),r.push("// export default function App() {"),r.push("// return ("),r.push("// <div>"),r.push("// {/* Your app content */}"),r.push("// <ChatWidget />"),r.push("// </div>"),r.push("// );"),r.push("// }"),r.join(`
224
+ `)}function SC(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ns(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&yo(o,"theme",e.theme," "),e.launcher&&yo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([s,r])=>{o.push(` ${s}: "${r}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"?o.push(` ${s}: ${r},`):typeof r=="number"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,r])=>{typeof r=="string"?o.push(` ${s}: "${r}",`):typeof r=="boolean"&&o.push(` ${s}: ${r},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([s,r])=>{o.push(` ${s}: ${r},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{o.push(` "${s}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...hi(e," ")),o.push(...yi(e," ",n)),o.push(...bi(e," ")),o.push(...vi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${bC}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${kf}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${kf}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${Pf}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${Pf}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
225
+ `)}function Wf(e){let t=mi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([r,a])=>{typeof a=="string"&&(s[r]=a)}),Object.keys(s).length>0&&(o.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([r,a])=>{r!=="onFeedback"&&r!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[r]=a)}),Object.keys(s).length>0&&(o.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(o.markdown=s)}if(e.layout){let s={};if(e.layout.header){let r={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.header=r)}if(e.layout.messages){let r={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)r.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(r.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(r[a]=i)}),Object.keys(r).length>0&&(s.messages=r)}Object.keys(s).length>0&&(o.layout=s)}return o}function TC(e,t){let n=Wf(e),s=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,r=JSON.stringify(s,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/install.global.js" data-config='${r}'></script>`}function EC(e,t){let n=t?.hooks,o=mi(e),s=o!=="plain",r=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ns(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),s&&r.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&yo(r,"theme",e.theme," "),e.launcher&&yo(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{r.push(` ${a}: "${i}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"?r.push(` ${a}: ${i},`):typeof i=="number"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?r.push(` ${a}: "${i}",`):typeof i=="boolean"&&r.push(` ${a}: ${i},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{r.push(` ${a}: ${i},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{r.push(` "${a}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...hi(e," ")),r.push(...yi(e," ",n)),r.push(...bi(e," ")),r.push(...vi(e," ")),r.push(...hc(n," ")),e.debug&&r.push(` debug: ${e.debug},`),n?.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage}`):r.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),r.push(" }"),r.push(" });"),r.push("</script>"),r.join(`
226
+ `)}function MC(e,t){let n=t?.hooks,o=Wf(e),r=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
204
227
  `).map((a,i)=>i===0?a:" "+a).join(`
205
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${wC});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Lf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Lf}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${If}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${If}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ea(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
- `)}var Hf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Bf=.1,Df=.15,Nf=1.5,oc=24,Of=40,PC=`
228
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(r.push(` widgetConfig.getHeaders = ${n.getHeaders};`),r.push("")),n?.contextProviders&&(r.push(` widgetConfig.contextProviders = ${n.contextProviders};`),r.push("")),n?.streamParser?r.push(` widgetConfig.streamParser = ${n.streamParser};`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(" widgetConfig.streamParser = function() {"),r.push(` return agentWidget.createFlexibleJsonStreamParser(${vC});`),r.push(" };")),r.push(""),n?.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` var customParsers = ${n.actionParsers};`),r.push(" widgetConfig.actionParsers = customParsers.concat(["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Lf}`),r.push(" ]);")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" widgetConfig.actionParsers = ["),r.push(" agentWidget.defaultJsonActionParser,"),r.push(` ${Lf}`),r.push(" ];")),r.push(""),n?.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` var customHandlers = ${n.actionHandlers};`),r.push(" widgetConfig.actionHandlers = customHandlers.concat(["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Rf}`),r.push(" ]);")):(r.push(" // Action handlers for navigation and other actions"),r.push(" widgetConfig.actionHandlers = ["),r.push(" agentWidget.defaultActionHandlers.message,"),r.push(" agentWidget.defaultActionHandlers.messageAndClick,"),r.push(` ${Rf}`),r.push(" ];")),r.push(""),n?.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(` var customResult = (${n.requestMiddleware})(ctx);`),r.push(" var merged = customResult || ctx.payload;"),r.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),r.push(" };")):(r.push(" // Send DOM context with each request"),r.push(" widgetConfig.requestMiddleware = function(ctx) {"),r.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),r.push(" };")),r.push(""),n?.postprocessMessage?r.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(r.push(" // Markdown postprocessor"),r.push(" widgetConfig.postprocessMessage = function(ctx) {"),r.push(" return agentWidget.markdownPostprocessor(ctx.text);"),r.push(" };")),r.push(""),(n?.onFeedback||n?.onCopy)&&(r.push(" // Message action callbacks"),r.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&r.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&r.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),r.push("")),r.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ns(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),r.join(`
229
+ `)}var Hf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Bf=.1,Df=.15,Of=1.5,yc=24,Nf=40,kC=`
207
230
  /* \u2500\u2500 Root \u2500\u2500 */
208
231
  .persona-dc-root {
209
232
  display: flex;
@@ -354,7 +377,7 @@ ${a.join(`
354
377
  .persona-dc-stage {
355
378
  height: 550px;
356
379
  min-height: 400px;
357
- padding: ${oc}px;
380
+ padding: ${yc}px;
358
381
  overflow: auto;
359
382
  background: #f0f1f3;
360
383
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -444,5 +467,5 @@ ${a.join(`
444
467
  min-height: 300px;
445
468
  }
446
469
  }
447
- `;function IC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=PC,document.head.appendChild(e)}function RC(e,t){let n=e.clientWidth-oc*2-Of,r=e.clientHeight-oc*2-Of;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function WC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function HC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");IC();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,b=1,v=!1,S=y("div","persona-dc-root"),T=y("div","persona-dc-toolbar"),L=y("div","persona-dc-toolbar-lead"),P=y("div","persona-dc-toolbar-trail"),E=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Q(-1)}),k=y("div");k.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let I=y("span","persona-dc-title-text"),j=y("span","persona-dc-title-chevron"),$=ye("chevron-down",12,"currentColor",2);$&&j.appendChild($),C.append(I,j);let R=y("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let N=!1;function O(){R.innerHTML="";for(let he=0;he<n.length;he++){let Ke=n[he],gt=y("button","persona-dc-dropdown-item");gt.type="button",gt.setAttribute("role","option"),gt.setAttribute("aria-current",he===p?"true":"false");let Wt=y("span");if(Wt.textContent=Ke.title,gt.appendChild(Wt),Ke.description){let tt=y("span","persona-dc-dropdown-desc");tt.textContent=Ke.description,gt.appendChild(tt)}gt.addEventListener("click",()=>{Ee(),Me(he)}),R.appendChild(gt)}}function Z(){N=!N,R.style.display=N?"":"none",C.setAttribute("aria-expanded",N?"true":"false"),N&&O()}function Ee(){N&&(N=!1,R.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",he=>{he.stopPropagation(),Z()});let de=()=>Ee();document.addEventListener("click",de),k.append(C,R);let ee=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Q(1)}),Le=y("span","persona-dc-counter");L.append(E,k,ee,Le);let Pe=null;i&&(Pe=ui({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:he=>{u=he,ae.dataset.device=u,g=null,J()}}),P.appendChild(Pe.element));let ne=null;if(a){let he=y("div","persona-dc-zoom-controls"),Ke=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let tt=g!=null?g:b;g=Math.max(Df,tt-Bf),J()}});ne=y("span","persona-dc-zoom-level"),ne.title="Reset to 100%",ne.style.cursor="pointer",ne.addEventListener("click",()=>{g=1,J()});let gt=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let tt=g!=null?g:b;g=Math.min(Nf,tt+Bf),J()}}),Wt=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});he.append(Ke,ne,gt,Wt),P.appendChild(he)}if(d){let he=y("div","persona-dc-separator");P.appendChild(he);let Ke=ui({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:gt=>{f=gt,ae.dataset.colorScheme=f,$e()}});P.appendChild(Ke.element)}let Ae=y("div","persona-dc-separator");P.appendChild(Ae);let re=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});P.appendChild(re),T.append(L,P);let se=y("div","persona-dc-stage"),ae=y("div","persona-dc-iframe-wrapper");ae.dataset.device=u,ae.dataset.colorScheme=f;let fe=y("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[p].title,ae.appendChild(fe),se.appendChild(ae),S.append(T,se),e.appendChild(S);function $e(){var he;try{let Ke=(he=fe.contentDocument)==null?void 0:he.body;if(!Ke)return;f==="dark"?Ke.classList.add("theme-dark"):Ke.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>$e());function V(){let he=n[p];I.textContent=he.title,Le.textContent=`${p+1} / ${n.length}`,fe.title=he.title}function Q(he){let Ke=((p+he)%n.length+n.length)%n.length;Me(Ke)}function Me(he){he<0||he>=n.length||(p=he,fe.src=n[p].url,V(),c==null||c(p,n[p]))}function J(){var gt;if(v)return;let he=(gt=Hf[u])!=null?gt:Hf.desktop;b=RC(se,he);let Ke=Math.max(Df,Math.min(Nf,g!=null?g:b));WC(ae,fe,he,Ke,u),ne&&(ne.textContent=`${Math.round(Ke*100)}%`)}let le=new ResizeObserver(()=>J());le.observe(se),V(),fe.src=n[p].url,requestAnimationFrame(()=>J());function Ie(){v||(v=!0,le.disconnect(),document.removeEventListener("click",de),S.remove())}return{element:S,goTo:Me,next:()=>Q(1),prev:()=>Q(-1),getIndex:()=>p,setDevice(he){u=he,ae.dataset.device=he,Pe==null||Pe.setSelected(he),g=null,J()},setColorScheme(he){f=he,ae.dataset.colorScheme=he},setZoom(he){g=he,J()},destroy:Ie}}export{Em as ASK_USER_QUESTION_CLIENT_TOOL,Tm as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ba as ASK_USER_QUESTION_TOOL_NAME,As as AgentWidgetClient,da as AgentWidgetSession,Es as AttachmentManager,Zo as BrowserSpeechEngine,Zm as DEFAULT_COMPONENTS,fl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,tr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Qm as DEFAULT_PALETTE,Ym as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,Mf as PRESETS,Ef as PRESET_FULLSCREEN,Tf as PRESET_MINIMAL,Sf as PRESET_SHOP,Ts as ReadAloudController,tl as SUGGEST_REPLIES_CLIENT_TOOL,Cm as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Hr as SUGGEST_REPLIES_TOOL_NAME,Vx as THEME_ZONES,fr as VERSION,Rr as WEBMCP_TOOL_PREFIX,Qs as WebMcpBridge,dC as accessibilityPlugin,pC as animationsPlugin,es as applyThemeVariables,Ls as attachHeaderToContainer,uC as brandPlugin,wa as buildComposer,yg as buildDefaultHeader,Eo as buildHeader,va as buildHeaderWithLayout,bg as buildMinimalHeader,_a as builtInClientToolsForDispatch,lC as collectEnrichedPageContext,Mo as componentRegistry,Ei as createActionManager,Gl as createAgentExperience,ny as createAskUserQuestionBubble,pl as createBestAvailableVoiceProvider,kv as createBubbleWithLayout,zl as createCSATFeedback,Sl as createComboButton,Mw as createComponentMiddleware,$l as createComponentStreamParser,Zu as createDefaultSanitizer,HC as createDemoCarousel,gh as createDirectivePostprocessor,ts as createDropdownMenu,ay as createFlexibleJsonStreamParser,Gt as createIconButton,yy as createImagePart,il as createJsonStreamParser,pi as createLabelButton,_l as createLocalStorageAdapter,Wa as createMarkdownProcessor,vs as createMarkdownProcessorFromConfig,kg as createMessageActions,Vl as createNPSFeedback,sl as createPlainTextParser,fC as createPlugin,al as createRegexJsonParser,Ca as createStandardBubble,Ka as createTextPart,ua as createTheme,xl as createThemeObserver,ui as createToggleGroup,Ps as createTypingIndicator,Yo as createVoiceProvider,Li as createWidgetHostLayout,ll as createXmlParser,bC as default,Hs as defaultActionHandlers,Ti as defaultJsonActionParser,xf as defaultParseRules,Za as detectColorScheme,fh as directivePostprocessor,na as ensureAskUserQuestionSheet,Kr as escapeHtml,ql as extractComponentDirectiveFromMessage,by as fileToImagePart,cC as formatEnrichedContext,Xo as generateAssistantMessageId,AC as generateCodeSnippet,uy as generateMessageId,wf as generateStableSelector,aa as generateUserMessageId,ma as getActiveTheme,rg as getColorScheme,gy as getDisplayText,xg as getHeaderLayout,hy as getImageParts,yC as getPreset,Ul as hasComponentDirective,fy as hasImages,Tl as headerLayouts,gC as highContrastPlugin,df as initAgentWidget,yo as isAskUserQuestionMessage,Ew as isComponentDirectiveType,dn as isDockedMountMode,Fa as isSuggestRepliesMessage,Ja as isVoiceSupported,Ko as isWebMcpToolName,rl as latestAgentSuggestions,nv as listRegisteredStreamAnimations,Xu as markdownPostprocessor,hl as mergeWithDefaults,my as normalizeContent,bo as parseAskUserQuestionPayload,Am as parseSuggestRepliesPayload,la as pickBestVoice,Si as pluginRegistry,mC as reducedMotionPlugin,ev as registerStreamAnimationPlugin,Jo as removeAskUserQuestionSheet,jl as renderComponentDirective,Mg as renderLoadingIndicatorWithFallback,ye as renderLucideIcon,nr as resolveDockConfig,Xs as resolveSanitizer,yl as resolveTokens,Ji as stripWebMcpPrefix,bl as themeToCssVariables,tv as unregisterStreamAnimationPlugin,xy as validateImageFile,eg as validateTheme};
470
+ `;function LC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=kC,document.head.appendChild(e)}function PC(e,t){let n=e.clientWidth-yc*2-Nf,o=e.clientHeight-yc*2-Nf;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function RC(e,t,n,o,s){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=s==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function IC(e,t){let{items:n,initialIndex:o=0,initialDevice:s="desktop",initialColorScheme:r="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");LC();let c=Math.max(0,Math.min(o,n.length-1)),u=s,h=r,f=null,b=1,C=!1,T=m("div","persona-dc-root"),L=m("div","persona-dc-toolbar"),P=m("div","persona-dc-toolbar-lead"),R=m("div","persona-dc-toolbar-trail"),D=mt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>je(-1)}),z=m("div");z.style.position="relative";let _=m("button","persona-dc-title-btn");_.type="button",_.setAttribute("aria-expanded","false"),_.setAttribute("aria-haspopup","listbox");let q=m("span","persona-dc-title-text"),w=m("span","persona-dc-title-chevron"),U=oe("chevron-down",12,"currentColor",2);U&&w.appendChild(U),_.append(q,w);let Q=m("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let B=!1;function $(){Q.innerHTML="";for(let ie=0;ie<n.length;ie++){let Re=n[ie],xt=m("button","persona-dc-dropdown-item");xt.type="button",xt.setAttribute("role","option"),xt.setAttribute("aria-current",ie===c?"true":"false");let yt=m("span");if(yt.textContent=Re.title,xt.appendChild(yt),Re.description){let rt=m("span","persona-dc-dropdown-desc");rt.textContent=Re.description,xt.appendChild(rt)}xt.addEventListener("click",()=>{ye(),Ne(ie)}),Q.appendChild(xt)}}function pe(){B=!B,Q.style.display=B?"":"none",_.setAttribute("aria-expanded",B?"true":"false"),B&&$()}function ye(){B&&(B=!1,Q.style.display="none",_.setAttribute("aria-expanded","false"))}_.addEventListener("click",ie=>{ie.stopPropagation(),pe()});let Te=()=>ye();document.addEventListener("click",Te),z.append(_,Q);let De=mt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>je(1)}),re=m("span","persona-dc-counter");P.append(D,z,De,re);let be=null;i&&(be=po({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ie=>{u=ie,me.dataset.device=u,f=null,we()}}),R.appendChild(be.element));let Y=null;if(a){let ie=m("div","persona-dc-zoom-controls"),Re=mt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(Df,(f??b)-Bf),we()}});Y=m("span","persona-dc-zoom-level"),Y.title="Reset to 100%",Y.style.cursor="pointer",Y.addEventListener("click",()=>{f=1,we()});let xt=mt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(Of,(f??b)+Bf),we()}}),yt=mt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,we()}});ie.append(Re,Y,xt,yt),R.appendChild(ie)}if(p){let ie=m("div","persona-dc-separator");R.appendChild(ie);let Re=po({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:h,onSelect:xt=>{h=xt,me.dataset.colorScheme=h,Pe()}});R.appendChild(Re.element)}let ce=m("div","persona-dc-separator");R.appendChild(ce);let Z=mt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});R.appendChild(Z),L.append(P,R);let xe=m("div","persona-dc-stage"),me=m("div","persona-dc-iframe-wrapper");me.dataset.device=u,me.dataset.colorScheme=h;let fe=m("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[c].title,me.appendChild(fe),xe.appendChild(me),T.append(L,xe),e.appendChild(T);function Pe(){try{let ie=fe.contentDocument?.body;if(!ie)return;h==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>Pe());function Oe(){let ie=n[c];q.textContent=ie.title,re.textContent=`${c+1} / ${n.length}`,fe.title=ie.title}function je(ie){let Re=((c+ie)%n.length+n.length)%n.length;Ne(Re)}function Ne(ie){ie<0||ie>=n.length||(c=ie,fe.src=n[c].url,Oe(),d?.(c,n[c]))}function we(){if(C)return;let ie=Hf[u]??Hf.desktop;b=PC(xe,ie);let Re=Math.max(Df,Math.min(Of,f??b));RC(me,fe,ie,Re,u),Y&&(Y.textContent=`${Math.round(Re*100)}%`)}let Le=new ResizeObserver(()=>we());Le.observe(xe),Oe(),fe.src=n[c].url,requestAnimationFrame(()=>we());function ot(){C||(C=!0,Le.disconnect(),document.removeEventListener("click",Te),T.remove())}return{element:T,goTo:Ne,next:()=>je(1),prev:()=>je(-1),getIndex:()=>c,setDevice(ie){u=ie,me.dataset.device=ie,be?.setSelected(ie),f=null,we()},setColorScheme(ie){h=ie,me.dataset.colorScheme=ie},setZoom(ie){f=ie,we()},destroy:ot}}export{pp as ASK_USER_QUESTION_CLIENT_TOOL,dp as ASK_USER_QUESTION_PARAMETERS_SCHEMA,ma as ASK_USER_QUESTION_TOOL_NAME,gr as AgentWidgetClient,hs as AgentWidgetSession,yr as AttachmentManager,qo as BrowserSpeechEngine,Np as DEFAULT_COMPONENTS,Cl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,fn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Dp as DEFAULT_PALETTE,Op as DEFAULT_SEMANTIC,ft as DEFAULT_WIDGET_CONFIG,Mf as PRESETS,Ef as PRESET_FULLSCREEN,Tf as PRESET_MINIMAL,Sf as PRESET_SHOP,hr as ReadAloudController,il as SUGGEST_REPLIES_CLIENT_TOOL,ip as SUGGEST_REPLIES_PARAMETERS_SCHEMA,kn as SUGGEST_REPLIES_TOOL_NAME,cb as THEME_ZONES,Cn as VERSION,En as WEBMCP_TOOL_PREFIX,os as WebMcpBridge,lC as accessibilityPlugin,cC as animationsPlugin,br as applyThemeVariables,Ar as attachHeaderToContainer,dC as brandPlugin,Rs as buildComposer,vu as buildDefaultHeader,ho as buildHeader,Ps as buildHeaderWithLayout,xu as buildMinimalHeader,ls as builtInClientToolsForDispatch,aC as collectEnrichedPageContext,Pn as componentRegistry,ci as createActionManager,lc as createAgentExperience,bm as createAskUserQuestionBubble,yl as createBestAvailableVoiceProvider,Ev as createBubbleWithLayout,sc as createCSATFeedback,Ll as createComboButton,Sx as createComponentMiddleware,nc as createComponentStreamParser,Od as createDefaultSanitizer,IC as createDemoCarousel,Pg as createDirectivePostprocessor,Go as createDropdownMenu,wm as createFlexibleJsonStreamParser,mt as createIconButton,Wm as createImagePart,fl as createJsonStreamParser,co as createLabelButton,tc as createLocalStorageAdapter,ua as createMarkdownProcessor,pr as createMarkdownProcessorFromConfig,Pu as createMessageActions,ac as createNPSFeedback,pl as createPlainTextParser,fC as createPlugin,ul as createRegexJsonParser,Gl as createRovingTablist,Is as createStandardBubble,Ea as createTextPart,bs as createTheme,vs as createThemeObserver,po as createToggleGroup,Sr as createTypingIndicator,zo as createVoiceProvider,fi as createWidgetHostLayout,gl as createXmlParser,hC as default,kr as defaultActionHandlers,li as defaultJsonActionParser,vf as defaultParseRules,Ha as detectColorScheme,Rg as directivePostprocessor,is as ensureAskUserQuestionSheet,_n as escapeHtml,rc as extractComponentDirectiveFromMessage,Hm as fileToImagePart,iC as formatEnrichedContext,jo as generateAssistantMessageId,CC as generateCodeSnippet,km as generateMessageId,Cf as generateStableSelector,us as generateUserMessageId,Vo as getActiveTheme,Tl as getColorScheme,Pm as getDisplayText,Cu as getHeaderLayout,Im as getImageParts,mC as getPreset,di as hasComponentDirective,Rm as hasImages,Ol as headerLayouts,uC as highContrastPlugin,df as initAgentWidget,to as isAskUserQuestionMessage,Ax as isComponentDirectiveType,Bt as isDockedMountMode,va as isSuggestRepliesMessage,ka as isVoiceSupported,Oo as isWebMcpToolName,cl as latestAgentSuggestions,ev as listRegisteredStreamAnimations,Id as loadMarkdownParsers,Hd as markdownPostprocessor,wl as mergeWithDefaults,Lm as normalizeContent,ts as onMarkdownParsersReady,no as parseAskUserQuestionPayload,lp as parseSuggestRepliesPayload,gs as pickBestVoice,ii as pluginRegistry,pC as reducedMotionPlugin,Yb as registerStreamAnimationPlugin,$o as removeAskUserQuestionSheet,oc as renderComponentDirective,Lu as renderLoadingIndicatorWithFallback,oe as renderLucideIcon,sn as resolveDockConfig,ns as resolveSanitizer,Al as resolveTokens,tl as stripWebMcpPrefix,Sl as themeToCssVariables,Zb as unregisterStreamAnimationPlugin,Bm as validateImageFile,Fp as validateTheme};
448
471
  //# sourceMappingURL=index.js.map