@runtypelabs/persona 4.17.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-BpWGm7_6.d.cts → types-DsmTD8TO.d.cts} +12 -0
  4. package/dist/animations/{types-BpWGm7_6.d.ts → types-DsmTD8TO.d.ts} +12 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/chunk-3I2S3I5P.js +1 -0
  8. package/dist/chunk-76IELU7F.js +1 -0
  9. package/dist/chunk-EFJBUH5F.js +1 -0
  10. package/dist/chunk-PDPVORUF.js +1 -0
  11. package/dist/chunk-Q735PSZL.js +1 -0
  12. package/dist/chunk-VK6JOIYJ.js +1 -0
  13. package/dist/codegen.cjs +4 -4
  14. package/dist/codegen.js +4 -4
  15. package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
  16. package/dist/context-mentions.cjs +9 -8
  17. package/dist/context-mentions.d.cts +1224 -14
  18. package/dist/context-mentions.d.ts +1224 -14
  19. package/dist/context-mentions.js +9 -8
  20. package/dist/event-stream-view-4EZ7BGFK.js +1 -0
  21. package/dist/event-stream-view.cjs +129 -0
  22. package/dist/event-stream-view.d.cts +8384 -0
  23. package/dist/event-stream-view.d.ts +8384 -0
  24. package/dist/event-stream-view.js +129 -0
  25. package/dist/history-view-BD6OXLNA.js +898 -0
  26. package/dist/history-view.cjs +898 -0
  27. package/dist/history-view.d.cts +1461 -0
  28. package/dist/history-view.d.ts +1461 -0
  29. package/dist/history-view.js +898 -0
  30. package/dist/index.cjs +77 -77
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +2040 -21
  33. package/dist/index.d.ts +2040 -21
  34. package/dist/index.global.js +67 -66
  35. package/dist/index.global.js.map +1 -1
  36. package/dist/index.js +77 -77
  37. package/dist/index.js.map +1 -1
  38. package/dist/launcher.global.js +5 -4
  39. package/dist/launcher.global.js.map +1 -1
  40. package/dist/plugin-kit.cjs +1 -1
  41. package/dist/plugin-kit.d.cts +0 -8
  42. package/dist/plugin-kit.d.ts +0 -8
  43. package/dist/plugin-kit.js +1 -1
  44. package/dist/smart-dom-reader.d.cts +1224 -14
  45. package/dist/smart-dom-reader.d.ts +1224 -14
  46. package/dist/theme-editor-preview.cjs +970 -73
  47. package/dist/theme-editor-preview.d.cts +1343 -15
  48. package/dist/theme-editor-preview.d.ts +1343 -15
  49. package/dist/theme-editor-preview.js +81 -81
  50. package/dist/theme-editor.cjs +7 -7
  51. package/dist/theme-editor.d.cts +1227 -15
  52. package/dist/theme-editor.d.ts +1227 -15
  53. package/dist/theme-editor.js +9 -9
  54. package/dist/theme-reference.cjs +1 -1
  55. package/dist/theme-reference.d.cts +226 -7
  56. package/dist/theme-reference.d.ts +226 -7
  57. package/dist/theme-reference.js +1 -1
  58. package/dist/webmcp-polyfill.js +2 -2
  59. package/dist/widget.css +1 -1
  60. package/package.json +18 -6
  61. package/src/client-history-rest.test.ts +1034 -0
  62. package/src/client-visitor-history.test.ts +596 -0
  63. package/src/client.ts +1040 -24
  64. package/src/components/artifact-inline.ts +8 -1
  65. package/src/components/artifact-pane.test.ts +278 -1
  66. package/src/components/artifact-pane.ts +135 -67
  67. package/src/components/artifact-preview.test.ts +14 -1
  68. package/src/components/artifact-preview.ts +9 -0
  69. package/src/components/header-builder.ts +3 -0
  70. package/src/components/header-layouts.test.ts +171 -7
  71. package/src/components/header-layouts.ts +83 -53
  72. package/src/components/header-parts.test.ts +154 -1
  73. package/src/components/header-parts.ts +266 -138
  74. package/src/components/history-confirm-dialog.ts +177 -0
  75. package/src/components/history-shell-copy.ts +99 -0
  76. package/src/components/history-view/announcer.ts +40 -0
  77. package/src/components/history-view/copy.ts +105 -0
  78. package/src/components/history-view/css.ts +1078 -0
  79. package/src/components/history-view/grouping.test.ts +142 -0
  80. package/src/components/history-view/grouping.ts +142 -0
  81. package/src/components/history-view/icons.ts +73 -0
  82. package/src/components/history-view/rows.ts +341 -0
  83. package/src/components/history-view/state.ts +309 -0
  84. package/src/components/history-view.test.ts +2660 -0
  85. package/src/components/history-view.ts +1891 -0
  86. package/src/components/launcher-surface.test.ts +133 -0
  87. package/src/components/launcher.test.ts +18 -0
  88. package/src/components/launcher.ts +7 -7
  89. package/src/components/panel.ts +17 -7
  90. package/src/components/welcome.ts +72 -2
  91. package/src/defaults.ts +36 -3
  92. package/src/event-stream-view-bundle.test.ts +69 -0
  93. package/src/event-stream-view-entry.ts +19 -0
  94. package/src/event-stream-view-loader.ts +31 -0
  95. package/src/event-stream-view.ts +19 -0
  96. package/src/generated/runtype-openapi-contract.ts +54 -4
  97. package/src/history-render.ts +325 -0
  98. package/src/history-view-bundle.test.ts +78 -0
  99. package/src/history-view-entry.ts +41 -0
  100. package/src/history-view-loader.test.ts +30 -0
  101. package/src/history-view-loader.ts +32 -0
  102. package/src/history-view.ts +28 -0
  103. package/src/index-core.ts +50 -2
  104. package/src/index-global.ts +55 -0
  105. package/src/internal/demo-history-provider.test.ts +402 -0
  106. package/src/internal/demo-history-provider.ts +689 -0
  107. package/src/internal/history-provider-registry.ts +25 -0
  108. package/src/internal/history-provider.ts +150 -0
  109. package/src/internal/runtype-history-provider.test.ts +313 -0
  110. package/src/internal/runtype-history-provider.ts +240 -0
  111. package/src/plugin-kit.test.ts +16 -0
  112. package/src/plugin-kit.ts +13 -5
  113. package/src/plugins/types.ts +177 -1
  114. package/src/session-history.test.ts +1397 -0
  115. package/src/session.ts +1200 -26
  116. package/src/styles/widget-styles.test.ts +133 -0
  117. package/src/styles/widget.css +227 -8
  118. package/src/theme-editor/preview-utils.test.ts +19 -0
  119. package/src/theme-editor/preview-utils.ts +15 -1
  120. package/src/theme-editor/preview.ts +7 -1
  121. package/src/theme-editor/role-mappings.ts +4 -1
  122. package/src/theme-editor/sections.test.ts +168 -1
  123. package/src/theme-editor/sections.ts +136 -7
  124. package/src/theme-editor/webmcp/summary.ts +16 -2
  125. package/src/theme-reference.ts +20 -6
  126. package/src/types/theme.ts +213 -7
  127. package/src/types.ts +927 -7
  128. package/src/ui.artifact-rail-resize.test.ts +235 -0
  129. package/src/ui.attachments-drop.test.ts +1 -0
  130. package/src/ui.header-update-stability.test.ts +2 -2
  131. package/src/ui.history-chunk.test.ts +72 -0
  132. package/src/ui.history-config-provider.test.ts +318 -0
  133. package/src/ui.history-controller.test.ts +711 -0
  134. package/src/ui.history-lifecycle.test.ts +456 -0
  135. package/src/ui.history-render-hooks.test.ts +904 -0
  136. package/src/ui.history-shell.test.ts +1887 -0
  137. package/src/ui.rail-overlay.test.ts +573 -0
  138. package/src/ui.rail-resize.test.ts +284 -0
  139. package/src/ui.rebuild-composer.test.ts +21 -0
  140. package/src/ui.render-welcome.test.ts +42 -0
  141. package/src/ui.shortcuts.test.ts +166 -0
  142. package/src/ui.ts +3071 -240
  143. package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
  144. package/src/utils/artifact-file.ts +15 -0
  145. package/src/utils/artifact-gate.test.ts +4 -0
  146. package/src/utils/artifact-gate.ts +13 -17
  147. package/src/utils/artifact-resize.test.ts +28 -0
  148. package/src/utils/artifact-resize.ts +9 -2
  149. package/src/utils/buttons.ts +188 -1
  150. package/src/utils/config-merge.test.ts +91 -0
  151. package/src/utils/dropdown.ts +10 -1
  152. package/src/utils/history-messages.test.ts +284 -0
  153. package/src/utils/history-messages.ts +284 -0
  154. package/src/utils/icons.ts +3 -0
  155. package/src/utils/shortcuts.test.ts +288 -0
  156. package/src/utils/shortcuts.ts +221 -0
  157. package/src/utils/theme.test.ts +501 -4
  158. package/src/utils/theme.ts +42 -3
  159. package/src/utils/tokens.ts +153 -15
  160. package/src/utils/tooltip-timing.ts +4 -0
  161. package/src/utils/tooltip.test.ts +249 -7
  162. package/src/utils/tooltip.ts +146 -4
  163. package/src/utils/visitor-store.test.ts +425 -0
  164. package/src/utils/visitor-store.ts +337 -0
  165. package/dist/chunk-QJ4LV2KW.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,51 +1,51 @@
1
- "use strict";var tb=Object.create;var gi=Object.defineProperty;var nb=Object.getOwnPropertyDescriptor;var ob=Object.getOwnPropertyNames;var rb=Object.getPrototypeOf,sb=Object.prototype.hasOwnProperty;var Xr=(e,t)=>()=>(e&&(t=e(e=0)),t);var fi=(e,t)=>{for(var n in t)gi(e,n,{get:t[n],enumerable:!0})},Yu=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ob(t))!sb.call(e,r)&&r!==n&&gi(e,r,{get:()=>t[r],enumerable:!(o=nb(t,r))||o.enumerable});return e};var Qs=(e,t,n)=>(n=e!=null?tb(rb(e)):{},Yu(t||!e||!e.__esModule?gi(n,"default",{value:e,enumerable:!0}):n,e)),ab=e=>Yu(gi({},"__esModule",{value:!0}),e);var Zu={};fi(Zu,{DOMPurify:()=>Qu.default,Marked:()=>Xu.Marked});var Xu,Qu,eg=Xr(()=>{"use strict";Xu=require("marked"),Qu=Qs(require("dompurify"),1)});var is,Zc=Xr(()=>{"use strict";is=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function uv(e){return e.replace(/\/+$/,"")}async function gv(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 Di,of=Xr(()=>{"use strict";Zc();Di=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 is(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${uv(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await gv(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var Oi,rf=Xr(()=>{"use strict";Oi=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var sf={};fi(sf,{FallbackSpeechEngine:()=>Oi,RuntypeSpeechEngine:()=>Di});var af=Xr(()=>{"use strict";of();rf()});var cf={};fi(cf,{createReconnectController:()=>mv});function mv(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let x=n;n=null,x()}},a=()=>{let x=e.getStatus();x!=="resuming"&&x!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},g=x=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},x)}),b=()=>{let x=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let k of e.getMessages())k.streaming&&(k.streaming=!1,C=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${x?.executionId??e.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let x=e.config.reconnect?.backoffMs??fv,C=e.config.reconnect?.maxAttempts??x.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let k=e.getResumable(),R=k.lastEventId,E=new AbortController;e.setAbortController(E),e.emitReconnect({phase:"resuming",handle:k,attempt:t});let P=null;try{let B=await S({executionId:k.executionId,after:k.lastEventId,signal:E.signal});B&&B.ok&&B.body&&(P=B.body)}catch{P=null}if(E.signal.aborted)return;if(P){let B=e.getMessages().find($=>$.id===k.assistantMessageId)?.content,N=typeof B=="string"?B:"";try{await e.resumeConnect(P,k.assistantMessageId,N)}catch{}if(E.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:k});return}e.getResumable().lastEventId!==R&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await g(x[Math.min(t-1,x.length-1)]??1e3),E.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var fv,df=Xr(()=>{"use strict";fv=[1e3,2e3,4e3,8e3,8e3]});var fA={};fi(fA,{ASK_USER_QUESTION_CLIENT_TOOL:()=>Yc,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>Jc,ASK_USER_QUESTION_TOOL_NAME:()=>oa,AgentWidgetClient:()=>vr,AgentWidgetSession:()=>cs,AttachmentManager:()=>wr,BrowserSpeechEngine:()=>Fo,DEFAULT_COMPONENTS:()=>cd,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>_i,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>pn,DEFAULT_PALETTE:()=>id,DEFAULT_SEMANTIC:()=>ld,DEFAULT_WIDGET_CONFIG:()=>st,PRESETS:()=>gp,PRESET_FULLSCREEN:()=>up,PRESET_MINIMAL:()=>pp,PRESET_SHOP:()=>dp,ReadAloudController:()=>Cr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ci,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>Vc,SUGGEST_REPLIES_TOOL_NAME:()=>Bn,THEME_ZONES:()=>Sf,VERSION:()=>ao,WEBMCP_TOOL_PREFIX:()=>Wn,WebMcpBridge:()=>ts,accessibilityPlugin:()=>Ph,animationsPlugin:()=>Rh,applyFeaturePreferences:()=>Gd,applyThemeVariables:()=>Ar,attachHeaderToContainer:()=>Er,brandPlugin:()=>Ih,buildComposer:()=>Mr,buildDefaultHeader:()=>Md,buildHeader:()=>uo,buildHeaderWithLayout:()=>hs,buildMinimalHeader:()=>kd,builtInClientToolsForDispatch:()=>ss,canonicalArtifactDisplayMode:()=>on,collectEnrichedPageContext:()=>kh,componentRegistry:()=>Dn,createActionManager:()=>Ha,createAgentExperience:()=>Hl,createAskUserQuestionBubble:()=>Og,createBestAvailableVoiceProvider:()=>Bi,createBubbleWithLayout:()=>gm,createCSATFeedback:()=>Rl,createComboButton:()=>Ji,createComponentMiddleware:()=>sh,createComponentStreamParser:()=>kl,createDefaultSanitizer:()=>Oc,createDemoCarousel:()=>Xh,createDirectivePostprocessor:()=>lg,createDropdownMenu:()=>zo,createFlexibleJsonStreamParser:()=>$g,createIconButton:()=>it,createImagePart:()=>Gg,createJsonStreamParser:()=>Li,createLabelButton:()=>lo,createLocalStorageAdapter:()=>Ml,createMarkdownProcessor:()=>Zs,createMarkdownProcessorFromConfig:()=>hr,createMessageActions:()=>Wd,createNPSFeedback:()=>Il,createPlainTextParser:()=>Mi,createPlugin:()=>Bh,createRegexJsonParser:()=>ki,createRovingTablist:()=>Al,createSlashCommandsSource:()=>yh,createStandardBubble:()=>ys,createStaticMentionSource:()=>hh,createTextPart:()=>Oo,createTheme:()=>ga,createThemeObserver:()=>ps,createToggleGroup:()=>co,createTypingIndicator:()=>kr,createVoiceProvider:()=>No,createWidgetHostLayout:()=>Da,createXmlParser:()=>Pi,default:()=>Nh,defaultActionHandlers:()=>Hr,defaultJsonActionParser:()=>Wa,defaultMentionFilter:()=>Dl,defaultParseRules:()=>lp,detectColorScheme:()=>fa,directivePostprocessor:()=>cg,ensureAskUserQuestionSheet:()=>rs,escapeHtml:()=>_n,extractComponentDirectiveFromMessage:()=>Pl,fileToImagePart:()=>Jg,formatEnrichedContext:()=>Lh,generateAssistantMessageId:()=>Do,generateCodeSnippet:()=>zh,generateMessageId:()=>zg,generateStableSelector:()=>cp,generateUserMessageId:()=>as,getActiveTheme:()=>_o,getColorScheme:()=>qi,getDisplayText:()=>Vg,getHeaderLayout:()=>Ld,getImageParts:()=>Kg,getPreset:()=>Oh,hasComponentDirective:()=>Ba,hasImages:()=>Wi,headerLayouts:()=>cl,highContrastPlugin:()=>Hh,initAgentWidget:()=>rp,isAskUserQuestionMessage:()=>oo,isComponentDirectiveType:()=>rh,isDockedMountMode:()=>Mt,isSuggestRepliesMessage:()=>br,isVoiceSupported:()=>ca,isWebMcpToolName:()=>ko,isWelcomeVisible:()=>Go,latestAgentSuggestions:()=>wi,listRegisteredStreamAnimations:()=>sm,loadMarkdownParsers:()=>Bc,markdownPostprocessor:()=>Dc,mergeWithDefaults:()=>ds,normalizeContent:()=>qg,normalizeMediaType:()=>Lo,onMarkdownParsersReady:()=>Zr,parseAskUserQuestionPayload:()=>ro,parseSuggestRepliesPayload:()=>Gc,parseWidgetPreferenceSlice:()=>Kd,pickBestVoice:()=>ls,pluginRegistry:()=>Ia,reducedMotionPlugin:()=>Wh,registerStreamAnimationPlugin:()=>om,removeAskUserQuestionSheet:()=>Io,renderComponentDirective:()=>Ll,renderLoadingIndicatorWithFallback:()=>Id,renderLucideIcon:()=>se,resolveArtifactDisplay:()=>_c,resolveArtifactDisplayMode:()=>$n,resolveConfigPreferences:()=>Ra,resolveDockConfig:()=>rn,resolveSanitizer:()=>es,resolveTokens:()=>Ui,resolveWelcomeConfig:()=>go,stripWebMcpPrefix:()=>yi,themeToCssVariables:()=>zi,unregisterStreamAnimationPlugin:()=>rm,validateImageFile:()=>Yg,validateTheme:()=>dd});module.exports=ab(fA);var og=require("marked"),rg=Qs(require("dompurify"),1);var Qr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:CA,load:ib,provide:lb,getSync:Hc}=Qr({fallbackImport:()=>Promise.resolve().then(()=>(eg(),Zu))}),mi=new Set,tg=()=>{let e=[...mi];mi.clear();for(let t of e)try{t()}catch{}};var Bc=()=>{let e=Hc();return e?Promise.resolve(e):ib().then(t=>(tg(),t))},Zr=e=>Hc()?()=>{}:(mi.add(e),Bc().catch(()=>{}),()=>{mi.delete(e)}),ng=e=>{lb(e),tg()},no=Hc;ng({Marked:og.Marked,DOMPurify:rg.default});var cb=e=>{if(e)return e},Zs=e=>{let t=null;return n=>{let o=no();if(!o)return _n(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=cb(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},hr=e=>e?Zs({markedOptions:e.options,renderer:e.renderer}):Zs(),db=Zs(),Dc=e=>db(e),_n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ag=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),sg=e=>`%%FORM_PLACEHOLDER_${e}%%`,ig=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=sg(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=sg(t.length);return t.push({token:s,type:r}),s}),n},lg=e=>{let t=hr(e);return n=>{let o=[],r=ig(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${ag(i)}"></div>`;s=s.replace(p,c)}),s}},cg=e=>{let t=[],n=ig(e,t),o=Dc(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${ag(s)}"></div>`;o=o.replace(a,p)}),o};var pb={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"]},ub=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Oc=()=>{let e=null;return t=>{let n=no();if(!n)return _n(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!ub.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,pb)}},es=e=>e===!1?null:typeof e=="function"?e:Oc();var dg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,pg=e=>e.includes("|"),ug=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())},gb=e=>`| ${e.join(" | ")} |`,fb=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,mb=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),gg=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!pg(r)||dg.test(r)||!dg.test(s))continue;let a=ug(r).length;if(a<1)continue;let i=fb(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()===""||!pg(d))break;let c=gb(mb(ug(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
- `):e};var fg="var(--persona-md-table-scroll-fade, 24px)",mg=new WeakSet;function yg(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function hg(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":fg),e.style.setProperty("--persona-fade-r",r<=1?"0px":fg)}function Nc(e){mg.has(e)||(mg.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&hg(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(hg)}var Wn="webmcp:",Fc=new Map,bg=e=>{Fc.clear();for(let t of e){let n=t.title?.trim();n&&Fc.set(t.name,n)}},ea=e=>Fc.get(yi(e)),hi={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},vg=null;function Cg(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}:${hb(t.join(""))}`}function xg(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function hb(e){let t=xg(e,0).toString(36),n=xg(e,2654435761).toString(36);return`${t}.${n}`}var ts=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return hi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}bg(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=bb(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return In("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let x=typeof document<"u"&&!!document.modelContext;return In(x?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=yi(t),a;try{a=await r.getTools()}catch(x){let C=x instanceof Error?x.message:String(x);return In(`Failed to read WebMCP registry: ${C}`)}bg(a);let i=a.find(x=>x.name===s);if(!i)return In(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return In(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return In("Aborted by cancel()");let p=ea(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return In("User declined the tool call.");if(o?.aborted)return In("Aborted by cancel()");let c=new AbortController,g=!1,b=setTimeout(()=>{g=!0,c.abort()},this.timeoutMs),f=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",f,{once:!0}));try{let x=await r.executeTool(i,wb(n),{signal:c.signal});return vb(x)}catch(x){if(g)return In(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return In("Aborted by cancel()");let C=x instanceof Error?x.message:String(x);return In(C)}finally{clearTimeout(b),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}(vg?await vg():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){hi.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,hi.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??xb;try{return await n(t)}catch(o){return hi.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=>yb(t,o))}},yi=e=>e.startsWith(Wn)?e.slice(Wn.length):e,ko=e=>e.startsWith(Wn),yb=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bb=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},vb=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:Ab(t)}]}},In=e=>({isError:!0,content:[{type:"text",text:e}]}),xb=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Cb(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var Sx=Object.create;var Yl=Object.defineProperty;var Ax=Object.getOwnPropertyDescriptor;var Tx=Object.getOwnPropertyNames;var Ex=Object.getPrototypeOf,Mx=Object.prototype.hasOwnProperty;var Us=(e,t)=>()=>(e&&(t=e(e=0)),t);var Jl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})},eh=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Tx(t))!Mx.call(e,r)&&r!==n&&Yl(e,r,{get:()=>t[r],enumerable:!(o=Ax(t,r))||o.enumerable});return e};var Jr=(e,t,n)=>(n=e!=null?Sx(Ex(e)):{},eh(t||!e||!e.__esModule?Yl(n,"default",{value:e,enumerable:!0}):n,e)),kx=e=>eh(Yl({},"__esModule",{value:!0}),e);var oh={};Jl(oh,{DOMPurify:()=>nh.default,Marked:()=>th.Marked});var th,nh,rh=Us(()=>{"use strict";th=require("marked"),nh=Jr(require("dompurify"),1)});var ti,uu=Us(()=>{"use strict";ti=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;this.sampleRate=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function _S(e){return e.replace(/\/+$/,"")}async function NS(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 bc,by=Us(()=>{"use strict";uu();bc=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 ti(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${_S(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!i.ok||!i.body)throw new Error(await NS(i));let l=i.body.getReader();for(;;){let{done:d,value:u}=await l.read();if(t!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;u&&u.byteLength>0&&r.enqueue(u)}r.markStreamEnd()}catch(r){if(t!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var vc,vy=Us(()=>{"use strict";vc=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Cy={};Jl(Cy,{FallbackSpeechEngine:()=>vc,RuntypeSpeechEngine:()=>bc});var wy=Us(()=>{"use strict";by();vy()});var Sy={};Jl(Sy,{createReconnectController:()=>$S});function $S(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},i=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},d=()=>{i()},u=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},p=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},g=b=>new Promise(x=>{n=x,o=setTimeout(()=>{o=null,n=null,x()},b)}),y=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let x=!1;for(let H of e.getMessages())H.streaming&&(H.streaming=!1,x=!0);let T=e.buildErrorContent("Connection lost and the response could not be resumed.");T?e.appendMessage({id:`reconnect-failed-${b?.executionId??e.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):x&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},m=async()=>{let b=e.config.reconnect?.backoffMs??FS,x=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<x;){t+=1,e.setStatus("resuming");let H=e.getResumable(),_=H.lastEventId,P=new AbortController;e.setAbortController(P),e.emitReconnect({phase:"resuming",handle:H,attempt:t});let A=null;try{let B=await T({executionId:H.executionId,after:H.lastEventId,signal:P.signal});B&&B.ok&&B.body&&(A=B.body)}catch{A=null}if(P.signal.aborted)return;if(A){let B=e.getMessages().find(W=>W.id===H.assistantMessageId)?.content,R=typeof B=="string"?B:"";try{await e.resumeConnect(A,H.assistantMessageId,R)}catch{}if(P.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:H});return}e.getResumable().lastEventId!==_&&(t=0)}if(e.getResumable()&&t<x&&(e.setStatus("paused"),await g(b[Math.min(t-1,b.length-1)]??1e3),P.signal.aborted))return}e.getResumable()&&y()};return{begin(){t=0,u(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,p()},wake:s}}var FS,Ay=Us(()=>{"use strict";FS=[1e3,2e3,4e3,8e3,8e3]});var XM={};Jl(XM,{ASK_USER_QUESTION_CLIENT_TOOL:()=>lu,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>au,ASK_USER_QUESTION_TOOL_NAME:()=>ga,AgentWidgetClient:()=>es,AgentWidgetSession:()=>oi,AttachmentManager:()=>os,BrowserSpeechEngine:()=>hr,DEFAULT_COMPONENTS:()=>Su,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>xc,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Hn,DEFAULT_PALETTE:()=>wu,DEFAULT_SEMANTIC:()=>xu,DEFAULT_WIDGET_CONFIG:()=>Xe,HistoryProviderError:()=>Un,PRESETS:()=>Bg,PRESET_FULLSCREEN:()=>Wg,PRESET_MINIMAL:()=>Rg,PRESET_SHOP:()=>Ig,ReadAloudController:()=>ns,SUGGEST_REPLIES_CLIENT_TOOL:()=>oc,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>ru,SUGGEST_REPLIES_TOOL_NAME:()=>eo,THEME_ZONES:()=>jy,VERSION:()=>uo,WEBMCP_TOOL_PREFIX:()=>Zn,WebMcpBridge:()=>Ks,accessibilityPlugin:()=>aC,animationsPlugin:()=>lC,applyFeaturePreferences:()=>ug,applyThemeVariables:()=>rs,attachHeaderToContainer:()=>ds,brandPlugin:()=>cC,buildComposer:()=>ps,buildDefaultHeader:()=>ju,buildHeader:()=>jo,buildHeaderWithLayout:()=>fi,buildMinimalHeader:()=>zu,builtInClientToolsForDispatch:()=>Xs,canonicalArtifactDisplayMode:()=>Cn,collectEnrichedPageContext:()=>sC,componentRegistry:()=>to,createActionManager:()=>Ga,createAgentExperience:()=>vd,createAskUserQuestionBubble:()=>$h,createBestAvailableVoiceProvider:()=>yc,createBubbleWithLayout:()=>Db,createCSATFeedback:()=>hd,createComboButton:()=>Dc,createComponentMiddleware:()=>Ov,createComponentStreamParser:()=>gd,createDefaultSanitizer:()=>Yp,createDemoCarousel:()=>kC,createDirectivePostprocessor:()=>uh,createDropdownMenu:()=>as,createFlexibleJsonStreamParser:()=>qh,createIconButton:()=>rt,createImagePart:()=>fc,createJsonStreamParser:()=>pc,createLabelButton:()=>Fo,createLocalStorageAdapter:()=>pd,createMarkdownProcessor:()=>ca,createMarkdownProcessorFromConfig:()=>Xr,createMessageActions:()=>Gu,createNPSFeedback:()=>yd,createPlainTextParser:()=>cc,createPlugin:()=>uC,createRegexJsonParser:()=>dc,createRovingTablist:()=>ad,createSlashCommandsSource:()=>Gv,createSplitButton:()=>Oc,createStandardBubble:()=>mi,createStaticMentionSource:()=>Kv,createTextPart:()=>go,createTheme:()=>Ea,createThemeObserver:()=>ai,createToggleGroup:()=>$o,createTypingIndicator:()=>us,createVoiceProvider:()=>mr,createWidgetHostLayout:()=>Ja,createXmlParser:()=>uc,default:()=>mC,defaultActionHandlers:()=>bs,defaultJsonActionParser:()=>Ka,defaultMentionFilter:()=>wd,defaultParseRules:()=>Lg,detectColorScheme:()=>Ma,directivePostprocessor:()=>gh,ensureAskUserQuestionSheet:()=>Js,escapeHtml:()=>co,extractComponentDirectiveFromMessage:()=>md,fileToImagePart:()=>Yh,formatEnrichedContext:()=>iC,generateAssistantMessageId:()=>fr,generateCodeSnippet:()=>wC,generateMessageId:()=>fy,generateStableSelector:()=>Hg,generateUserMessageId:()=>ei,getActiveTheme:()=>yr,getColorScheme:()=>Mc,getDisplayText:()=>gc,getHeaderLayout:()=>Uu,getImageParts:()=>Gh,getPreset:()=>fC,hasComponentDirective:()=>Ya,hasImages:()=>Zs,headerLayouts:()=>Kc,highContrastPlugin:()=>pC,initAgentWidget:()=>Eg,isAskUserQuestionMessage:()=>Oo,isComponentDirectiveType:()=>Bv,isDockedMountMode:()=>Ct,isHistoryProviderError:()=>my,isSuggestRepliesMessage:()=>Zr,isVoiceSupported:()=>wa,isWebMcpToolName:()=>ir,isWelcomeVisible:()=>Ar,latestAgentSuggestions:()=>rc,listRegisteredStreamAnimations:()=>kb,loadMarkdownParsers:()=>Kp,markdownPostprocessor:()=>Gp,mergeWithDefaults:()=>ii,normalizeContent:()=>Kh,normalizeMediaType:()=>ar,onMarkdownParsersReady:()=>qs,parseAskUserQuestionPayload:()=>Do,parseSuggestRepliesPayload:()=>iu,parseWidgetPreferenceSlice:()=>pg,pickBestVoice:()=>ni,pluginRegistry:()=>Va,reducedMotionPlugin:()=>dC,registerStreamAnimationPlugin:()=>Eb,removeAskUserQuestionSheet:()=>dr,renderComponentDirective:()=>fd,renderLoadingIndicatorWithFallback:()=>Ku,renderLucideIcon:()=>de,resolveArtifactDisplay:()=>Qp,resolveArtifactDisplayMode:()=>po,resolveConfigPreferences:()=>qa,resolveDockConfig:()=>wn,resolveSanitizer:()=>Vs,resolveTokens:()=>Tc,resolveWelcomeConfig:()=>zo,stripWebMcpPrefix:()=>Zl,themeToCssVariables:()=>Ec,unregisterStreamAnimationPlugin:()=>Mb,validateImageFile:()=>Jh,validateTheme:()=>Au});module.exports=kx(XM);var ah=require("marked"),lh=Jr(require("dompurify"),1);var lo=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:p=>{o=p,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:p=>{r=p},getSync:()=>r}};var{setLoader:sk,load:Px,provide:Lx,getSync:Vp}=lo({fallbackImport:()=>Promise.resolve().then(()=>(rh(),oh))}),Xl=new Set,sh=()=>{let e=[...Xl];Xl.clear();for(let t of e)try{t()}catch{}};var Kp=()=>{let e=Vp();return e?Promise.resolve(e):Px().then(t=>(sh(),t))},qs=e=>Vp()?()=>{}:(Xl.add(e),Kp().catch(()=>{}),()=>{Xl.delete(e)}),ih=e=>{Lx(e),sh()},Bo=Vp;ih({Marked:ah.Marked,DOMPurify:lh.default});var Hx=e=>{if(e)return e},ca=e=>{let t=null;return n=>{let o=Bo();if(!o)return co(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=Hx(e?.renderer);i&&t.use({renderer:i})}return t.parse(n)}},Xr=e=>e?ca({markedOptions:e.options,renderer:e.renderer}):ca(),Ix=ca(),Gp=e=>Ix(e),co=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),dh=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),ch=e=>`%%FORM_PLACEHOLDER_${e}%%`,ph=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=ch(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=ch(t.length);return t.push({token:s,type:r}),s}),n},uh=e=>{let t=Xr(e);return n=>{let o=[],r=ph(n,o),s=t(r);return o.forEach(({token:i,type:l})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${dh(l)}"></div>`;s=s.replace(d,p)}),s}},gh=e=>{let t=[],n=ph(e,t),o=Gp(n);return t.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${dh(s)}"></div>`;o=o.replace(i,d)}),o};var Rx={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"]},Wx=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Yp=()=>{let e=null;return t=>{let n=Bo();if(!n)return co(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!Wx.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Rx)}},Vs=e=>e===!1?null:typeof e=="function"?e:Yp();var fh=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mh=e=>e.includes("|"),hh=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())},Bx=e=>`| ${e.join(" | ")} |`,Ox=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Dx=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),yh=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!mh(r)||fh.test(r)||!fh.test(s))continue;let i=hh(r).length;if(i<1)continue;let l=Ox(i);t[o+1]!==l&&(t[o+1]=l,n=!0);let d=o+2;for(;d<t.length;d++){let u=t[d];if(u.trim()===""||!mh(u))break;let p=Bx(Dx(hh(u),i));t[d]!==p&&(t[d]=p,n=!0)}o=d-1}return n?t.join(`
3
+ `):e};var bh="var(--persona-md-table-scroll-fade, 24px)",vh=new WeakSet;function wh(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Ch(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":bh),e.style.setProperty("--persona-fade-r",r<=1?"0px":bh)}function Jp(e){vh.has(e)||(vh.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Ch(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Ch)}var Zn="webmcp:",Xp=new Map,xh=e=>{Xp.clear();for(let t of e){let n=t.title?.trim();n&&Xp.set(t.name,n)}},da=e=>Xp.get(Zl(e)),Ql={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Sh=null;function Th(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}:${_x(t.join(""))}`}function Ah(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function _x(e){let t=Ah(e,0).toString(36),n=Ah(e,2654435761).toString(36);return`${t}.${n}`}var Ks=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return Ql.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}xh(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},i=Fx(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Qn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Qn(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=Zl(t),i;try{i=await r.getTools()}catch(b){let x=b instanceof Error?b.message:String(b);return Qn(`Failed to read WebMCP registry: ${x}`)}xh(i);let l=i.find(b=>b.name===s);if(!l)return Qn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Qn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Qn("Aborted by cancel()");let d=da(s),u={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(u))return Qn("User declined the tool call.");if(o?.aborted)return Qn("Aborted by cancel()");let p=new AbortController,g=!1,y=setTimeout(()=>{g=!0,p.abort()},this.timeoutMs),m=()=>p.abort();o&&(o.aborted?p.abort():o.addEventListener("abort",m,{once:!0}));try{let b=await r.executeTool(l,Ux(n),{signal:p.signal});return $x(b)}catch(b){if(g)return Qn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Qn("Aborted by cancel()");let x=b instanceof Error?b.message:String(b);return Qn(x)}finally{clearTimeout(y),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Sh?await Sh():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ql.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,Ql.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??jx;try{return await n(t)}catch(o){return Ql.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=>Nx(t,o))}},Zl=e=>e.startsWith(Zn)?e.slice(Zn.length):e,ir=e=>e.startsWith(Zn),Nx=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Fx=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},$x=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:qx(t)}]}},Qn=e=>({isError:!0,content:[{type:"text",text:e}]}),jx=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=zx(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)},Cb=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)}},wb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ab=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function on(e){return e==="card"?"collapsed":e}function Lo(e){return e.split(";",1)[0].trim().toLowerCase()}function Sb(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(Lo(r)===t)return{mode:on(s),selector:Lo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(Lo(r)===o)return{mode:on(s),selector:o}}function _c(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:on(o.files),matchedBy:{type:"files"}};let i=t.file.mimeType?Lo(t.file.mimeType):void 0,p=i?Sb(o.files.byMediaType,i):void 0;if(i&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:i,selector:p.selector}};if(o.files.default)return{mode:on(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:on(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:on(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let a=t.presentation?.preferredMode;return a?{mode:on(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:on(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function $n(e,t){return _c(e,t).mode}function ta(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Tb="agent_",Eb="flow_";function wg(e){return e.startsWith(Tb)?{kind:"agentId",agentId:e}:e.startsWith(Eb)?{kind:"flowId",flowId:e}:null}function Ag(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=wg(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=wg(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Po=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var Sg=()=>document.createDocumentFragment(),ke=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Hn=(...e)=>e.filter(Boolean).join(" ");var oa="ask_user_question",na=8,ns="data-persona-ask-sheet-for",Mb="Other",kb="Other\u2026",Eg="Type your own answer here",Mg="Send",Lb="Next",Pb="Back",Rb="Submit all",Ib="Skip",Wb=3,$c="data-ask-current-index",jc="data-ask-question-count",kg="data-ask-answers",Uc="data-ask-grouped",Lg="data-ask-layout",Hb=e=>e.layout==="pills"?"pills":"rows",Bb=e=>e.getAttribute(Lg)==="pills"?"pills":"rows",Tg=!1,Pg=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===oa,bi=e=>e?.features?.askUserQuestion??{},ro=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,Po.parse)(r,Po.STR|Po.OBJ|Po.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ra=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>na&&!Tg&&(Tg=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${na}.`)),t.slice(0,na)},Db=e=>ra(e)[0]??null,Ob=(e,t)=>ra(e)[t]??null,Rg=(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))},Ig=(e,t,n)=>{if(e!=="rows")return null;let o=y("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=y("span","persona-ask-row-check");o.appendChild(r)}else{let r=y("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Nb=(e,t,n,o)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=y("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=Ig(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Fb=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},_b=(e,t,n,o)=>{let s=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Wb;c++)s.appendChild(Fb(o));return s}if(p.forEach((c,g)=>{s.appendChild(Nb(c,g,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Mb:kb;if(o==="rows"){let g=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(p.length)),g.setAttribute("data-ask-other-row","true");let b=y("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=t.freeTextPlaceholder??Eg,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(f),g.appendChild(b);let x=Ig(o,a,p.length);x&&g.appendChild(x),s.appendChild(g)}else{let g=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??c,s.appendChild(g)}}return s},Wg=(e,t)=>{let o=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Eg,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=y("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Mg,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},$b=e=>{let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Mg,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},jb=(e,t,n)=>{let o=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=y("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Pb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Ib,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Rb:n.nextLabel??Lb,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},yr=e=>{let t=e.getAttribute(kg);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Hg=(e,t)=>{e.setAttribute(kg,JSON.stringify(t))},Cn=e=>{let t=Number(e.getAttribute($c)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ub=(e,t)=>{e.setAttribute($c,String(Math.max(0,Math.floor(t))))},os=e=>{let t=Number(e.getAttribute(jc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Ro=e=>e.getAttribute(Uc)==="true",zb=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},qb=(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)))},vi=(e,t)=>{let{payload:n}=ro(t),o=ra(n),r=yr(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},Bg=e=>{let t=yr(e),n=Cn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},Dg=e=>{if(!Ro(e))return;let t=yr(e),n=Cn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},zc=(e,t,n)=>{let o=bi(n),r=Bb(e),{payload:s,complete:a}=ro(t),i=Ro(e),p=Cn(e),d=os(e),c=i?Ob(s,p):Db(s),g=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let R=typeof c?.question=="string"?c.question:"";x.textContent=R,x.classList.toggle("persona-ask-question-skeleton",!R&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let R=_b(c,o,a,r);C.replaceWith(R)}if(r!=="rows"){let R=e.querySelector('[data-ask-free-text-row="true"]');R&&R.replaceWith(Wg(o,r))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!S?e.appendChild($b(o)):(!g||i)&&S&&S.remove(),e.setAttribute("data-multi-select",g?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(i){let R=jb(p,d,o);k?k.replaceWith(R):e.appendChild(R)}else k&&k.remove();Bg(e),Dg(e)},Vb=(e,t,n)=>{let o=bi(t),r=Hb(o),s=e.toolCall.id,a=ra(n),i=Math.max(1,a.length),p=i>1,d=zb(e,a),c=p?qb(e,i):0,g=y("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ns,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(jc,String(i)),g.setAttribute($c,String(c)),g.setAttribute(Uc,p?"true":"false"),g.setAttribute(Lg,r),Hg(g,d),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Rg(g,o);let b=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let x=y("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",b.appendChild(x),g.appendChild(b);let S=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),g.appendChild(S),r!=="rows"&&g.appendChild(Wg(o,r)),zc(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Kb=(e,t,n)=>{let{payload:o}=ro(t),r=Math.max(1,ra(o).length);r>os(e)&&(e.setAttribute(jc,String(r)),r>1&&!Ro(e)&&e.setAttribute(Uc,"true")),zc(e,t,n)},Og=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=bi(t);Rg(n,o);let r=y("span","persona-ask-stub-label"),{complete:s}=ro(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},rs=(e,t,n)=>{if(!n||!oo(e)||bi(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${ns}]`).forEach(d=>{d.getAttribute(ns)!==r&&d.remove()});let a=n.querySelector(`[${ns}="${Pg(r)}"]`);if(a){Kb(a,e,t);return}let{payload:i}=ro(e),p=Vb(e,t,i);n.appendChild(p)},Io=(e,t)=>{if(!e)return;let n=t?`[${ns}="${Pg(t)}"]`:`[${ns}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},qc=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Wo=(e,t)=>{let n=yr(e),o=Cn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Hg(e,n),Bg(e),Dg(e)},xi=(e,t,n,o)=>{let r=os(e),s=Math.max(0,Math.min(r-1,o));Ub(e,s),zc(e,t,n)};var Bn="suggest_replies";var Vc={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Ci={name:Bn,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:Vc,origin:"sdk",annotations:{readOnlyHint:!0}},Kc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),br=e=>e.variant==="tool"&&e.toolCall?.name===Bn,Gc=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let i=r.trim();return i?[i]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},wi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!br(n))continue;let o=Gc(n.toolCall?.args);return o.length>0?o:null}return null},Ng=new Set,Gb=(e,t,n)=>{let o=`${e}:${t}:${n}`;Ng.has(o)||(Ng.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Ho=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=a=>{let i=t?.[a],p=n?.[a];i===void 0||p===void 0||i!==p&&Gb(a,p,i)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var Jc={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:na,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},Yc={name:oa,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:Jc,origin:"sdk",annotations:{readOnlyHint:!0}},ss=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Yc),Ho(e).expose&&t.push(Ci),t};var so=require("partial-json"),Ai=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Bo=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)}},Jb=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Fg=e=>e.status==="complete"?Jb(e):e.status==="pending"?"Waiting":"",Yb=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 _g=e=>e.status==="complete"?Yb(e):"Using tool...",Si=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},aa=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 Si(t)},Ti=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Si(t)},Xc=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=aa(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ei=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&sa(o,n.slice(s,a.index),[]),a[1]!==void 0?sa(o,a[1],["bold"]):a[2]!==void 0?sa(o,a[2],["italic"]):a[3]!==void 0&&sa(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&sa(o,n.slice(s),[]),o},sa=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Xb=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let 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 r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ia=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Mi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ki=()=>{let e=Xb();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)}},Li=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,so.parse)(n,so.STR|so.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Ai(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Ai(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Ai(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ai(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=(0,so.parse)(s,so.STR|so.OBJ),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Pi=()=>{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 jg="4.17.0";var ao=jg;var Zb="https://api.runtype.com/v1/dispatch",Ri="https://api.runtype.com";function ev(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var Qc=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 tv(e){switch(e){case"json":return Li;case"regex-json":return ki;case"xml":return Pi;default:return Mi}}var Ug=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function nv(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Ug(n);if(!Ug(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ia(e);return ia(t)!==null&&a===null?t:e}var vr=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??Zb,this.headers={"Content-Type":"application/json","X-Persona-Version":ao,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??tv(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 ts(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Ag(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(Qc).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ao},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(i.status===429){let g=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Ri}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?Cg(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,g;for(let b=0;;b++){if(g=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Ri}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:g}=await this.sendWithClientToolsDiff(a,d,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:i,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&g(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Qc).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(Qc).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...c!==void 0&&{partId:c}};return o.current=g,r(g),g},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,g=M=>{let W=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,h=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,H=M.tools?M.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...M,reasoning:W,toolCall:h,tools:H}},b=M=>{if(M.role!=="assistant"||M.variant)return!0;let W=Array.isArray(M.contentParts)&&M.contentParts.length>0,h=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||W||h||!!M.stopReason},f=M=>{b(M)&&n({type:"message",message:g(M)})},x=null,C=null,S={current:null},k={current:null},R=null,E="",P=new Map,B=new Map,N=new Map,$=new Map,z=new Map,q={lastId:null,byStep:new Map},X={lastId:null,byCall:new Map},A=M=>{if(M==null)return null;try{return String(M)}catch{return null}},J=M=>A(M.stepId??M.step_id??M.step??M.parentId??M.flowStepId??M.flow_step_id),Z=M=>A(M.callId??M.call_id??M.requestId??M.request_id??M.toolCallId??M.tool_call_id??M.stepId??M.step_id),ce=o,Y=!1,he=()=>{if(x)return x;let M,W="",h=R;return!Y&&ce?(M=ce,Y=!0,W=r??""):ce&&h?M=`${ce}_${h}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:M,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},f(x),x},te=(M,W)=>{q.lastId=W,M&&q.byStep.set(M,W)},be=(M,W)=>{let h=M.reasoningId??M.id,H=J(M);if(h){let D=String(h);return te(H,D),D}if(H){let D=q.byStep.get(H);if(D)return q.lastId=D,D}if(q.lastId&&!W)return q.lastId;if(!W)return null;let I=`reason-${c()}`;return te(H,I),I},ee=M=>{let W=$.get(M);if(W)return W;let h={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"streaming",chunks:[]}};return $.set(M,h),f(h),h},ge=(M,W)=>{X.lastId=W,M&&X.byCall.set(M,W)},ne=new Set,me=new Map,ve=new Set,ye=new Map,De=M=>{if(!M)return!1;let W=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return W==="emit_artifact_markdown"||W==="emit_artifact_component"},at=(M,W)=>{let h=M.toolId??M.id,H=Z(M);if(h){let D=String(h);return ge(H,D),D}if(H){let D=X.byCall.get(H);if(D)return X.lastId=D,D}if(X.lastId&&!W)return X.lastId;if(!W)return null;let I=`tool-${c()}`;return ge(H,I),I},je=M=>{let W=z.get(M);if(W)return W;let h={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:M,status:"pending"}};return z.set(M,h),f(h),h},Ke=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let W=Number(M);if(!Number.isNaN(W)&&Number.isFinite(W))return W;let h=Date.parse(M);if(!Number.isNaN(h))return h}return Date.now()},Pe=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},$e=new Map,Ae=new Map,ie=new Map,Ie=(M,W,h)=>{let H=ie.get(M);H||(H=[],ie.set(M,H));let I=0,D=H.length;for(;I<D;){let j=I+D>>>1;H[j].seq<W?I=j+1:D=j}H[I]?.seq===W?H[I]={seq:W,text:h}:H.splice(I,0,{seq:W,text:h});let K="";for(let j=0;j<H.length;j++)K+=H[j].text;return K},dt=(M,W)=>{let h=Pe(W),H=Ae.get(M.id),I=nv(H,h);M.rawContent=I;let D=$e.get(M.id),K=ue=>{let Re=M.content??"";ue.trim()!==""&&(Re.trim().length===0||ue.startsWith(Re)||ue.trimStart().startsWith(Re.trim()))&&(M.content=ue)},j=()=>{if(D){let ue=D.close?.();ue instanceof Promise&&ue.catch(()=>{})}$e.delete(M.id),Ae.delete(M.id),M.streaming=!1,f(M)};if(!D){K(h),j();return}let G=ia(I);if(G!==null&&G.trim()!==""){K(G),j();return}let pe=ue=>{let Re=typeof ue=="string"?ue:ue?.text??null;if(Re!==null&&Re.trim()!=="")return Re;let qe=D.getExtractedText();return qe!==null&&qe.trim()!==""?qe:h},ze;try{ze=D.processChunk(I)}catch{K(h),j();return}if(ze instanceof Promise){ze.then(ue=>{K(pe(ue)),j()}).catch(()=>{K(h),j()});return}K(pe(ze)),j()},tt=null,xt=(M,W,h,H)=>{M.rawContent=W,$e.has(M.id)||$e.set(M.id,this.createStreamParser());let I=$e.get(M.id),D=W.trim().startsWith("{")||W.trim().startsWith("[");if(D&&Ae.set(M.id,W),I.__isPlainTextParser===!0){M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M);return}let j=I.processChunk(W);if(j instanceof Promise)j.then(G=>{let pe=typeof G=="string"?G:G?.text??null;pe!==null&&pe.trim()!==""?(M.content=pe,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}).catch(()=>{M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M)});else{let G=typeof j=="string"?j:j?.text??null;G!==null&&G.trim()!==""?(M.content=G,f(M)):!D&&!W.trim().startsWith("<")&&(M.content=H!==void 0?W:M.content+h,Ae.delete(M.id),$e.delete(M.id),M.rawContent=void 0,f(M))}},An=(M,W)=>{let h=W??M.content;if(h==null||h===""){M.streaming=!1,f(M);return}let I=Ae.get(M.id)??Pe(h);M.rawContent=I;let D=$e.get(M.id),K=null,j=!1;if(D&&(K=D.getExtractedText(),K===null&&(K=ia(I)),K===null)){let G=D.processChunk(I);G instanceof Promise?(j=!0,G.then(pe=>{let ze=typeof pe=="string"?pe:pe?.text??null;ze!==null&&(M.content=ze,M.streaming=!1,$e.delete(M.id),Ae.delete(M.id),f(M))}).catch(()=>{})):K=typeof G=="string"?G:G?.text??null}if(!j){K!==null&&K.trim()!==""?M.content=K:Ae.has(M.id)||(M.content=Pe(h));let G=$e.get(M.id);if(G){let pe=G.close?.();pe instanceof Promise&&pe.catch(()=>{}),$e.delete(M.id)}Ae.delete(M.id),M.streaming=!1,f(M)}},Sn=(M,W,h)=>{let H=B.get(M);if(H)return H;let I={id:`nested-${W}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:W}};return B.set(M,I),f(I),I},et=[],Le,xe=new Map,nt=0,Ee="agent",we=!1,ae=null,Se=null,Tn=new Map,oe=this.config.iterationDisplay??"separate";for(Le=()=>{for(let M=0;M<et.length;M++){let W=et[M].payloadType,h=et[M].payload;if(!we&&Ee!=="flow"&&typeof h.stepType=="string"&&(Ee="flow"),W==="reasoning_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I),Sn(H,I,"reasoning");continue}let D=be(h,!0)??`reason-${c()}`,K=ee(D);K.reasoning=K.reasoning??{id:D,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Ke(h.startedAt??h.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(W==="reasoning_delta"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let j=B.get(H),G=h.reasoningText??h.text??h.delta??"";G&&h.hidden!==!0&&j.reasoning&&(j.reasoning.chunks.push(String(G)),f(j));continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=ee(I);D.reasoning=D.reasoning??{id:I,status:"streaming",chunks:[]},D.reasoning.startedAt=D.reasoning.startedAt??Ke(h.startedAt??h.timestamp);let K=h.reasoningText??h.text??h.delta??"";if(K&&h.hidden!==!0){let j=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(j!==void 0){let G=Ie(I,j,String(K));D.reasoning.chunks=[G]}else D.reasoning.chunks.push(String(K))}if(D.reasoning.status=h.done?"complete":"streaming",h.done){D.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let j=D.reasoning.startedAt??Date.now();D.reasoning.durationMs=Math.max(0,(D.reasoning.completedAt??Date.now())-j)}D.streaming=D.reasoning.status!=="complete",f(D)}else if(W==="reasoning_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)&&B.has(H)){let G=B.get(H);if(G.reasoning){let pe=typeof h.text=="string"?h.text:"";pe&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(pe),G.reasoning.status="complete",G.streaming=!1,f(G)}P.delete(H),B.delete(H);continue}let I=be(h,!1)??be(h,!0)??`reason-${c()}`,D=typeof h.text=="string"?h.text:"";!$.get(I)&&(D||h.scope==="loop")&&ee(I);let K=$.get(I);if(K?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(K.reasoning.scope=h.scope),D&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(D),K.reasoning.status="complete",K.reasoning.completedAt=Ke(h.completedAt??h.timestamp);let G=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-G),K.streaming=!1,f(K)}let j=J(h);j&&q.byStep.delete(j)}else if(W==="tool_start"){x&&(x.streaming=!1,f(x),x=null),typeof h.iteration=="number"&&(nt=h.iteration);let H=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??at(h,!0)??`tool-${c()}`,I=h.toolName??h.name;if(De(I)){ne.add(H);continue}ge(Z(h),H);let D=je(H),K=D.toolCall??{id:H,status:"pending"};K.name=I??K.name,K.status="running",h.parameters!==void 0?K.args=h.parameters:h.args!==void 0&&(K.args=h.args),K.startedAt=K.startedAt??Ke(h.startedAt??h.timestamp),K.completedAt=void 0,K.durationMs=void 0,D.toolCall=K,D.streaming=!0,h.executionId&&(D.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(D)}else if(W==="tool_output_delta"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H))continue;let I=je(H),D=I.toolCall??{id:H,status:"running"};D.startedAt=D.startedAt??Ke(h.startedAt??h.timestamp);let K=h.text??h.delta??h.message??"";K&&(D.chunks=D.chunks??[],D.chunks.push(String(K))),D.status="running",I.toolCall=D,I.streaming=!0;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I)}else if(W==="tool_complete"){let H=at(h,!1)??at(h,!0)??`tool-${c()}`;if(ne.has(H)){ne.delete(H);continue}let I=je(H),D=I.toolCall??{id:H,status:"running"};D.status="complete",h.result!==void 0&&(D.result=h.result),typeof h.duration=="number"&&(D.duration=h.duration),D.completedAt=Ke(h.completedAt??h.timestamp);let K=h.duration??h.executionTime;if(typeof K=="number")D.durationMs=K;else{let pe=D.startedAt??Date.now();D.durationMs=Math.max(0,(D.completedAt??Date.now())-pe)}I.toolCall=D,I.streaming=!1;let j=h.agentContext;(j||h.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:j?.executionId??h.executionId,iteration:j?.iteration??h.iteration}),f(I);let G=Z(h);G&&X.byCall.delete(G)}else if(W==="await"&&h.toolName){let H=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,I=H??h.toolId??`local-${c()}`,D=je(I),K=h.toolName,j=h.origin==="webmcp"&&!ko(K)?`webmcp:${K}`:K,G=ko(j),pe=D.toolCall??{id:I,status:"pending"};pe.name=j,pe.args=h.parameters,pe.status=G?"running":"complete",pe.chunks=pe.chunks??[],pe.startedAt=pe.startedAt??Ke(h.startedAt??h.timestamp??h.awaitedAt),G?(pe.completedAt=void 0,pe.duration=void 0,pe.durationMs=void 0):pe.completedAt=pe.completedAt??pe.startedAt,D.toolCall=pe,D.streaming=!1,D.agentMetadata={...D.agentMetadata,executionId:h.executionId??D.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(D)}else if(W==="text_start"){let H=typeof h.id=="string"?h.id:null,I=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(H&&I){P.set(H,I);continue}let D=x;D&&(Ee==="flow"?(An(D),tt=D):(D.streaming=!1,f(D)),x=null),R=typeof h.id=="string"?h.id:R,E=""}else if(W==="text_delta"){let H=typeof h.id=="string"?h.id:null,I=H?P.get(H):void 0;if(H&&I){let K=typeof h.delta=="string"?h.delta:"",j=(N.get(H)??"")+K;if(N.set(H,j),j.trim()==="")continue;let G=Sn(H,I);G.agentMetadata={...G.agentMetadata,executionId:h.executionId,parentToolId:I},xt(G,j,K,void 0);continue}if(R=typeof h.id=="string"?h.id:R,Ee==="flow"){let K=typeof h.delta=="string"?h.delta:"";if(E+=K,E.trim()==="")continue;let j=he();j.agentMetadata={executionId:h.executionId,iteration:h.iteration},xt(j,E,K,void 0),C=j;continue}let D=he();D.content+=h.delta??"",D.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:ae??void 0,agentName:Se?.agentName},C=D,f(D)}else if(W==="text_complete"){let H=typeof h.id=="string"?h.id:null;if(H&&P.has(H)){let D=B.get(H);D&&An(D),P.delete(H),N.delete(H),B.delete(H);continue}let I=x;I&&(Ee==="flow"?(An(I),tt=I):((I.content??"")===""&&typeof h.text=="string"&&(I.content=h.text),I.streaming=!1,f(I)),x=null),R=null,E=""}else if(W==="step_complete"){let H=h.stepType,I=h.executionType;if(H==="tool"||I==="context")continue;if(h.success===!1){let D=h.error,K=typeof D=="string"&&D!==""?D:D!=null&&typeof D=="object"&&Reflect.has(D,"message")?String(D.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let j=x;j&&j.streaming&&(j.streaming=!1,f(j)),n({type:"status",status:"idle"});continue}{let D=tt;tt=null;let K=h.stopReason,j=h.result?.response;if(D)K&&(D.stopReason=K),j!=null?dt(D,j):D.streaming!==!1&&($e.delete(D.id),Ae.delete(D.id),D.streaming=!1,f(D));else{let G=j!=null&&j!=="";if(G||K){let pe=he();K&&(pe.stopReason=K),G?An(pe,j):(pe.streaming=!1,f(pe))}}continue}}else if(W==="execution_start")Ee=h.kind==="flow"?"flow":"agent",we=!0,Ee==="agent"&&(Se={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ke(h.startedAt)});else if(W==="turn_start"){let H=typeof h.iteration=="number"?h.iteration:nt;if(H!==nt){if(Se&&(Se.currentIteration=H),oe==="separate"&&H>1){let I=x;I&&(I.streaming=!1,f(I),Tn.set(H-1,I),x=null)}nt=H}ae=typeof h.id=="string"?h.id:null,C=null}else if(W==="tool_input_delta"){let H=h.toolCallId??X.lastId;if(H){let I=z.get(H);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(h.delta??""),f(I))}}else{if(W==="tool_input_complete")continue;if(W==="turn_complete"){let H=h.stopReason,I=x??C;if(H&&I!==null){let D=h.id;(!D||I.agentMetadata?.turnId===D)&&(I.stopReason=H,f(I))}ae===h.id&&(ae=null)}else if(W==="media_start"){let H=String(h.id);xe.set(H,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(W==="media_delta"){let H=xe.get(String(h.id));H&&typeof h.delta=="string"&&H.parts.push(h.delta)}else if(W==="media_complete"){let H=String(h.id),I=xe.get(H);xe.delete(H);let D=(typeof h.mediaType=="string"?h.mediaType:void 0)??I?.mediaType??"application/octet-stream",K=typeof h.data=="string"?h.data:void 0,j=typeof h.url=="string"?h.url:I&&I.parts.length>0?I.parts.join(""):void 0,G=null;if(K)G={type:"media",data:K,mediaType:D};else if(j){let Re=D.toLowerCase();G={type:Re==="image"||Re.startsWith("image/")?"image-url":"file-url",url:j,mediaType:D}}let pe=h.toolCallId??I?.toolCallId,ze=G?[G]:[],ue=[];for(let Re of ze){if(!Re||typeof Re!="object")continue;let qe=Re,Ue=typeof qe.type=="string"?qe.type:void 0,Be=typeof qe.mediaType=="string"?qe.mediaType.toLowerCase():"",Te=null,ot="";if(Ue==="media"){let Tt=typeof qe.data=="string"?qe.data:void 0;if(!Tt)continue;ot=Be.length>0?Be:"application/octet-stream",Te=`data:${ot};base64,${Tt}`}else if(Ue==="image-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else if(Ue==="file-url"){let Tt=typeof qe.url=="string"?qe.url:void 0;if(!Tt)continue;ot=Be,Te=Tt}else continue;if(Te)if(Ue==="image-url"||ot.startsWith("image/"))ue.push({type:"image",image:Te,...ot.includes("/")?{mimeType:ot}:{}});else if(ot.startsWith("audio/"))ue.push({type:"audio",audio:Te,mimeType:ot});else if(ot.startsWith("video/"))ue.push({type:"video",video:Te,mimeType:ot});else{let Tt=ot||"application/octet-stream";ue.push({type:"file",data:Te,mimeType:Tt,filename:ev(Tt)})}}if(ue.length>0){let Re=c(),qe=pe,Be={id:`agent-media-${typeof qe=="string"&&qe.length>0?`${qe}-${Re}`:String(Re)}`,role:"assistant",content:"",contentParts:ue,createdAt:new Date().toISOString(),streaming:!1,sequence:Re,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:nt}};f(Be);let Te=x;Te&&(Te.streaming=!1,f(Te)),x=null,S.current=null}}else if(W==="execution_complete"){let H=h.kind??Ee;H==="agent"&&Se&&(Se.status=h.success?"complete":"error",Se.completedAt=Ke(h.completedAt),Se.stopReason=h.stopReason);let I=x;I&&(H==="flow"&&I.streaming!==!1?An(I):(I.streaming=!1,f(I)),x=null),R=null,E="",tt=null,n({type:"status",status:"idle",terminal:!0})}else if(W==="execution_error"){let H=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(W!=="ping"){if(W==="approval_start"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="step_await"&&h.awaitReason==="approval_required"){let H=h.approvalId??`approval-${c()}`,I={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(I)}else if(W==="approval_complete"){let H=h.approvalId;if(H){let D={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:h.decision??"approved",agentId:Se?.agentId??"virtual",executionId:h.executionId??Se?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(D)}}else if(W==="artifact_start"||W==="artifact_delta"||W==="artifact_update"||W==="artifact_complete"){if(W==="artifact_start"){let H=h.artifactType,I=String(h.id),D=typeof h.title=="string"?h.title:void 0,K=h.file,j;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(j={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:I,artifactType:H,title:D,component:typeof h.component=="string"?h.component:void 0,...j?{file:j}:{}});let G=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(ye.set(I,{markdown:"",title:D,file:j,...G?{props:G}:{}}),!ve.has(I)){ve.add(I);let pe=$n(this.config.features?.artifacts,{artifactType:H,...j?{file:j}:{}}),ze=typeof h.component=="string"?h.component:void 0,ue={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ta(pe,{artifactId:I,title:D,artifactType:H,status:"streaming",...j?{file:j}:{},...ze?{component:ze}:{}})};me.set(I,ue),f(ue)}}else if(W==="artifact_delta"){let H=String(h.id),I=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:H,artDelta:I});let D=ye.get(H);D&&(D.markdown+=I)}else if(W==="artifact_update"){let H=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:H,component:typeof h.component=="string"?h.component:void 0});let I=ye.get(String(h.id));I&&(I.props={...I.props??{},...H})}else if(W==="artifact_complete"){let H=String(h.id);n({type:"artifact_complete",id:H});let I=me.get(H);if(I){I.streaming=!1;try{let D=JSON.parse(I.rawContent??"{}");if(D.props){D.props.status="complete";let K=ye.get(H);K?.markdown&&(D.props.markdown=K.markdown),K?.file&&(D.props.file=K.file),D.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(D.props.componentProps=K.props)}I.rawContent=JSON.stringify(D)}catch{}ye.delete(H),f(I),me.delete(H)}}}else if(W==="transcript_insert"){let H=h.message;if(!H||typeof H!="object")continue;let I=String(H.id??`msg-${c()}`),D=H.role,j={id:I,role:D==="user"?"user":D==="system"?"system":"assistant",content:typeof H.content=="string"?H.content:"",rawContent:typeof H.rawContent=="string"?H.rawContent:void 0,createdAt:typeof H.createdAt=="string"?H.createdAt:new Date().toISOString(),streaming:H.streaming===!0,...typeof H.variant=="string"?{variant:H.variant}:{},sequence:c()};if(f(j),j.rawContent)try{let pe=JSON.parse(j.rawContent)?.props?.artifactId;typeof pe=="string"&&ve.add(pe)}catch{}x=null,S.current=null,$e.delete(I),Ae.delete(I)}else if(W==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let H=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(H)});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}else if(W==="step_error"||W==="dispatch_error"||W==="flow_error"){let H=null;if(h.error instanceof Error)H=h.error;else if(W==="dispatch_error"){let I=h.message??h.error;I!=null&&I!==""&&(H=new Error(String(I)))}else{let I=h.error;typeof I=="string"&&I!==""?H=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(H=new Error(String(I.message??I)))}if(H){n({type:"error",error:H});let I=x;I&&I.streaming&&(I.streaming=!1,f(I)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:M,value:W}=await s.read();if(M)break;i+=a.decode(W,{stream:!0});let h=i.split(`
8
+ ${e.description}`:"");return window.confirm(n)},zx=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)}},Ux=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},qx=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Cn(e){return e==="card"?"collapsed":e}function ar(e){return e.split(";",1)[0].trim().toLowerCase()}function Vx(e,t){if(!e)return;let n=Object.entries(e);for(let[r,s]of n)if(ar(r)===t)return{mode:Cn(s),selector:ar(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,s]of n)if(ar(r)===o)return{mode:Cn(s),selector:o}}function Qp(e,t){let n=e?.display,o=typeof n=="string"?{default:n}:n??{};if(t.file&&o.files){if(typeof o.files=="string")return{mode:Cn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?ar(t.file.mimeType):void 0,d=l?Vx(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:Cn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:Cn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=o.byType?.[t.artifactType];if(s)return{mode:Cn(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let i=t.presentation?.preferredMode;return i?{mode:Cn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:Cn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function po(e,t){return Qp(e,t).mode}function pa(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Kx="agent_",Gx="flow_";function Eh(e){return e.startsWith(Kx)?{kind:"agentId",agentId:e}:e.startsWith(Gx)?{kind:"flowId",flowId:e}:null}function Mh(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let u=Eh(l);if(u)return u;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=t?.[i];if(!d)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Eh(n);if(r)return r;let s=t?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var lr=require("partial-json");var v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var kh=()=>document.createDocumentFragment(),ge=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,i]of Object.entries(t.attrs))o.setAttribute(s,i);if(t.style){let s=o.style,i=t.style;for(let l of Object.keys(i)){let d=i[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},jn=(...e)=>e.filter(Boolean).join(" ");var ga="ask_user_question",ua=8,Gs="data-persona-ask-sheet-for",Yx="Other",Jx="Other\u2026",Lh="Type your own answer here",Hh="Send",Xx="Next",Qx="Back",Zx="Submit all",eS="Skip",tS=3,Zp="data-ask-current-index",eu="data-ask-question-count",Ih="data-ask-answers",tu="data-ask-grouped",Rh="data-ask-layout",nS=e=>e.layout==="pills"?"pills":"rows",oS=e=>e.getAttribute(Rh)==="pills"?"pills":"rows",Ph=!1,Wh=e=>e.replace(/["\\]/g,"\\$&"),Oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ga,ec=e=>e?.features?.askUserQuestion??{},Do=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,lr.parse)(r,lr.STR|lr.OBJ|lr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},fa=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ua&&!Ph&&(Ph=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ua}.`)),t.slice(0,ua)},rS=e=>fa(e)[0]??null,sS=(e,t)=>fa(e)[t]??null,Bh=(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))},Oh=(e,t,n)=>{if(e!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},iS=(e,t,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,i.appendChild(l),e.description){let u=v("span","persona-ask-row-description");u.textContent=e.description,i.appendChild(u)}s.appendChild(i);let d=Oh(n,o,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},aS=e=>{let n=v("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},lS=(e,t,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!e?.multiSelect,d=(Array.isArray(e?.options)?e.options:[]).filter(p=>p&&typeof p.label=="string"&&p.label.length>0);if(d.length===0&&!n){for(let p=0;p<tS;p++)s.appendChild(aS(o));return s}if(d.forEach((p,g)=>{s.appendChild(iS(p,g,o,i))}),e?.allowFreeText!==!1){let p=o==="rows"?Yx:Jx;if(o==="rows"){let g=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(d.length)),g.setAttribute("data-ask-other-row","true");let y=v("span","persona-ask-row-content"),m=document.createElement("input");m.type="text",m.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",m.placeholder=t.freeTextPlaceholder??Lh,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",t.freeTextLabel??p),y.appendChild(m),g.appendChild(y);let b=Oh(o,i,d.length);b&&g.appendChild(b),s.appendChild(g)}else{let g=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=t.freeTextLabel??p,s.appendChild(g)}}return s},Dh=(e,t)=>{let o=v("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=e.freeTextPlaceholder??Lh,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??Hh,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},cS=e=>{let t=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??Hh,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},dS=(e,t,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Qx,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??eS,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=e===t-1;return l.textContent=d?n.submitAllLabel??Zx:n.nextLabel??Xx,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Qr=e=>{let t=e.getAttribute(Ih);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},_h=(e,t)=>{e.setAttribute(Ih,JSON.stringify(t))},zn=e=>{let t=Number(e.getAttribute(Zp)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},pS=(e,t)=>{e.setAttribute(Zp,String(Math.max(0,Math.floor(t))))},Ys=e=>{let t=Number(e.getAttribute(eu)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},cr=e=>e.getAttribute(tu)==="true",uS=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},gS=(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)))},tc=(e,t)=>{let{payload:n}=Do(t),o=fa(n),r=Qr(e),s={},i=new Set;return o.forEach((l,d)=>{let u=typeof l?.question=="string"?l.question:"";u&&(i.has(u)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${u}"; later answer wins.`),i.add(u),Object.prototype.hasOwnProperty.call(r,d)&&(s[u]=r[d]))}),s},Nh=e=>{let t=Qr(e),n=zn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let u=d.getAttribute("data-option-label")??"",p=r.has(u);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let i=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Fh=e=>{if(!cr(e))return;let t=Qr(e),n=zn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=e.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},nu=(e,t,n)=>{let o=ec(n),r=oS(e),{payload:s,complete:i}=Do(t),l=cr(e),d=zn(e),u=Ys(e),p=l?sS(s,d):rS(s),g=!!p?.multiSelect,y=e.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${d+1}/${u}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let _=typeof p?.question=="string"?p.question:"";b.textContent=_,b.classList.toggle("persona-ask-question-skeleton",!_&&!i)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let _=lS(p,o,i,r);x.replaceWith(_)}if(r!=="rows"){let _=e.querySelector('[data-ask-free-text-row="true"]');_&&_.replaceWith(Dh(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!T?e.appendChild(cS(o)):(!g||l)&&T&&T.remove(),e.setAttribute("data-multi-select",g?"true":"false");let H=e.querySelector('[data-ask-nav-row="true"]');if(l){let _=dS(d,u,o);H?H.replaceWith(_):e.appendChild(_)}else H&&H.remove();Nh(e),Fh(e)},fS=(e,t,n)=>{let o=ec(t),r=nS(o),s=e.toolCall.id,i=fa(n),l=Math.max(1,i.length),d=l>1,u=uS(e,i),p=d?gS(e,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Gs,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",e.id),g.setAttribute(eu,String(l)),g.setAttribute(Zp,String(p)),g.setAttribute(tu,d?"true":"false"),g.setAttribute(Rh,r),_h(g,u),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Bh(g,o);let y=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",y.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",y.appendChild(b),g.appendChild(y);let T=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),r!=="rows"&&g.appendChild(Dh(o,r)),nu(g,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},mS=(e,t,n)=>{let{payload:o}=Do(t),r=Math.max(1,fa(o).length);r>Ys(e)&&(e.setAttribute(eu,String(r)),r>1&&!cr(e)&&e.setAttribute(tu,"true")),nu(e,t,n)},$h=(e,t)=>{let n=v("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ec(t);Bh(n,o);let r=v("span","persona-ask-stub-label"),{complete:s}=Do(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Js=(e,t,n)=>{if(!n||!Oo(e)||ec(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Gs}]`).forEach(u=>{u.getAttribute(Gs)!==r&&u.remove()});let i=n.querySelector(`[${Gs}="${Wh(r)}"]`);if(i){mS(i,e,t);return}let{payload:l}=Do(e),d=fS(e,t,l);n.appendChild(d)},dr=(e,t)=>{if(!e)return;let n=t?`[${Gs}="${Wh(t)}"]`:`[${Gs}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},ou=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),pr=(e,t)=>{let n=Qr(e),o=zn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,_h(e,n),Nh(e),Fh(e)},nc=(e,t,n,o)=>{let r=Ys(e),s=Math.max(0,Math.min(r-1,o));pS(e,s),nu(e,t,n)};var eo="suggest_replies";var ru={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},oc={name:eo,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:ru,origin:"sdk",annotations:{readOnlyHint:!0}},su=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Zr=e=>e.variant==="tool"&&e.toolCall?.name===eo,iu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},rc=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Zr(n))continue;let o=iu(n.toolCall?.args);return o.length>0?o:null}return null},jh=new Set,hS=(e,t,n)=>{let o=`${e}:${t}:${n}`;jh.has(o)||(jh.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},ur=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=i=>{let l=t?.[i],d=n?.[i];l===void 0||d===void 0||l!==d&&hS(i,d,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,s=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var au={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ua,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},lu={name:ga,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:au,origin:"sdk",annotations:{readOnlyHint:!0}},Xs=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(lu),ur(e).expose&&t.push(oc),t};var _o=require("partial-json"),sc=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),gr=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)}},yS=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},zh=e=>e.status==="complete"?yS(e):e.status==="pending"?"Waiting":"",bS=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 Uh=e=>e.status==="complete"?bS(e):"Using tool...",ic=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ha=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 ic(t)},ac=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ic(t)},cu=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=ha(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},lc=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&ma(o,n.slice(s,i.index),[]),i[1]!==void 0?ma(o,i[1],["bold"]):i[2]!==void 0?ma(o,i[2],["italic"]):i[3]!==void 0&&ma(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&ma(o,n.slice(s),[]),o},ma=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},vS=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ya=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},cc=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},dc=()=>{let e=vS();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)}},pc=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=(0,_o.parse)(n,_o.STR|_o.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?sc(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=sc(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},qh=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=l=>typeof l=="string"?sc(l):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?sc(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let l=(0,_o.parse)(s,_o.STR|_o.OBJ),d=r(l);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},uc=()=>{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 Vh="4.18.0";var uo=Vh;var Qs="[Image]";function Kh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gc(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Zs(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Gh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function go(e){return{type:"text",text:e}}function fc(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Yh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Jh(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 Xh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],wS=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],No=[...Xh,...wS];function xS(e){return Xh.includes(e)||e.startsWith("image/")}function mc(e){return xS(e.type)}function Qh(e,t,n){return{type:"file",data:e,mimeType:t,filename:n}}async function Zh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;mc(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function ey(e,t=No,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function SS(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ty(e,t){let n=SS(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var AS=["user","assistant","system"],TS=0;function ny(e){if(typeof e!="string"||e==="")return null;let t=Date.parse(e);return Number.isNaN(t)?null:t}function hc(e){return typeof e=="string"?e:void 0}function ES(e){if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"text":return typeof t.text=="string"?go(t.text):null;case"image":return typeof t.image=="string"?fc(t.image,{mimeType:hc(t.mimeType),alt:hc(t.alt)}):null;case"file":return typeof t.data=="string"&&typeof t.mimeType=="string"&&typeof t.filename=="string"?Qh(t.data,t.mimeType,t.filename):null;case"audio":return typeof t.audio=="string"?{type:"audio",audio:t.audio,...hc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;case"video":return typeof t.video=="string"?{type:"video",video:t.video,...hc(t.mimeType)!==void 0&&{mimeType:t.mimeType}}:null;default:return null}}function MS(e,t){let n=ny(t),o=e.map(i=>ny(i.timestamp)),r=new Array(e.length),s=0;for(;s<o.length;){let i=o[s];if(i!==null){r[s]=i,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,u=s>0?r[s-1]:null,p=l+1<o.length?o[l+1]:null,g=p!==null&&n!==null?Math.min(p,n):p??n;for(let y=0;y<d;y+=1)r[s+y]=g!==null?g-(d-y):u!==null?u+y+1:TS+y;s=l+1}return r.map(i=>new Date(i).toISOString())}function oy(e,t){let n=MS(e,t?.beforeCreatedAt),o=[];return e.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!AS.includes(r.role))return;let i=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:i,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:i,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:i,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(ES).filter(p=>p!==null),u=gc(d);o.push({id:r.id,role:i,content:u||(Zs(d)?Qs:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:i,content:"",createdAt:l})}),o}function ba(e){let t=e.content;if(typeof t!="string"||t==="")return;let n=e.contentParts??e.llmContent??e.rawContent??t;if(!(typeof n=="string"&&n===t))return t}function va(e,t){let n=new Map;for(let o of e)n.set(o.id,o);for(let o of t)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),i=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(i)&&s!==i)return s-i;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var kS="https://api.runtype.com/v1/dispatch",ry="https://api.runtype.com",De=class extends Error{constructor(t,n,o){super(n),this.name="HistoryClientError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},sy=32768,du=49152,iy=e=>{let t=e??{},n=typeof t.targetId=="string"?t.targetId:typeof t.flowId=="string"?t.flowId:null;return{id:typeof t.id=="string"?t.id:"",title:typeof t.title=="string"?t.title:"",targetId:n,preview:typeof t.preview=="string"?t.preview:null,messageCount:typeof t.messageCount=="number"?t.messageCount:0,createdAt:typeof t.createdAt=="string"?t.createdAt:"",updatedAt:typeof t.updatedAt=="string"?t.updatedAt:""}},ay=e=>"reason"in e?e.reason:void 0,ly="The identity proof was not admitted; account history is unavailable",cy="The identity proof was rejected",dy="The request carried no visitor credential",py="The stored visitor belongs to a different signed-in user",uy=(e,t)=>e instanceof De&&e.code===t;function PS(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var pu=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 LS(e){switch(e){case"json":return pc;case"regex-json":return dc;case"xml":return uc;default:return cc}}var gy=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function HS(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=gy(n);if(!gy(o))return e;if(!r||o===n||o.startsWith(n))return t;let i=ya(e);return ya(t)!==null&&i===null?t:e}var es=class{constructor(t={},n={}){this.config=t;this.historyInternals=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??kS,this.headers={"Content-Type":"application/json","X-Persona-Version":uo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??LS(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 Ks(t.webmcp):null}updateConfig(t){this.config=t}setHistoryInternals(t){this.historyInternals=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=Mh(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ry}getClientApiUrl(t){return`${this.clientApiBase()}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let t=this.historyInternals.visitorStore;return t?(await t.ready,await t.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let t of[...this.historyAvailabilitySubscribers])t(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(t){return this.historyIdentitySubscribers.add(t),()=>{this.historyIdentitySubscribers.delete(t)}}subscribeHistoryAvailability(t){return this.historyAvailabilitySubscribers.add(t),this.historyUnavailable&&t(!1),()=>{this.historyAvailabilitySubscribers.delete(t)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let t=this.historyIdentityStatus;return t?.state==="browser_only"?t:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(t){let n=this.getHistoryIdentityStatus(),o=n.state===t.state&&ay(n)===ay(t);if(this.historyIdentityStatus=t,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(t);for(let r of[...this.historyIdentitySubscribers])r(t)}}async createClientSession(t){let n=this.isHistoryCapable()&&!t.omitVisitorFields,o=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),s=r.agentId??r.flowId,i=n?t.conversationId:void 0,l={token:this.config.clientToken,...s&&{flowId:s},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&t.identityProof?{identityProof:t.identityProof}:{},...i?{conversationId:i}:t.storedSessionId?{sessionId:t.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":uo},body:JSON.stringify(l)});if(!d.ok){let p=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&p.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),i)throw new De("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...t,omitVisitorFields:!0})}throw n&&d.status===401&&p.error==="visitor_required"?new De("visitor_required","Visitor credential no longer resolves"):i&&d.status===404?new De("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):d.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let u=await d.json();return u.visitor?.token&&await this.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId??u.flow?.id?{targetId:u.targetId??u.flow?.id}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let t=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(t&&n)try{let o=await this.createClientSession({conversationId:t});return this.finishInit(o,t,!1)}catch(o){if(!uy(o,"not_found")&&!uy(o,"visitor_required"))throw o;return this.ordinaryInit(t,!0)}return this.ordinaryInit(t,!1)}async ordinaryInit(t,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(t,n)):this.doOrdinaryInit(t,n)}async doOrdinaryInit(t,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,t,n)}async reinitWithProof(t){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:t}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(t){if(!t.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return t;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:t.sessionId})}catch{return t}finally{this.claimInFlight=!1}}finishInit(t,n,o){let r=t.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(t.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),t}prepared(t){let n=!1;return{session:t,commit:()=>{n||(n=!0,this.clientSession=t,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(t,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new De("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new De("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:t,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let t=await this.createClientSession({});return this.prepared(t)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(t){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":uo},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:n})}historyUrl(t,n){let o=new URLSearchParams;for(let[s,i]of Object.entries(n))i===void 0||i===""||o.set(s,String(i));let r=o.toString();return`${this.clientApiBase()}/v1/client/${t}${r?`?${r}`:""}`}resolveHistoryScope(t){if(t)return t;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(t,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new De("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(t.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new De("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(t,n,o){if(t.visitor?.endUserId!=null)return t;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new De("proof_not_admitted",ly);return r}async readErrorCode(t){let n=await t.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(t,n,o){let r=t.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new De("invalid_identity_proof",cy);if(r.includes("visitor token required"))throw new De("visitor_token_missing",dy);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new De("visitor_identity_mismatch",py);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new De("unauthorized",t||"History request was not authorized")}async historyErrorFor(t,n){let o=await this.readErrorCode(t);if(t.status===404)return new De("not_found","Conversation not found");if(t.status===429){let r=Number.parseInt(t.headers.get("Retry-After")??"",10);return new De("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(t.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new De("proof_not_admitted",ly);if(t.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new De("invalid_identity_proof",cy)):r.includes("visitor token required")?new De("visitor_token_missing",dy):r.includes("visitor_identity_mismatch")?new De("visitor_identity_mismatch",py):new De("unauthorized",o||"History request was not authorized")}return new De("request_failed",o||`History request failed (${t.status})`)}commitIdentityAcknowledgement(t,n,o){let r=t?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new De("identity_contract_violation","Server reported an ignored identity proof on a success response"):new De("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new De("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(t,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let i=this.historyInternals.visitorStore,l=!1;for(;;){let d=i?.revision()??0,u=await this.readVisitorToken();if(!u&&!n.visitorTokenOptional)throw new De("visitor_token_missing","No visitor credential is stored for this browser");let p=await fetch(this.historyUrl(t,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":uo,...u?{"X-Visitor-Token":u}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(p.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(p),s,o);continue}if(!p.ok)throw await this.historyErrorFor(p,o);let g=p.headers.get("X-History-Identity-Status"),y=await p.json().catch(()=>{});if(i&&i.revision()!==d)throw new De("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(g,s!==null,o),y}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new De("history_disabled","Visitor history is disabled for this surface")}async listConversations(t){let n=await this.historyFetch("conversations",{method:"GET",query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(iy),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:iy(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(t,n){this.assertHistoryUsable();let o=0;for(let d of n){let u=d.displayContent.length;if(u>sy)throw new De("payload_too_large",`displayContent exceeds the ${sy} character limit`);o+=u}if(o>du)throw new De("payload_too_large",`Display projection batch exceeds the ${du} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,i=await this.historyFetch(`conversations/${encodeURIComponent(t)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=du,trackIdentity:!1}),l=typeof i?.conversationRevision=="string"?i.conversationRevision:null;return l&&this.clientSession?.conversationId===t&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(t,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(t)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(t){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...t?.targetId!==void 0?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let p=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:p}),p}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([p])=>p!=="sessionId"&&p!=="session_id")):void 0,i=this.isHistoryCapable(),l={sessionId:o.sessionId,messages:t.messages.filter(pu).map(p=>{let g=i?ba(p):void 0;return{id:p.id,role:p.role,content:p.contentParts??p.llmContent??p.rawContent??p.content,...g!==void 0&&{displayContent:g}}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:d,commit:u}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,p=>{let g={...l,...p};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":uo},body:JSON.stringify(g),signal:t.signal})});if(!d.ok){let p=await d.json().catch(()=>({error:"Chat request failed"}));if(d.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let y=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:y}),y}if(d.status===429){let y=new Error(p.hint||"Message limit reached for this session.");throw n({type:"error",error:y}),y}if(d.status===410&&p.error==="conversation_deleted"){let y=new De("conversation_deleted","This conversation was deleted");throw n({type:"error",error:y}),y}let g=new Error(p.error||"Failed to send message");throw n({type:"error",error:g}),g}if(!d.body){let p=new Error("No response body received");throw n({type:"error",error:p}),p}u(),n({type:"status",status:"connected"});try{await this.streamResponse(d.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!(r instanceof De)&&!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let o=`${this.clientApiBase()}/v1/agents/${t.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),i=s?Th(n):void 0,l=this.clientToolsFingerprintSessionId===t,d=s&&l&&this.lastSentClientToolsFingerprint===i,u=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,g;for(let y=0;;y++){if(g=await o({...s&&(p||!d)&&n?{clientTools:n}:{},...u?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&y===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:u&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ry}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(d.sessionId=i),r&&i){let u=[...Xs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:p,commit:g}=await this.sendWithClientToolsDiff(i,u,y=>{let m={...d,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(s,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return p.ok&&g(),p}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(pu).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Xs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);return i&&(r.context=i),r}async buildPayload(t){let n=t.slice().filter(pu).sort((l,d)=>{let u=new Date(l.createdAt).getTime(),p=new Date(d.createdAt).getTime();return u-p}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,d]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=d);let s=[...Xs(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(t);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let d=l;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let d=p=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return o.current=g,r(g),g},u=p=>o.current?o.current:d(p);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(i.current=l.partId);let p=u(l.partId);l.partId!==void 0&&!p.partId&&(p.partId=l.partId),p.content+=l.text,r(p)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),i=new TextDecoder,l="",d=Date.now(),u=0,p=()=>d+u++,g=F=>{let te=F.reasoning?{...F.reasoning,chunks:[...F.reasoning.chunks]}:void 0,w=F.toolCall?{...F.toolCall,chunks:F.toolCall.chunks?[...F.toolCall.chunks]:void 0}:void 0,S=F.tools?F.tools.map(I=>({...I,chunks:I.chunks?[...I.chunks]:void 0})):void 0;return{...F,reasoning:te,toolCall:w,tools:S}},y=F=>{if(F.role!=="assistant"||F.variant)return!0;let te=Array.isArray(F.contentParts)&&F.contentParts.length>0,w=typeof F.rawContent=="string"&&F.rawContent.trim()!=="";return typeof F.content=="string"&&F.content.trim()!==""||te||w||!!F.stopReason},m=F=>{y(F)&&n({type:"message",message:g(F)})},b=null,x=null,T={current:null},H={current:null},_=null,P="",A=new Map,B=new Map,R=new Map,W=new Map,U=new Map,V={lastId:null,byStep:new Map},Z={lastId:null,byCall:new Map},j=F=>{if(F==null)return null;try{return String(F)}catch{return null}},X=F=>j(F.stepId??F.step_id??F.step??F.parentId??F.flowStepId??F.flow_step_id),ue=F=>j(F.callId??F.call_id??F.requestId??F.request_id??F.toolCallId??F.tool_call_id??F.stepId??F.step_id),xe=o,Ce=!1,ye=()=>{if(b)return b;let F,te="",w=_;return!Ce&&xe?(F=xe,Ce=!0,te=r??""):xe&&w?F=`${xe}_${w}`:F=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:F,role:"assistant",content:te,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(b),b},oe=(F,te)=>{V.lastId=te,F&&V.byStep.set(F,te)},le=(F,te)=>{let w=F.reasoningId??F.id,S=X(F);if(w){let L=String(w);return oe(S,L),L}if(S){let L=V.byStep.get(S);if(L)return V.lastId=L,L}if(V.lastId&&!te)return V.lastId;if(!te)return null;let I=`reason-${p()}`;return oe(S,I),I},ae=F=>{let te=W.get(F);if(te)return te;let w={id:`reason-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:F,status:"streaming",chunks:[]}};return W.set(F,w),m(w),w},M=(F,te)=>{Z.lastId=te,F&&Z.byCall.set(F,te)},ee=new Set,pe=new Map,we=new Set,me=new Map,Se=F=>{if(!F)return!1;let te=F.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Le=(F,te)=>{let w=F.toolId??F.id,S=ue(F);if(w){let L=String(w);return M(S,L),L}if(S){let L=Z.byCall.get(S);if(L)return Z.lastId=L,L}if(Z.lastId&&!te)return Z.lastId;if(!te)return null;let I=`tool-${p()}`;return M(S,I),I},He=F=>{let te=U.get(F);if(te)return te;let w={id:`tool-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:F,status:"pending"}};return U.set(F,w),m(w),w},Qe=F=>{if(typeof F=="number"&&Number.isFinite(F))return F;if(typeof F=="string"){let te=Number(F);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let w=Date.parse(F);if(!Number.isNaN(w))return w}return Date.now()},Oe=F=>{if(typeof F=="string")return F;if(F==null)return"";try{return JSON.stringify(F)}catch{return String(F)}},We=new Map,tt=new Map,ve=new Map,Ne=(F,te,w)=>{let S=ve.get(F);S||(S=[],ve.set(F,S));let I=0,L=S.length;for(;I<L;){let Y=I+L>>>1;S[Y].seq<te?I=Y+1:L=Y}S[I]?.seq===te?S[I]={seq:te,text:w}:S.splice(I,0,{seq:te,text:w});let O="";for(let Y=0;Y<S.length;Y++)O+=S[Y].text;return O},ft=(F,te)=>{let w=Oe(te),S=tt.get(F.id),I=HS(S,w);F.rawContent=I;let L=We.get(F.id),O=ce=>{let dt=F.content??"";ce.trim()!==""&&(dt.trim().length===0||ce.startsWith(dt)||ce.trimStart().startsWith(dt.trim()))&&(F.content=ce)},Y=()=>{if(L){let ce=L.close?.();ce instanceof Promise&&ce.catch(()=>{})}We.delete(F.id),tt.delete(F.id),F.streaming=!1,m(F)};if(!L){O(w),Y();return}let Q=ya(I);if(Q!==null&&Q.trim()!==""){O(Q),Y();return}let G=ce=>{let dt=typeof ce=="string"?ce:ce?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let st=L.getExtractedText();return st!==null&&st.trim()!==""?st:w},K;try{K=L.processChunk(I)}catch{O(w),Y();return}if(K instanceof Promise){K.then(ce=>{O(G(ce)),Y()}).catch(()=>{O(w),Y()});return}O(G(K)),Y()},Ae=null,Fe=(F,te,w,S)=>{F.rawContent=te,We.has(F.id)||We.set(F.id,this.createStreamParser());let I=We.get(F.id),L=te.trim().startsWith("{")||te.trim().startsWith("[");if(L&&tt.set(F.id,te),I.__isPlainTextParser===!0){F.content=S!==void 0?te:F.content+w,tt.delete(F.id),We.delete(F.id),F.rawContent=void 0,m(F);return}let Y=I.processChunk(te);if(Y instanceof Promise)Y.then(Q=>{let G=typeof Q=="string"?Q:Q?.text??null;G!==null&&G.trim()!==""?(F.content=G,m(F)):!L&&!te.trim().startsWith("<")&&(F.content=S!==void 0?te:F.content+w,tt.delete(F.id),We.delete(F.id),F.rawContent=void 0,m(F))}).catch(()=>{F.content=S!==void 0?te:F.content+w,tt.delete(F.id),We.delete(F.id),F.rawContent=void 0,m(F)});else{let Q=typeof Y=="string"?Y:Y?.text??null;Q!==null&&Q.trim()!==""?(F.content=Q,m(F)):!L&&!te.trim().startsWith("<")&&(F.content=S!==void 0?te:F.content+w,tt.delete(F.id),We.delete(F.id),F.rawContent=void 0,m(F))}},at=(F,te)=>{let w=te??F.content;if(w==null||w===""){F.streaming=!1,m(F);return}let I=tt.get(F.id)??Oe(w);F.rawContent=I;let L=We.get(F.id),O=null,Y=!1;if(L&&(O=L.getExtractedText(),O===null&&(O=ya(I)),O===null)){let Q=L.processChunk(I);Q instanceof Promise?(Y=!0,Q.then(G=>{let K=typeof G=="string"?G:G?.text??null;K!==null&&(F.content=K,F.streaming=!1,We.delete(F.id),tt.delete(F.id),m(F))}).catch(()=>{})):O=typeof Q=="string"?Q:Q?.text??null}if(!Y){O!==null&&O.trim()!==""?F.content=O:tt.has(F.id)||(F.content=Oe(w));let Q=We.get(F.id);if(Q){let G=Q.close?.();G instanceof Promise&&G.catch(()=>{}),We.delete(F.id)}tt.delete(F.id),F.streaming=!1,m(F)}},Gt=(F,te,w)=>{let S=B.get(F);if(S)return S;let I={id:`nested-${te}-${F}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...w?{variant:w}:{},...w==="reasoning"?{reasoning:{id:F,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return B.set(F,I),m(I),I},Ut=[],Vn,et=new Map,nt=0,wt="agent",Zt=!1,vo=null,Rt=null,Ko=new Map,vs=this.config.iterationDisplay??"separate";for(Vn=()=>{for(let F=0;F<Ut.length;F++){let te=Ut[F].payloadType,w=Ut[F].payload;if(!Zt&&wt!=="flow"&&typeof w.stepType=="string"&&(wt="flow"),te==="reasoning_start"){let S=typeof w.id=="string"?w.id:null,I=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(S&&I){A.set(S,I),Gt(S,I,"reasoning");continue}let L=le(w,!0)??`reason-${p()}`,O=ae(L);O.reasoning=O.reasoning??{id:L,status:"streaming",chunks:[]},O.reasoning.startedAt=O.reasoning.startedAt??Qe(w.startedAt??w.timestamp),O.reasoning.completedAt=void 0,O.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(O.reasoning.scope=w.scope),O.streaming=!0,O.reasoning.status="streaming",m(O)}else if(te==="reasoning_delta"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)&&B.has(S)){let Y=B.get(S),Q=w.reasoningText??w.text??w.delta??"";Q&&w.hidden!==!0&&Y.reasoning&&(Y.reasoning.chunks.push(String(Q)),m(Y));continue}let I=le(w,!1)??le(w,!0)??`reason-${p()}`,L=ae(I);L.reasoning=L.reasoning??{id:I,status:"streaming",chunks:[]},L.reasoning.startedAt=L.reasoning.startedAt??Qe(w.startedAt??w.timestamp);let O=w.reasoningText??w.text??w.delta??"";if(O&&w.hidden!==!0){let Y=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Y!==void 0){let Q=Ne(I,Y,String(O));L.reasoning.chunks=[Q]}else L.reasoning.chunks.push(String(O))}if(L.reasoning.status=w.done?"complete":"streaming",w.done){L.reasoning.completedAt=Qe(w.completedAt??w.timestamp);let Y=L.reasoning.startedAt??Date.now();L.reasoning.durationMs=Math.max(0,(L.reasoning.completedAt??Date.now())-Y)}L.streaming=L.reasoning.status!=="complete",m(L)}else if(te==="reasoning_complete"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)&&B.has(S)){let Q=B.get(S);if(Q.reasoning){let G=typeof w.text=="string"?w.text:"";G&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(G),Q.reasoning.status="complete",Q.streaming=!1,m(Q)}A.delete(S),B.delete(S);continue}let I=le(w,!1)??le(w,!0)??`reason-${p()}`,L=typeof w.text=="string"?w.text:"";!W.get(I)&&(L||w.scope==="loop")&&ae(I);let O=W.get(I);if(O?.reasoning){(w.scope==="loop"||w.scope==="turn")&&(O.reasoning.scope=w.scope),L&&O.reasoning.chunks.length===0&&O.reasoning.chunks.push(L),O.reasoning.status="complete",O.reasoning.completedAt=Qe(w.completedAt??w.timestamp);let Q=O.reasoning.startedAt??Date.now();O.reasoning.durationMs=Math.max(0,(O.reasoning.completedAt??Date.now())-Q),O.streaming=!1,m(O)}let Y=X(w);Y&&V.byStep.delete(Y)}else if(te==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof w.iteration=="number"&&(nt=w.iteration);let S=(typeof w.toolCallId=="string"?w.toolCallId:void 0)??Le(w,!0)??`tool-${p()}`,I=w.toolName??w.name;if(Se(I)){ee.add(S);continue}M(ue(w),S);let L=He(S),O=L.toolCall??{id:S,status:"pending"};O.name=I??O.name,O.status="running",w.parameters!==void 0?O.args=w.parameters:w.args!==void 0&&(O.args=w.args),O.startedAt=O.startedAt??Qe(w.startedAt??w.timestamp),O.completedAt=void 0,O.durationMs=void 0,L.toolCall=O,L.streaming=!0,w.executionId&&(L.agentMetadata={executionId:w.executionId,iteration:w.iteration}),m(L)}else if(te==="tool_output_delta"){let S=Le(w,!1)??Le(w,!0)??`tool-${p()}`;if(ee.has(S))continue;let I=He(S),L=I.toolCall??{id:S,status:"running"};L.startedAt=L.startedAt??Qe(w.startedAt??w.timestamp);let O=w.text??w.delta??w.message??"";O&&(L.chunks=L.chunks??[],L.chunks.push(String(O))),L.status="running",I.toolCall=L,I.streaming=!0;let Y=w.agentContext;(Y||w.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:Y?.executionId??w.executionId,iteration:Y?.iteration??w.iteration}),m(I)}else if(te==="tool_complete"){let S=Le(w,!1)??Le(w,!0)??`tool-${p()}`;if(ee.has(S)){ee.delete(S);continue}let I=He(S),L=I.toolCall??{id:S,status:"running"};L.status="complete",w.result!==void 0&&(L.result=w.result),typeof w.duration=="number"&&(L.duration=w.duration),L.completedAt=Qe(w.completedAt??w.timestamp);let O=w.duration??w.executionTime;if(typeof O=="number")L.durationMs=O;else{let G=L.startedAt??Date.now();L.durationMs=Math.max(0,(L.completedAt??Date.now())-G)}I.toolCall=L,I.streaming=!1;let Y=w.agentContext;(Y||w.executionId)&&(I.agentMetadata=I.agentMetadata??{executionId:Y?.executionId??w.executionId,iteration:Y?.iteration??w.iteration}),m(I);let Q=ue(w);Q&&Z.byCall.delete(Q)}else if(te==="await"&&w.toolName){let S=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,I=S??w.toolId??`local-${p()}`,L=He(I),O=w.toolName,Y=w.origin==="webmcp"&&!ir(O)?`webmcp:${O}`:O,Q=ir(Y),G=L.toolCall??{id:I,status:"pending"};G.name=Y,G.args=w.parameters,G.status=Q?"running":"complete",G.chunks=G.chunks??[],G.startedAt=G.startedAt??Qe(w.startedAt??w.timestamp??w.awaitedAt),Q?(G.completedAt=void 0,G.duration=void 0,G.durationMs=void 0):G.completedAt=G.completedAt??G.startedAt,L.toolCall=G,L.streaming=!1,L.agentMetadata={...L.agentMetadata,executionId:w.executionId??L.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},m(L)}else if(te==="text_start"){let S=typeof w.id=="string"?w.id:null,I=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(S&&I){A.set(S,I);continue}let L=b;L&&(wt==="flow"?(at(L),Ae=L):(L.streaming=!1,m(L)),b=null),_=typeof w.id=="string"?w.id:_,P=""}else if(te==="text_delta"){let S=typeof w.id=="string"?w.id:null,I=S?A.get(S):void 0;if(S&&I){let O=typeof w.delta=="string"?w.delta:"",Y=(R.get(S)??"")+O;if(R.set(S,Y),Y.trim()==="")continue;let Q=Gt(S,I);Q.agentMetadata={...Q.agentMetadata,executionId:w.executionId,parentToolId:I},Fe(Q,Y,O,void 0);continue}if(_=typeof w.id=="string"?w.id:_,wt==="flow"){let O=typeof w.delta=="string"?w.delta:"";if(P+=O,P.trim()==="")continue;let Y=ye();Y.agentMetadata={executionId:w.executionId,iteration:w.iteration},Fe(Y,P,O,void 0),x=Y;continue}let L=ye();L.content+=w.delta??"",L.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:vo??void 0,agentName:Rt?.agentName},x=L,m(L)}else if(te==="text_complete"){let S=typeof w.id=="string"?w.id:null;if(S&&A.has(S)){let L=B.get(S);L&&at(L),A.delete(S),R.delete(S),B.delete(S);continue}let I=b;I&&(wt==="flow"?(at(I),Ae=I):((I.content??"")===""&&typeof w.text=="string"&&(I.content=w.text),I.streaming=!1,m(I)),b=null),_=null,P=""}else if(te==="step_complete"){let S=w.stepType,I=w.executionType;if(S==="tool"||I==="context")continue;if(w.success===!1){let L=w.error,O=typeof L=="string"&&L!==""?L:L!=null&&typeof L=="object"&&Reflect.has(L,"message")?String(L.message??"Step failed"):"Step failed";n({type:"error",error:new Error(O)});let Y=b;Y&&Y.streaming&&(Y.streaming=!1,m(Y)),n({type:"status",status:"idle"});continue}{let L=Ae;Ae=null;let O=w.stopReason,Y=w.result?.response;if(L)O&&(L.stopReason=O),Y!=null?ft(L,Y):L.streaming!==!1&&(We.delete(L.id),tt.delete(L.id),L.streaming=!1,m(L));else{let Q=Y!=null&&Y!=="";if(Q||O){let G=ye();O&&(G.stopReason=O),Q?at(G,Y):(G.streaming=!1,m(G))}}continue}}else if(te==="execution_start")wt=w.kind==="flow"?"flow":"agent",Zt=!0,wt==="agent"&&(Rt={executionId:w.executionId,agentId:w.agentId??"virtual",agentName:w.agentName??"",status:"running",currentIteration:0,maxTurns:w.maxTurns??1,startedAt:Qe(w.startedAt)});else if(te==="turn_start"){let S=typeof w.iteration=="number"?w.iteration:nt;if(S!==nt){if(Rt&&(Rt.currentIteration=S),vs==="separate"&&S>1){let I=b;I&&(I.streaming=!1,m(I),Ko.set(S-1,I),b=null)}nt=S}vo=typeof w.id=="string"?w.id:null,x=null}else if(te==="tool_input_delta"){let S=w.toolCallId??Z.lastId;if(S){let I=U.get(S);I?.toolCall&&(I.toolCall.chunks=I.toolCall.chunks??[],I.toolCall.chunks.push(w.delta??""),m(I))}}else{if(te==="tool_input_complete")continue;if(te==="turn_complete"){let S=w.stopReason,I=b??x;if(S&&I!==null){let L=w.id;(!L||I.agentMetadata?.turnId===L)&&(I.stopReason=S,m(I))}vo===w.id&&(vo=null)}else if(te==="media_start"){let S=String(w.id);et.set(S,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(te==="media_delta"){let S=et.get(String(w.id));S&&typeof w.delta=="string"&&S.parts.push(w.delta)}else if(te==="media_complete"){let S=String(w.id),I=et.get(S);et.delete(S);let L=(typeof w.mediaType=="string"?w.mediaType:void 0)??I?.mediaType??"application/octet-stream",O=typeof w.data=="string"?w.data:void 0,Y=typeof w.url=="string"?w.url:I&&I.parts.length>0?I.parts.join(""):void 0,Q=null;if(O)Q={type:"media",data:O,mediaType:L};else if(Y){let dt=L.toLowerCase();Q={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:Y,mediaType:L}}let G=w.toolCallId??I?.toolCallId,K=Q?[Q]:[],ce=[];for(let dt of K){if(!dt||typeof dt!="object")continue;let st=dt,xt=typeof st.type=="string"?st.type:void 0,he=typeof st.mediaType=="string"?st.mediaType.toLowerCase():"",be=null,en="";if(xt==="media"){let Ue=typeof st.data=="string"?st.data:void 0;if(!Ue)continue;en=he.length>0?he:"application/octet-stream",be=`data:${en};base64,${Ue}`}else if(xt==="image-url"){let Ue=typeof st.url=="string"?st.url:void 0;if(!Ue)continue;en=he,be=Ue}else if(xt==="file-url"){let Ue=typeof st.url=="string"?st.url:void 0;if(!Ue)continue;en=he,be=Ue}else continue;if(be)if(xt==="image-url"||en.startsWith("image/"))ce.push({type:"image",image:be,...en.includes("/")?{mimeType:en}:{}});else if(en.startsWith("audio/"))ce.push({type:"audio",audio:be,mimeType:en});else if(en.startsWith("video/"))ce.push({type:"video",video:be,mimeType:en});else{let Ue=en||"application/octet-stream";ce.push({type:"file",data:be,mimeType:Ue,filename:PS(Ue)})}}if(ce.length>0){let dt=p(),st=G,he={id:`agent-media-${typeof st=="string"&&st.length>0?`${st}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:ce,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:nt}};m(he);let be=b;be&&(be.streaming=!1,m(be)),b=null,T.current=null}}else if(te==="execution_complete"){let S=w.kind??wt;S==="agent"&&Rt&&(Rt.status=w.success?"complete":"error",Rt.completedAt=Qe(w.completedAt),Rt.stopReason=w.stopReason);let I=b;I&&(S==="flow"&&I.streaming!==!1?at(I):(I.streaming=!1,m(I)),b=null),_=null,P="",Ae=null,n({type:"status",status:"idle",terminal:!0})}else if(te==="execution_error"){let S=typeof w.error=="string"?w.error:w.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(te!=="ping"){if(te==="approval_start"){let S=w.approvalId??`approval-${p()}`,I={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:"pending",agentId:Rt?.agentId??"virtual",executionId:w.executionId??Rt?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};m(I)}else if(te==="step_await"&&w.awaitReason==="approval_required"){let S=w.approvalId??`approval-${p()}`,I={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:"pending",agentId:Rt?.agentId??"virtual",executionId:w.executionId??Rt?.executionId??"",toolName:w.toolName??"",toolType:w.toolType,description:w.description??`Execute ${w.toolName??"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};m(I)}else if(te==="approval_complete"){let S=w.approvalId;if(S){let L={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:S,status:w.decision??"approved",agentId:Rt?.agentId??"virtual",executionId:w.executionId??Rt?.executionId??"",toolName:w.toolName??"",description:w.description??"",resolvedAt:Date.now()}};m(L)}}else if(te==="artifact_start"||te==="artifact_delta"||te==="artifact_update"||te==="artifact_complete"){if(te==="artifact_start"){let S=w.artifactType,I=String(w.id),L=typeof w.title=="string"?w.title:void 0,O=w.file,Y;O&&typeof O=="object"&&!Array.isArray(O)&&typeof O.path=="string"&&typeof O.mimeType=="string"&&(Y={path:O.path,mimeType:O.mimeType,...typeof O.language=="string"?{language:O.language}:{}}),n({type:"artifact_start",id:I,artifactType:S,title:L,component:typeof w.component=="string"?w.component:void 0,...Y?{file:Y}:{}});let Q=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?{...w.props}:void 0;if(me.set(I,{markdown:"",title:L,file:Y,...Q?{props:Q}:{}}),!we.has(I)){we.add(I);let G=po(this.config.features?.artifacts,{artifactType:S,...Y?{file:Y}:{}}),K=typeof w.component=="string"?w.component:void 0,ce={id:`artifact-ref-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:pa(G,{artifactId:I,title:L,artifactType:S,status:"streaming",...Y?{file:Y}:{},...K?{component:K}:{}})};pe.set(I,ce),m(ce)}}else if(te==="artifact_delta"){let S=String(w.id),I=typeof w.delta=="string"?w.delta:String(w.delta??"");n({type:"artifact_delta",id:S,artDelta:I});let L=me.get(S);L&&(L.markdown+=I)}else if(te==="artifact_update"){let S=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:S,component:typeof w.component=="string"?w.component:void 0});let I=me.get(String(w.id));I&&(I.props={...I.props??{},...S})}else if(te==="artifact_complete"){let S=String(w.id);n({type:"artifact_complete",id:S});let I=pe.get(S);if(I){I.streaming=!1;try{let L=JSON.parse(I.rawContent??"{}");if(L.props){L.props.status="complete";let O=me.get(S);O?.markdown&&(L.props.markdown=O.markdown),O?.file&&(L.props.file=O.file),L.component==="PersonaArtifactInline"&&O?.props&&Object.keys(O.props).length>0&&(L.props.componentProps=O.props)}I.rawContent=JSON.stringify(L)}catch{}me.delete(S),m(I),pe.delete(S)}}}else if(te==="transcript_insert"){let S=w.message;if(!S||typeof S!="object")continue;let I=String(S.id??`msg-${p()}`),L=S.role,Y={id:I,role:L==="user"?"user":L==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:p()};if(m(Y),Y.rawContent)try{let G=JSON.parse(Y.rawContent)?.props?.artifactId;typeof G=="string"&&we.add(G)}catch{}b=null,T.current=null,We.delete(I),tt.delete(I)}else if(te==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let S=typeof w.error=="string"?w.error:w.error?.message!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(S)});let I=b;I&&I.streaming&&(I.streaming=!1,m(I)),n({type:"status",status:"idle"})}}else if(te==="step_error"||te==="dispatch_error"||te==="flow_error"){let S=null;if(w.error instanceof Error)S=w.error;else if(te==="dispatch_error"){let I=w.message??w.error;I!=null&&I!==""&&(S=new Error(String(I)))}else{let I=w.error;typeof I=="string"&&I!==""?S=new Error(I):I!=null&&typeof I=="object"&&Reflect.has(I,"message")&&(S=new Error(String(I.message??I)))}if(S){n({type:"error",error:S});let I=b;I&&I.streaming&&(I.streaming=!1,m(I)),n({type:"status",status:"idle"})}}}}}Ut.length=0};;){let{done:F,value:te}=await s.read();if(F)break;l+=i.decode(te,{stream:!0});let w=l.split(`
12
12
 
13
- `);i=h.pop()??"";for(let H of h){let I=H.split(`
14
- `),D="message",K="",j=null;for(let ue of I)ue.startsWith("event:")?D=ue.replace("event:","").trim():ue.startsWith("data:")?K+=ue.replace("data:","").trim():ue.startsWith("id:")&&(j=ue.slice(3).trim());let G=()=>{j!==null&&j!==""&&n({type:"cursor",id:j})};if(!K){G();continue}let pe;try{pe=JSON.parse(K)}catch(ue){n({type:"error",error:ue instanceof Error?ue:new Error("Failed to parse chat stream payload")});continue}let ze=D!=="message"?D:pe.type??"message";if(this.onSSEEvent?.(ze,pe),this.parseSSEEvent){S.current=x;let ue=await this.handleCustomSSEEvent(pe,n,S,f,c,k);if(S.current&&S.current!==x&&(x=S.current),ue){G();continue}}et.push({payloadType:ze,payload:pe}),Le(),G()}}Le()}};function zg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function as(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Do(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ii="[Image]";function qg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Vg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Kg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oo(e){return{type:"text",text:e}}function Gg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Jg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Yg(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 Xg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ov=["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"],io=[...Xg,...ov];function rv(e){return Xg.includes(e)||e.startsWith("image/")}function Hi(e){return rv(e.type)}async function Qg(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Hi(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Zg(e,t=io,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 sv(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function ef(e,t){let n=sv(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"}Zc();var tf=16e3,av=24e3,iv=4096,lv=1380533830;function cv(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===lv?new Uint8Array(e,44):new Uint8Array(e)}function dv(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 la=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:tf,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:tf});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new is(av);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(g=>g.stop()),i.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${dv(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=g=>this.handleMessage(g,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(iv,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let g=Math.max(-1,Math.min(1,p[c]));d[c]=g<0?g*32768:g*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=cv(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var xr=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function No(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new la(e.runtype);case"browser":if(!xr.isSupported())throw new Error("Browser speech recognition not supported");return new xr(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 Bi(e){if(e?.type==="custom"&&e.custom)return No({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return No({type:"runtype",runtype:e.runtype});if(xr.isSupported())return No({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function ca(e){try{return Bi(e),!0}catch{return!1}}function ls(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var Fo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ls(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Cr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function ed(e){if(!e)return"";let t=pv(e);return nf(t!==null?t:e)}function pv(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 nf(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
+ `);l=w.pop()??"";for(let S of w){let I=S.split(`
14
+ `),L="message",O="",Y=null;for(let ce of I)ce.startsWith("event:")?L=ce.replace("event:","").trim():ce.startsWith("data:")?O+=ce.replace("data:","").trim():ce.startsWith("id:")&&(Y=ce.slice(3).trim());let Q=()=>{Y!==null&&Y!==""&&n({type:"cursor",id:Y})};if(!O){Q();continue}let G;try{G=JSON.parse(O)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let K=L!=="message"?L:G.type??"message";if(this.onSSEEvent?.(K,G),this.parseSSEEvent){T.current=b;let ce=await this.handleCustomSSEEvent(G,n,T,m,p,H);if(T.current&&T.current!==b&&(b=T.current),ce){Q();continue}}Ut.push({payloadType:K,payload:G}),Vn(),Q()}}Vn()}};function fy(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ei(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function fr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Un=class extends Error{constructor(t,n,o){super(n),this.name="HistoryProviderError",this.code=t,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}};function my(e){return e instanceof Un}uu();var hy=16e3,IS=24e3,RS=4096,WS=1380533830;function BS(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===WS?new Uint8Array(e,44):new Uint8Array(e)}function OS(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 Ca=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){if(this.callLive)return;let t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:hy,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:hy});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ti(IS);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let u=`${OS(o)}/ws/agents/${encodeURIComponent(t)}/voice`,p=new WebSocket(u,["runtype.bearer",n]);p.binaryType="arraybuffer",this.ws=p,p.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,p,r))},p.onmessage=g=>this.handleMessage(g,r),p.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},p.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let y=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let i=t.createScriptProcessor(RS,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),u=new Int16Array(d.length);for(let p=0;p<d.length;p++){let g=Math.max(-1,Math.min(1,d[p]));u[p]=g<0?g*32768:g*32767}o.send(u.buffer)},s.connect(i),i.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let o=BS(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var ts=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function mr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ca(e.runtype);case"browser":if(!ts.isSupported())throw new Error("Browser speech recognition not supported");return new ts(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 yc(e){if(e?.type==="custom"&&e.custom)return mr({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return mr({type:"runtype",runtype:e.runtype});if(ts.isSupported())return mr({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function wa(e){try{return yc(e),!0}catch{return!1}}function ni(e){let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var hr=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let i=s.find(l=>l.name===t.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ni(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ns=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function gu(e){if(!e)return"";let t=DS(e);return yy(t!==null?t:e)}function DS(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function yy(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 lf=null;var td=()=>lf?lf():Promise.resolve().then(()=>(af(),sf));var hv=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function yv(e,t){return hv.some(n=>e[n]!==t[n])}function nd(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}
16
+ `),t.trim()}var xy=null;var fu=()=>xy?xy():Promise.resolve().then(()=>(wy(),Cy));var jS=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function zS(e,t){return jS.some(n=>e[n]!==t[n])}var fo=class extends Error{constructor(t,n){super(n),this.name="SessionHistoryError",this.code=t}};function mu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
17
17
 
18
- _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]}),pf=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,uf=e=>ko(e)||e===Bn,cs=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 Cr(()=>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&&(ko(n.name)||n.name===Bn&&Ho(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new vr(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||td().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 ca(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=Fo.isSupported()?new Fo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return td().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=No(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!yv(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new vr(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:g}=t,f={id:a??(n==="user"?as():n==="assistant"?Do():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...g!==void 0&&{rawContent:g}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:g=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?as():r==="assistant"?Do():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
18
+ _Details: ${n.message}_`:o}var xa=e=>({isError:!0,content:[{type:"text",text:e}]}),Ty=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ey=e=>ir(e)||e===eo,oi=class e{constructor(t={},n,o={}){this.config=t;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new ns(()=>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&&(ir(n.name)||n.name===eo&&ur(this.config).enabled);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...t.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new es(t,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of t.initialArtifacts??[])this.artifacts.set(r.id,{...r,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||fu().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 wa(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=hr.isSupported()?new hr({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=t.browserFallback!==!1;if(o&&r&&s)return fu().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let u=new l({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return i&&n?new d(u,n,{onFallback:p=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${p.message}`)}):u});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=mr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let d=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=d.id}if(l){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let d=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=d.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){this.clientSession=t,this.injectWelcomeMessage(t)}injectWelcomeMessage(t){if(this.suppressWelcomeInjection||!t.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}setHistoryInternals(t){this.historyInternals=this.composeHistoryInternals(t),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(t){let n=t.onHistoryContinuityChanged;return{...t,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let t=this.historyProvider;if(!t)throw new fo("history_unavailable","No conversation history provider is installed");return t}historyContext(t){let n=this.requireHistoryProvider(),o=t??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new Un("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(t,n){this.callbacks.onHistoryNotice?.({code:t,message:n})}async awaitHistorySettled(){let t=this.historyGate;t&&await t.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new fo("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(t){return this.requireHistoryProvider().list({...t?.cursor?{cursor:t.cursor}:{},...t?.limit!==void 0?{limit:t.limit}:{},...t?.targetId!==void 0?{targetId:t.targetId}:{},context:this.historyContext(t?.scope)})}async openConversation(t,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,i=await o.getPage(t,{context:r});if(s!==this.historyOpenEpoch)throw new fo("superseded","A later selection won");let l=await o.prepareOpen(t,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new fo("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||t,this.activeConversationRevision=l.conversationRevision||i.conversationRevision||null,this.historyNextMessageCursor=i.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(i.messages),this.emitHistoryState(),{summary:i.summary,nextMessageCursor:i.nextCursor}}loadOlderMessages(t,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),i=n??this.historyNextMessageCursor;if(!i)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${t} ${i}`,d=this.olderPageRequests.get(l);if(d)return d;let u=this.fetchOlderPage(r,t,i,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,u),u}async fetchOlderPage(t,n,o,r){let s=this.messages[0]?.createdAt,i=await t.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:i.nextCursor};let l=va(this.messages,i.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=i.nextCursor;for(let d of i.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(i.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:i.messages,nextMessageCursor:i.nextCursor}}async startNewConversation(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new fo("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(t){this.discardConversationState(),await this.commitActivation(t),this.activeConversationId=t.conversationId||null,this.activeConversationRevision=t.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(t,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(t,{context:r}),t===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(t,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new fo("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(t,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(t){let n=this.requireHistoryProvider(),o=this.historyContext(t?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...t?.targetId!==void 0?{targetId:t.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let t=this.requireHistoryProvider();if(!t.resetDevice)throw new fo("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await t.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(t)}async prepareReplacementConversation(t){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:t});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new fo("new_conversation_required","A new conversation is required before sending")}async commitActivation(t){await t.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(t){this.clientSession=t,this.config.setStoredSessionId?.(t.sessionId),t.conversationId&&(this.activeConversationId=t.conversationId,this.activeConversationRevision=t.conversationRevision??null,this.config.setStoredConversationId?.(t.conversationId),this.historyInternals.setStoredConversationRevision?.(t.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(t)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(t){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=t.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let t=this.historyInternals.visitorStore??null;t!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=t,t&&(this.visitorStoreUnsubscribe=t.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(t){if(t.source!=="external"||t.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(t){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(t?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(t,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let i=await t.getPage(n,{context:o}),l=new Set(i.messages.map(g=>g.id)),d=this.messages.some(g=>l.has(g.id)),u=i.messages[0]?.createdAt,p;if(!d)p=i.messages.map(g=>this.ensureSequence(g));else{let g=this.resumable?this.activeAssistantMessageId:null,y=this.messages.filter(m=>l.has(m.id)||m.id===g?!0:u!==void 0&&m.createdAt<u);p=va(y,i.messages).map(m=>this.ensureSequence(m))}this.historyNextMessageCursor=i.nextCursor,this.activeConversationRevision=i.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let g of i.messages)this.acknowledgedProjections.set(g.id,g.content);this.persistConversationMetadata(),this.messages=this.sortMessages(p),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(t){this.pendingProjections=t,this.historyInternals.setPendingDisplayProjections?.(t)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(t){if(this.projectionFinalizationEnabled())for(let n of t){let o=ba(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let t=this.activeConversationId;if(!t)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=ba(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:t,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(t,n))}enqueueProjectionFinalization(t,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(t,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(t,n,o){if(this.activeConversationId!==t)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(t,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(t,r);for(let i of r)this.acknowledgedProjections.set(i.id,i.displayContent);this.activeConversationId===t&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(t,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(t,r,!0);return}if(s instanceof De&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(t,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(t){return t instanceof De?t.code==="request_failed":t instanceof Error}clearFinalizedMarker(t,n){let o=this.readPendingProjections();if(!o||o.conversationId!==t)return;let r=new Set(n.map(i=>i.id)),s=o.messageIds.filter(i=>!r.has(i));this.setPendingProjections(s.length?{conversationId:t,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let t=this.readPendingProjections();if(!t)return;if(this.activeConversationId&&t.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of t.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(t.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(t){return t instanceof De&&t.code==="conversation_deleted"}async dispatchWithDeletedRecovery(t,n,o,r){this.recordDispatchedProjections(t);try{await this.client.dispatch({messages:t,signal:n.signal,assistantMessageId:o},this.handleEvent);return}catch(s){if(!e.isConversationDeleted(s))throw s;let i=await this.recoverFromDeletedConversation(r);if(!i)throw s;this.recordDispatchedProjections([i]),await this.client.dispatch({messages:[i],signal:n.signal,assistantMessageId:o},this.handleEvent)}}async recoverFromDeletedConversation(t){let n=this.messages.find(r=>r.id===t);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(t){let n=this.config.features?.artifacts?.display,o={...this.config,...t},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!zS(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new es(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:d,streaming:u=!1,voiceProcessing:p,rawContent:g}=t,m={id:i??(n==="user"?ei():n==="assistant"?fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:i,contentParts:l,id:d,createdAt:u,sequence:p,streaming:g=!1,voiceProcessing:y,rawContent:m}=o,x={id:d??(r==="user"?ei():r==="assistant"?fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:u??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...y!==void 0&&{voiceProcessing:y},...m!==void 0&&{rawContent:m}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:d}=t,u={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(u),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
19
19
 
20
- `),a=[s,n].filter(Boolean).join(`
20
+ `),i=[s,n].filter(Boolean).join(`
21
21
 
22
- `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(Oo(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(Oo(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=as(),s=Do();this.activeAssistantMessageId=null;let a=n?.contentParts&&Wi(n.contentParts)?Ii:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(g=>g.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!g){let b=nd(c,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=Do();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=nd(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let g=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}g=c.body}else c instanceof ReadableStream&&(g=c);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,g=Array.isArray(c?.questions)?c.questions:[];if(g.length===1){let b=typeof g[0]?.question=="string"?g[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((g,b)=>{let f=typeof g?.question=="string"?g.question:"";if(!f)return;let x=c[f],C=Array.isArray(x)?x.join(", "):typeof x=="string"?x:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let g=await c.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let g=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Bn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let g=`${t}:${c}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(g),o.push(g);let b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??d;if(d===Bn)return{dedupeKey:g,resumeKey:f,output:Kc(),toolMessage:p,startedAt:b,completedAt:Date.now()};let x=new AbortController;this.webMcpResolveControllers.add(x),r.push(x);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,x.signal),S;if(!C)S={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{S=await C}catch(k){let R=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));return R||this.callbacks.onError?.(k instanceof Error?k:new Error(String(k))),this.markWebMcpToolComplete(p,da(R?"Aborted by cancel()":pf(k)),b),this.webMcpInflightKeys.delete(g),null}return x.signal.aborted?(this.markWebMcpToolComplete(p,da("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:f,output:S,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Bn?{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,da("Aborted by cancel()"),c.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let x=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x))return;this.webMcpInflightKeys.add(x);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(x)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(x)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Bn,c=t.toolCall?.args,g=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",f=a;try{let x;if(d?x=Kc():g?x=await g:x={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,da("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,x,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,x,a,f,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(x){let C=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,da(C||p.aborted?"Aborted by cancel()":pf(x)),a),C||this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=$n(this.config.features?.artifacts,t),r=ta(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=$n(this.config.features?.artifacts,n),s=ta(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(df(),cf)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>nd(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=Do(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=ed(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ls(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=ed(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,g=n.approval;a.approval={...c,...g,executionId:g.executionId||c.executionId,toolName:g.toolName||c.toolName,description:g.description||c.description,toolType:g.toolType??c.toolType,reason:g.reason??c.reason,parameters:g.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&uf(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,g=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),f=r.toolCall?.name,x=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&f!==void 0&&uf(f)&&r.toolCall?.status==="complete";(g||b||x)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};var T=require("lucide"),bv={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,"code-xml":T.CodeXml,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,"pen-line":T.PenLine,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,"chart-column":T.ChartColumn,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,lightbulb:T.Lightbulb,monitor:T.Monitor,smartphone:T.Smartphone},se=(e,t=24,n="currentColor",o=2)=>{let r=bv[e];return r?vv(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function vv(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var Ni={allowedTypes:io,maxFileSize:10*1024*1024,maxFiles:4};function xv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Cv(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 wr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Ni.allowedTypes,maxFileSize:t.maxFileSize??Ni.maxFileSize,maxFiles:t.maxFiles??Ni.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ni.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=Zg(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Qg(n),s=Hi(n)?URL.createObjectURL(n):null,a={id:xv(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Hi(t.file),o=y("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Cv(t.file.type),p=se(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=y("span");d.textContent=ef(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=se("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var gf=/\s/;function wv(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
- `:o===""||gf.test(o)}function Av(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return wv(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
- `||a==="\uFFFC"||!r&&gf.test(a))return null;s--}return null}function ff(e,t,n){for(let o of n){let r=Av(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function mf(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function hf(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Dt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},$t=1e5,Fi=$t+1;var Sv=8,Tv=8,od=10,rd=new WeakMap,yf=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ev=e=>{let t=e.getRootNode?.();return yf(t)?t:e.ownerDocument.body},sd=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function jt(e){rd.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=Sv,viewportPadding:a=Tv}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,g=null,b=!1,f=!1,x=!1,C=()=>(typeof o=="function"?o():o).trim(),S=()=>{g?.(),g=null,d?.remove(),d=null,c=null},k=()=>{if(!d)return;let X=i(),A=p(),J=t.getBoundingClientRect(),Z=d.getBoundingClientRect(),ce=X.documentElement.clientWidth||A.innerWidth,Y=X.documentElement.clientHeight||A.innerHeight,he=ce-a-Z.width,te=J.left+J.width/2-Z.width/2,be=sd(te,a,he),ee=J.top-a,ge=Y-a-J.bottom,ne=Z.height+s,me=ee>=ne||ee>=ge?"top":"bottom",ve=me==="top"?J.top-s-Z.height:J.bottom+s,ye=Y-a-Z.height,De=sd(ve,a,ye),at=J.left+J.width/2,je=Math.max(od,Z.width-od),Ke=sd(at-be,od,je);d.dataset.placement=me,d.style.left=`${be}px`,d.style.top=`${De}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Ke}px`)},R=()=>{if(x||!r||d||!t.isConnected)return;let X=C(),A=Ev(t);if(!X||!A)return;let J=i(),Z=p();d=J.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Fi),c=J.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=X,d.appendChild(c);let ce=J.createElement("span");ce.className="persona-control-tooltip__arrow",d.appendChild(ce),A.appendChild(d),k(),d.dataset.state="open";let Y=()=>{if(!t.isConnected){S();return}c&&(c.textContent=C()),k()};Z.addEventListener("scroll",Y,!0),Z.addEventListener("resize",Y);let he=t.getRootNode(),te=yf(he)?he:J.documentElement,be=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||S()});be?.observe(te,{childList:!0,subtree:!0}),g=()=>{Z.removeEventListener("scroll",Y,!0),Z.removeEventListener("resize",Y),be?.disconnect()}},E=()=>{b||f?R():S()},P=()=>{let X=p();(!X.matchMedia||!X.matchMedia("(hover: none)").matches)&&(b=!0,E())},B=()=>{b=!1,E()},N=()=>{f=!0,E()},$=()=>{f=!1,E()},z=X=>{X.key==="Escape"&&(b=!1,f=!1,S())};n.addEventListener("mouseenter",P),n.addEventListener("mouseleave",B),t.addEventListener("focus",N),t.addEventListener("blur",$),t.addEventListener("keydown",z);let q={get isOpen(){return d!==null},show:R,hide:S,reposition:k,destroy:()=>{x||(x=!0,S(),n.removeEventListener("mouseenter",P),n.removeEventListener("mouseleave",B),t.removeEventListener("focus",N),t.removeEventListener("blur",$),t.removeEventListener("keydown",z),rd.delete(t))}};return rd.set(t,q),q}function bf(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=y("div","persona-send-button-wrapper"),d=ke("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=se(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),p.appendChild(d),jt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:KS,load:Mv}=Qr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var ad=Mv;var{setLoader:YS,load:kv}=Qr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var vf=kv;function pa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ke("span",{className:Hn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=se(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=y("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ke("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function xf(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=hf(t).filter(E=>E.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(E=>E.sources.some(P=>typeof P.matchCommand=="function")),r=E=>o.some(P=>P.trigger?P.position==="line-start"?E.split(`
25
- `).some(N=>N.startsWith(P.trigger)):(P.position==="anywhere"?E:E.split(`
26
- `)[0]).startsWith(P.trigger):!1),s=(E,P)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:P}))}catch{}},a=ke("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,g=null,b=null,f=null,x=()=>{if(i)return Promise.resolve(i);if(p)return p;let E=ad().then(P=>(i=P.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:R,emit:s}),i)).catch(P=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",P),p===E&&(p=null),null));return p=E,E},C=()=>{vf().then(E=>{let P=E.mountInlineComposer({textarea:e.textarea,renderToken:N=>pa(N,{render:t.renderMentionToken}),onMentionRemoved:N=>i?.untrackMention(N)});c=P.input,g=P.destroy;let B=d;B.replaceWith(P.element),d=P.element,f={next:P.element,prev:B},b?.(P.element,B),i?i.rebindComposer(P.input):p&&p.then(N=>N?.rebindComposer(P.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};t.display==="inline"&&C();let S=[],k=new Map;for(let E of n){if(!E.showButton)continue;let P=bf({config:{...t,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{x().then(B=>B?.openMenu(E.trigger))}});S.push(P),k.set(E.trigger,P.button)}let R=(E,P,B)=>{let N=k.get(P);N&&(N.setAttribute("aria-expanded",E?"true":"false"),E?N.setAttribute("aria-controls",B):N.removeAttribute("aria-controls"))};return{affordanceButtons:S.map(E=>E.wrapper),contextRow:a,handleInput:E=>{if(i){i.handleInput();return}if(!mf(E))return;let P=d,B=P.selectionStart??0;ff(P.value,B,n)&&x().then(N=>N?.handleInput())},handleKeydown:E=>{if(i?.isMenuOpen())return i.handleKeydown(E);if(E.key==="Backspace"&&i?.hasMentions()&&!f){let P=d,B=P.selectionStart===0&&P.selectionEnd===0;if((P.value.length===0||B)&&i.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(i??await x())?.dispatchInlineCommand(E)??null:null,clear:()=>i?.clear(),prefetch:()=>{ad().catch(()=>{})},onComposerSwap:E=>{b=E,f&&E(f.next,f.prev)},destroy:()=>{i?.destroy(),g?.();for(let E of S)E.wrapper.remove();a.remove()}}}var Cf=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ua(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Cf(s)&&Cf(r)?n[o]=ua(s,r):n[o]=r}return n}var pn="min(440px, calc(100vw - 24px))",_i="440px",Lv={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:pn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},st={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Lv,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function wf(e,t){if(!(!e&&!t))return e?t?ua(e,t):e:t}function ds(e){return e?{...st,...e,theme:wf(st.theme,e.theme),darkTheme:wf(st.darkTheme,e.darkTheme),launcher:{...st.launcher,...e.launcher,dock:{...st.launcher?.dock,...e.launcher?.dock},clearChat:{...st.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...st.copy,...e.copy},sendButton:{...st.sendButton,...e.sendButton},statusIndicator:{...st.statusIndicator,...e.statusIndicator},voiceRecognition:{...st.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=st.features?.artifacts,n=e.features?.artifacts,o=st.features?.scrollToBottom,r=e.features?.scrollToBottom,s=st.features?.scrollBehavior,a=e.features?.scrollBehavior,i=st.features?.streamAnimation,p=e.features?.streamAnimation,d=st.features?.askUserQuestion,c=e.features?.askUserQuestion,g=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&a===void 0?void 0:{...s,...a},x=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...st.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...g!==void 0?{artifacts:g}:{},...x!==void 0?{streamAnimation:x}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??st.suggestionChips,suggestionChipsConfig:{...st.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...st.layout,...e.layout,header:{...st.layout?.header,...e.layout?.header},messages:{...st.layout?.messages,...e.layout?.messages,avatar:{...st.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...st.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...st.layout?.slots,...e.layout?.slots}},markdown:{...st.markdown,...e.markdown,options:{...st.markdown?.options,...e.markdown?.options}},messageActions:{...st.messageActions,...e.messageActions}}:st}var $i="16px",ji="transparent",id={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"}},ld={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"}},cd={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:pn,maxWidth:_i,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:$i,canvasBackground:ji},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Qt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Qt(e,o):o}function Ui(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Qt(e,a);p!==void 0&&(t[i]={path:i,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function dd(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 Af(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Af(s,r):n[o]=r}return n}function Pv(e,t){return t?Af(e,t):e}function ga(e,t={}){let n={palette:id,semantic:ld,components:cd},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:Pv(n.components,e?.components)};if(t.validate!==!1){let r=dd(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function zi(e){let t=Ui(e),n={};for(let[A,J]of Object.entries(t)){let Z=A.replace(/\./g,"-");n[`--persona-${Z}`]=J.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??$i,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ji,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],a=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),i=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=a&&i==="1.5rem"?"1.5rem 0":i,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let p=n["--persona-components-markdown-heading-h1-fontSize"];p&&(n["--persona-md-h1-size"]=p);let d=n["--persona-components-markdown-heading-h1-fontWeight"];d&&(n["--persona-md-h1-weight"]=d);let c=n["--persona-components-markdown-heading-h2-fontSize"];c&&(n["--persona-md-h2-size"]=c);let g=n["--persona-components-markdown-heading-h2-fontWeight"];g&&(n["--persona-md-h2-weight"]=g);let b=n["--persona-components-markdown-prose-fontFamily"];b&&b!=="inherit"&&(n["--persona-md-prose-font-family"]=b),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let f=e.components,x=f?.iconButton;x&&(x.background&&(n["--persona-icon-btn-bg"]=x.background),x.border&&(n["--persona-icon-btn-border"]=x.border),x.color&&(n["--persona-icon-btn-color"]=x.color),x.padding&&(n["--persona-icon-btn-padding"]=x.padding),x.borderRadius&&(n["--persona-icon-btn-radius"]=x.borderRadius),x.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=x.hoverBackground),x.hoverColor&&(n["--persona-icon-btn-hover-color"]=x.hoverColor),x.activeBackground&&(n["--persona-icon-btn-active-bg"]=x.activeBackground),x.activeBorder&&(n["--persona-icon-btn-active-border"]=x.activeBorder));let C=f?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let S=f?.toggleGroup;S&&(S.gap&&(n["--persona-toggle-group-gap"]=S.gap),S.borderRadius&&(n["--persona-toggle-group-radius"]=S.borderRadius));let k=f?.artifact;if(k?.toolbar){let A=k.toolbar;A.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=A.iconHoverColor),A.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=A.iconHoverBackground),A.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=A.iconPadding),A.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=A.iconBorderRadius),A.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=A.iconBorder),A.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=A.toggleGroupGap),A.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=A.toggleBorderRadius),A.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=A.toggleGroupPadding),A.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=A.toggleGroupBorder),A.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=A.toggleGroupBorderRadius),A.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,A.toggleGroupBackground)??A.toggleGroupBackground),A.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=A.copyBackground),A.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=A.copyBorder),A.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=A.copyColor),A.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=A.copyBorderRadius),A.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=A.copyPadding),A.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=A.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??A.copyMenuBackground),A.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=A.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??A.copyMenuBorder),A.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=A.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??A.copyMenuShadow),A.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=A.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??A.copyMenuBorderRadius),A.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=A.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??A.copyMenuItemHoverBackground),A.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=A.iconBackground),A.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=A.toolbarBorder)}if(k?.tab){let A=k.tab;A.background&&(n["--persona-artifact-tab-bg"]=A.background),A.activeBackground&&(n["--persona-artifact-tab-active-bg"]=A.activeBackground),A.activeBorder&&(n["--persona-artifact-tab-active-border"]=A.activeBorder),A.borderRadius&&(n["--persona-artifact-tab-radius"]=A.borderRadius),A.textColor&&(n["--persona-artifact-tab-color"]=A.textColor),A.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=A.hoverBackground),A.listBackground&&(n["--persona-artifact-tab-list-bg"]=A.listBackground),A.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=A.listBorderColor),A.listPadding&&(n["--persona-artifact-tab-list-padding"]=A.listPadding)}if(k?.pane){let A=k.pane;if(A.toolbarBackground){let J=Qt(e,A.toolbarBackground)??A.toolbarBackground;n["--persona-artifact-toolbar-bg"]=J}}if(k?.card){let A=k.card;A.background&&(n["--persona-artifact-card-bg"]=A.background),A.border&&(n["--persona-artifact-card-border"]=A.border),A.borderRadius&&(n["--persona-artifact-card-radius"]=A.borderRadius),A.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=A.hoverBackground),A.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=A.hoverBorderColor)}if(k?.inline){let A=k.inline;A.background&&(n["--persona-artifact-inline-bg"]=Qt(e,A.background)??A.background),A.border&&(n["--persona-artifact-inline-border"]=A.border),A.borderRadius&&(n["--persona-artifact-inline-radius"]=A.borderRadius),A.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,A.chromeBackground)??A.chromeBackground),A.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,A.chromeBorder)??A.chromeBorder),A.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,A.titleColor)??A.titleColor),A.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,A.mutedColor)??A.mutedColor),A.frameHeight&&(n["--persona-artifact-inline-frame-height"]=A.frameHeight)}let R=f?.code;R&&(R.keywordColor&&(n["--persona-code-keyword-color"]=R.keywordColor),R.stringColor&&(n["--persona-code-string-color"]=R.stringColor),R.commentColor&&(n["--persona-code-comment-color"]=R.commentColor),R.numberColor&&(n["--persona-code-number-color"]=R.numberColor),R.tagColor&&(n["--persona-code-tag-color"]=R.tagColor),R.attrColor&&(n["--persona-code-attr-color"]=R.attrColor),R.propertyColor&&(n["--persona-code-property-color"]=R.propertyColor),R.lineNumberColor&&(n["--persona-code-line-number-color"]=R.lineNumberColor),R.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=R.gutterBorderColor),R.background&&(n["--persona-code-bg"]=Qt(e,R.background)??R.background));let E=n["--persona-surface"],P=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",N=n["--persona-palette-colors-gray-200"]??"#e5e7eb",$=n["--persona-palette-colors-gray-300"]??"#d1d5db",z=!P||P===E,q=z?B:P,X=z?N:P;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??q,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??X,z&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??$),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??q,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??q,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??q,n}var Sf={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 Rv={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"}}},Tf=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},fa=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Iv=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":fa()},qi=e=>Iv(e),Wv=e=>ga(e),Hv=e=>ga({...e,palette:{...e?.palette,colors:{...Rv.colors,...e?.palette?.colors}}},{validate:!1}),_o=e=>{let t=qi(e),n=Tf(e?.theme),o=Tf(e?.darkTheme);return t==="dark"?Hv(ua(n??{},o??{})):Wv(n)},Bv=e=>zi(e),Ar=(e,t)=>{let n=_o(t),o=Bv(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",qi(t))},ps=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(fa())});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(fa());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var $o=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function jn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Ef(e){let t=jn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Vi(e){if(typeof e!="string")return"";let t=e.indexOf(`
22
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,d=r.contentParts.length>0;if(l){let u=[];s&&u.push(go(s)),u.push(...r.contentParts),u.push(...t.contentParts),t.contentParts=u}else if(d){let u=[];i&&u.push(go(i)),u.push(...r.contentParts),t.contentParts=u}else s&&(t.llmContent=i);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=ei(),s=fr();this.activeAssistantMessageId=null;let i=n?.contentParts&&Zs(n.contentParts)?Qs:"",l={id:r,role:"user",content:o||i,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let p=this.messages.find(g=>g.id===r)??l;if(await this.applyMentionBundle(p,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let u=[...this.messages];try{await this.dispatchWithDeletedRecovery(u,d,s,r)}catch(p){if(this.status==="resuming"||this.reconnecting)return;let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));if(!g){let y=mu(p,this.config.errorMessage);if(y){let m={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(p instanceof Error?this.callbacks.onError?.(p):this.callbacks.onError?.(new Error(String(p))))}}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let t=fr();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=mu(r,this.config.errorMessage);if(i){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(t,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},i=this.messages.find(p=>p.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,u=d&&typeof d=="object"?d.onDecision:void 0;try{let p;if(u?p=await u({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),p){let g=null;if(p instanceof Response){if(!p.ok){let y=await p.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${p.status}`)}g=p.body}else p instanceof ReadableStream&&(g=p);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(p=>p.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let p=t.toolCall?.args,g=Array.isArray(p?.questions)?p.questions:[];if(g.length===1){let y=typeof g[0]?.question=="string"?g[0].question:"";y&&(i={[y]:n})}}this.markAskUserQuestionResolved(t,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===0){let p=typeof n=="string"?n:Object.entries(n).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:p,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let p=i??{};u.forEach((g,y)=>{let m=typeof g?.question=="string"?g.question:"";if(!m)return;let b=p[m],x=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,role:"user",content:x||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let p=await this.client.resumeFlow(r,{[s]:n});if(!p.ok){let g=await p.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${p.status}`)}p.body?await this.connectStream(p.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(p){let g=p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==eo?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(i=>i.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=await Promise.all(n.map(async d=>{let u=d.toolCall?.name,p=d.toolCall?.id;if(!u||!p)return null;let g=`${t}:${p}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(g),o.push(g);let y=this.markWebMcpToolRunning(d),m=d.agentMetadata?.webMcpToolCallId??u;if(u===eo)return{dedupeKey:g,resumeKey:m,output:su(),toolMessage:d,startedAt:y,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let x=this.client.executeWebMcpToolCall(u,d.toolCall?.args,b.signal),T;if(!x)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await x}catch(H){let _=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));return _||this.callbacks.onError?.(H instanceof Error?H:new Error(String(H))),this.markWebMcpToolComplete(d,xa(_?"Aborted by cancel()":Ty(H)),y),this.webMcpInflightKeys.delete(g),null}return b.signal.aborted?(this.markWebMcpToolComplete(d,xa("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:m,output:T,toolMessage:d,startedAt:y,completedAt:Date.now()}})),l=[];try{if(l=i.filter(p=>p!==null),l.length===0)return;let d={};for(let p of l)d[p.resumeKey]=p.output;let u=await this.client.resumeFlow(t,d,{signal:s.signal});if(!u.ok){let p=await u.json().catch(()=>null);throw new Error(p?.error??`Resume failed: ${u.status}`)}for(let p of l)this.webMcpResolvedKeys.add(p.dedupeKey),this.markWebMcpToolComplete(p.toolMessage,p.output,p.startedAt,p.completedAt,p.toolMessage.toolCall?.name===eo?{suggestRepliesResolved:!0}:void 0);u.body&&await this.connectStream(u.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let p of l)this.markWebMcpToolComplete(p.toolMessage,xa("Aborted by cancel()"),p.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let b=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b))return;this.webMcpInflightKeys.add(b);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(b)}catch(x){this.callbacks.onError?.(x instanceof Error?x:new Error(String(x)))}finally{this.webMcpInflightKeys.delete(b)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let u=o===eo,p=t.toolCall?.args,g=u?null:this.client.executeWebMcpToolCall(o,p,d),y="execute",m=i;try{let b;if(u?b=su():g?b=await g:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(t,xa("Aborted by cancel()"),i);return}let x=t.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,x,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,b,i,m,u?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(b){let x=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(y==="execute"||x||d.aborted)&&this.markWebMcpToolComplete(t,xa(x||d.aborted?"Aborted by cancel()":Ty(b)),i),x||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{},...t.presentation?{presentation:t.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=po(this.config.features?.artifacts,t),r=pa(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let t=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=po(this.config.features?.artifacts,n),s=pa(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",t=!0)}t&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Ay(),Sy)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>mu(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=fr(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=gu(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ni(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=gu(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let p=r.approval,g=n.approval;i.approval={...p,...g,executionId:g.executionId||p.executionId,toolName:g.toolName||p.toolName,description:g.description||p.description,toolType:g.toolType??p.toolType,reason:g.reason??p.reason,parameters:g.parameters??p.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,u=n.toolCall?.id;if(l&&Ey(l)&&d&&u&&n.agentMetadata?.awaitingLocalTool===!0){let p=`${d}:${u}`,g=this.webMcpInflightKeys.has(p),y=this.webMcpResolvedKeys.has(p),m=r.toolCall?.name,b=r.agentMetadata?.executionId===d&&r.toolCall?.id===u&&m!==void 0&&Ey(m)&&r.toolCall?.status==="complete";(g||y||b)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};var k=require("lucide"),US={activity:k.Activity,"arrow-down":k.ArrowDown,"arrow-up":k.ArrowUp,"arrow-up-right":k.ArrowUpRight,bot:k.Bot,"chevron-down":k.ChevronDown,"chevron-up":k.ChevronUp,"chevron-right":k.ChevronRight,"chevron-left":k.ChevronLeft,check:k.Check,clipboard:k.Clipboard,"clipboard-copy":k.ClipboardCopy,"code-xml":k.CodeXml,copy:k.Copy,file:k.File,"file-code":k.FileCode,"file-spreadsheet":k.FileSpreadsheet,"file-text":k.FileText,"image-plus":k.ImagePlus,loader:k.Loader,"loader-circle":k.LoaderCircle,mic:k.Mic,paperclip:k.Paperclip,"refresh-cw":k.RefreshCw,search:k.Search,send:k.Send,"shield-alert":k.ShieldAlert,"shield-check":k.ShieldCheck,"shield-x":k.ShieldX,square:k.Square,"thumbs-down":k.ThumbsDown,"thumbs-up":k.ThumbsUp,upload:k.Upload,"volume-2":k.Volume2,x:k.X,user:k.User,mail:k.Mail,phone:k.Phone,calendar:k.Calendar,clock:k.Clock,building:k.Building,"map-pin":k.MapPin,lock:k.Lock,key:k.Key,"credit-card":k.CreditCard,"at-sign":k.AtSign,hash:k.Hash,globe:k.Globe,link:k.Link,"circle-check":k.CircleCheck,"circle-x":k.CircleX,"triangle-alert":k.TriangleAlert,info:k.Info,ban:k.Ban,shield:k.Shield,"arrow-left":k.ArrowLeft,"arrow-right":k.ArrowRight,"external-link":k.ExternalLink,ellipsis:k.Ellipsis,"ellipsis-vertical":k.EllipsisVertical,menu:k.Menu,house:k.House,"panel-left":k.PanelLeft,plus:k.Plus,minus:k.Minus,pencil:k.Pencil,"pen-line":k.PenLine,trash:k.Trash,"trash-2":k.Trash2,save:k.Save,download:k.Download,share:k.Share,funnel:k.Funnel,settings:k.Settings,"rotate-cw":k.RotateCw,maximize:k.Maximize,minimize:k.Minimize,"shopping-cart":k.ShoppingCart,"shopping-bag":k.ShoppingBag,package:k.Package,truck:k.Truck,tag:k.Tag,gift:k.Gift,receipt:k.Receipt,wallet:k.Wallet,store:k.Store,"dollar-sign":k.DollarSign,percent:k.Percent,play:k.Play,pause:k.Pause,"volume-x":k.VolumeX,camera:k.Camera,image:k.Image,film:k.Film,headphones:k.Headphones,"message-circle":k.MessageCircle,"message-square":k.MessageSquare,bell:k.Bell,heart:k.Heart,star:k.Star,eye:k.Eye,"eye-off":k.EyeOff,bookmark:k.Bookmark,"calendar-days":k.CalendarDays,history:k.History,timer:k.Timer,folder:k.Folder,"folder-open":k.FolderOpen,files:k.Files,"chart-column":k.ChartColumn,sparkles:k.Sparkles,zap:k.Zap,sun:k.Sun,moon:k.Moon,flag:k.Flag,lightbulb:k.Lightbulb,monitor:k.Monitor,smartphone:k.Smartphone},de=(e,t=24,n="currentColor",o=2)=>{let r=US[e];return r?qS(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function qS(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([u,p])=>{u!=="stroke"&&d.setAttribute(u,String(p))}),r.appendChild(d)}),r}var Cc={allowedTypes:No,maxFileSize:10*1024*1024,maxFiles:4};function VS(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function KS(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 os=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Cc.allowedTypes,maxFileSize:t.maxFileSize??Cc.maxFileSize,maxFiles:t.maxFiles??Cc.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}remountPreviews(t){if(this.previewsContainer=t,t){t.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Cc.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=ey(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await Zh(n),s=mc(n)?URL.createObjectURL(n):null,i={id:VS(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=mc(t.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let i=v("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=v("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=KS(t.file.type),d=de(l,20,"var(--persona-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=v("span");u.textContent=ty(t.file.type,t.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--persona-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),o.appendChild(i)}let r=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=de("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var My=/\s/;function GS(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
+ `:o===""||My.test(o)}function YS(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let i=e[s];if(i===n)return GS(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(i===`
24
+ `||i==="\uFFFC"||!r&&My.test(i))return null;s--}return null}function ky(e,t,n){for(let o of n){let r=YS(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Py(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Ly(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[t,...n]}var Nt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Xt=1e5,ri=Xt+1;var JS=8,XS=8,hu=10,Hy=200,Iy=300,Ry=0,wc=e=>Math.max(0,e);function Wy(e){e.delayMs!==void 0&&(Hy=wc(e.delayMs)),e.skipDelayMs!==void 0&&(Iy=wc(e.skipDelayMs))}var QS=()=>Date.now()<Ry,ZS=e=>{Ry=e>0?Date.now()+e:0},yu=new WeakMap,By=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,eA=e=>{let t=e.getRootNode?.();return By(t)?t:e.ownerDocument.body},bu=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),tA=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(e=>`--persona-tooltip-${e}`),"--persona-font-family","--persona-radius-sm"];function Qt(e){yu.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,hint:r,enabled:s=!0,gap:i=JS,viewportPadding:l=XS}=e,d=()=>t.ownerDocument,u=()=>d().defaultView??window,p=null,g=null,y=null,m=null,b,x=!1,T=!1,H=!1,_=()=>(typeof o=="function"?o():o).trim(),P=()=>(typeof r=="function"?r():r??"").trim(),A=()=>wc(e.delayMs??Hy),B=()=>wc(e.skipDelayMs??Iy),R=()=>{b!==void 0&&(u().clearTimeout(b),b=void 0)},W=()=>{R();let ae=p!==null;m?.(),m=null,p?.remove(),p=null,g=null,y=null,ae&&ZS(B())},U=()=>{if(!p)return;let ae=d(),M=u(),ee=t.getBoundingClientRect(),pe=p.getBoundingClientRect(),we=ae.documentElement.clientWidth||M.innerWidth,me=ae.documentElement.clientHeight||M.innerHeight,Se=we-l-pe.width,Le=ee.left+ee.width/2-pe.width/2,He=bu(Le,l,Se),Qe=ee.top-l,Oe=me-l-ee.bottom,We=pe.height+i,tt=Qe>=We||Qe>=Oe?"top":"bottom",ve=tt==="top"?ee.top-i-pe.height:ee.bottom+i,Ne=me-l-pe.height,ft=bu(ve,l,Ne),Ae=ee.left+ee.width/2,Fe=Math.max(hu,pe.width-hu),at=bu(Ae-He,hu,Fe);p.dataset.placement=tt,p.style.left=`${He}px`,p.style.top=`${ft}px`,p.style.setProperty("--persona-tooltip-arrow-x",`${at}px`)},V=()=>{if(H||!s||p||!t.isConnected)return;let ae=_(),M=eA(t);if(!ae||!M)return;let ee=d(),pe=u();p=ee.createElement("div"),p.className="persona-control-tooltip",p.setAttribute("role","tooltip"),p.dataset.state="measuring",p.style.zIndex=String(ri);let we=pe.getComputedStyle?.(t);if(we){for(let We of tA){let tt=we.getPropertyValue(We).trim();tt&&p.style.setProperty(We,tt)}we.fontFamily&&(p.style.fontFamily=we.fontFamily)}g=ee.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ae,p.appendChild(g);let me=P();me&&(y=ee.createElement("span"),y.className="persona-control-tooltip__hint",y.textContent=me,p.appendChild(y));let Se=ee.createElement("span");Se.className="persona-control-tooltip__arrow",p.appendChild(Se),M.appendChild(p),U(),p.dataset.state="open";let Le=()=>{if(!t.isConnected){W();return}g&&(g.textContent=_()),y&&(y.textContent=P()),U()};pe.addEventListener("scroll",Le,!0),pe.addEventListener("resize",Le);let He=t.getRootNode(),Qe=By(He)?He:ee.documentElement,Oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||W()});Oe?.observe(Qe,{childList:!0,subtree:!0}),m=()=>{pe.removeEventListener("scroll",Le,!0),pe.removeEventListener("resize",Le),Oe?.disconnect()}},Z=ae=>{if(!(H||p)){if(R(),ae||A()<=0||QS()){V();return}b=u().setTimeout(()=>{b=void 0,V()},A())}},j=()=>{x||T?Z(T):W()},X=()=>{let ae=u();(!ae.matchMedia||!ae.matchMedia("(hover: none)").matches)&&(x=!0,j())},ue=()=>{x=!1,j()},xe=()=>{try{T=t.matches(":focus-visible")}catch{T=!0}j()},Ce=()=>{T=!1,j()},ye=()=>{x=!1,T=!1,W()},oe=ae=>{ae.key==="Escape"&&ye()};n.addEventListener("mouseenter",X),n.addEventListener("mouseleave",ue),t.addEventListener("focus",xe),t.addEventListener("blur",Ce),t.addEventListener("keydown",oe),t.addEventListener("click",ye);let le={get isOpen(){return p!==null},show:V,hide:W,reposition:U,destroy:()=>{H||(H=!0,W(),n.removeEventListener("mouseenter",X),n.removeEventListener("mouseleave",ue),t.removeEventListener("focus",xe),t.removeEventListener("blur",Ce),t.removeEventListener("keydown",oe),t.removeEventListener("click",ye),yu.delete(t))}};return yu.set(t,le),le}function Oy(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",d=v("div","persona-send-button-wrapper"),u=ge("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),p=de(i,s,"currentColor",1.5);return p?u.appendChild(p):u.textContent="+",u.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),d.appendChild(u),Qt({anchor:u,trigger:d,text:()=>u.getAttribute("aria-label")??l}),{button:u,wrapper:d}}var{setLoader:N0,load:nA}=lo({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var vu=nA;var{setLoader:j0,load:oA}=lo({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Dy=oA;function Ta(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ge("span",{className:jn("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=de(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ge("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function _y(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Ly(t).filter(P=>P.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(P=>P.sources.some(A=>typeof A.matchCommand=="function")),r=P=>o.some(A=>A.trigger?A.position==="line-start"?P.split(`
25
+ `).some(R=>R.startsWith(A.trigger)):(A.position==="anywhere"?P:P.split(`
26
+ `)[0]).startsWith(A.trigger):!1),s=(P,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${P}`,{detail:A}))}catch{}},i=ge("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,d=null,u=e.textarea,p=null,g=null,y=null,m=null,b=()=>{if(l)return Promise.resolve(l);if(d)return d;let P=vu().then(A=>(l=A.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:p??void 0,anchor:e.anchor,contextRow:i,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:_,emit:s}),l)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),d===P&&(d=null),null));return d=P,P},x=()=>{Dy().then(P=>{let A=P.mountInlineComposer({textarea:e.textarea,renderToken:R=>Ta(R,{render:t.renderMentionToken}),onMentionRemoved:R=>l?.untrackMention(R)});p=A.input,g=A.destroy;let B=u;B.replaceWith(A.element),u=A.element,m={next:A.element,prev:B},y?.(A.element,B),l?l.rebindComposer(A.input):d&&d.then(R=>R?.rebindComposer(A.input))}).catch(P=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",P)})};t.display==="inline"&&x();let T=[],H=new Map;for(let P of n){if(!P.showButton)continue;let A=Oy({config:{...t,buttonIconName:P.buttonIconName,buttonTooltipText:P.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(B=>B?.openMenu(P.trigger))}});T.push(A),H.set(P.trigger,A.button)}let _=(P,A,B)=>{let R=H.get(A);R&&(R.setAttribute("aria-expanded",P?"true":"false"),P?R.setAttribute("aria-controls",B):R.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(P=>P.wrapper),contextRow:i,handleInput:P=>{if(l){l.handleInput();return}if(!Py(P))return;let A=u,B=A.selectionStart??0;ky(A.value,B,n)&&b().then(R=>R?.handleInput())},handleKeydown:P=>{if(l?.isMenuOpen())return l.handleKeydown(P);if(P.key==="Backspace"&&l?.hasMentions()&&!m){let A=u,B=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||B)&&l.removeLastChip())return P.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async P=>r(P)?(l??await b())?.dispatchInlineCommand(P)??null:null,clear:()=>l?.clear(),prefetch:()=>{vu().catch(()=>{})},onComposerSwap:P=>{y=P,m&&P(m.next,m.prev)},destroy:()=>{l?.destroy(),g?.();for(let P of T)P.wrapper.remove();i.remove()}}}var Ny=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function si(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Ny(s)&&Ny(r)?n[o]=si(s,r):n[o]=r}return n}var Hn="min(440px, calc(100vw - 24px))",xc="440px",rA={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:Hn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Xe={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:rA,copy:{inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Fy(e,t){if(!(!e&&!t))return e?t?si(e,t):e:t}function ii(e){return e?{...Xe,...e,theme:Fy(Xe.theme,e.theme),darkTheme:Fy(Xe.darkTheme,e.darkTheme),launcher:{...Xe.launcher,...e.launcher,dock:{...Xe.launcher?.dock,...e.launcher?.dock},clearChat:{...Xe.launcher?.clearChat,...e.launcher?.clearChat}},tooltip:{...Xe.tooltip,...e.tooltip},copy:{...Xe.copy,...e.copy},sendButton:{...Xe.sendButton,...e.sendButton},statusIndicator:{...Xe.statusIndicator,...e.statusIndicator},voiceRecognition:{...Xe.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=Xe.features?.artifacts,n=e.features?.artifacts,o=Xe.features?.scrollToBottom,r=e.features?.scrollToBottom,s=Xe.features?.scrollBehavior,i=e.features?.scrollBehavior,l=Xe.features?.streamAnimation,d=e.features?.streamAnimation,u=Xe.features?.askUserQuestion,p=e.features?.askUserQuestion,g=Xe.features?.history,y=e.features?.history,m=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},x=s===void 0&&i===void 0?void 0:{...s,...i},T=l===void 0&&d===void 0?void 0:{...l,...d},H=u===void 0&&p===void 0?void 0:{...u,...p,styles:{...u?.styles,...p?.styles}},_=g===void 0&&y===void 0?void 0:{...g,...y,copy:{...g?.copy,...y?.copy}};return{...Xe.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...x!==void 0?{scrollBehavior:x}:{},...m!==void 0?{artifacts:m}:{},...T!==void 0?{streamAnimation:T}:{},...H!==void 0?{askUserQuestion:H}:{},..._!==void 0?{history:_}:{}}})(),suggestionChips:e.suggestionChips??Xe.suggestionChips,suggestionChipsConfig:{...Xe.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Xe.layout,...e.layout,header:{...Xe.layout?.header,...e.layout?.header},messages:{...Xe.layout?.messages,...e.layout?.messages,avatar:{...Xe.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...Xe.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...Xe.layout?.slots,...e.layout?.slots}},markdown:{...Xe.markdown,...e.markdown,options:{...Xe.markdown?.options,...e.markdown?.options}},messageActions:{...Xe.messageActions,...e.messageActions}}:Xe}var Sc="16px",Ac="transparent",wu={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"}},xu={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"}},Su={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Hn,maxWidth:xc,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Sc,canvasBackground:Ac},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function pn(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?pn(e,o):o}function Tc(e){let t={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let d=pn(e,i);d!==void 0&&(t[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Au(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 $y(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=$y(s,r):n[o]=r}return n}function sA(e,t){return t?$y(e,t):e}function Ea(e,t={}){let n={palette:wu,semantic:xu,components:Su},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:sA(n.components,e?.components)};if(t.validate!==!1){let r=Au(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}var Cu=e=>e.trim()==="0"?"0px":e;function Ec(e){let t=Tc(e),n={};for(let[M,ee]of Object.entries(t)){let pe=M.replace(/\./g,"-");n[`--persona-${pe}`]=ee.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-surface"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-primary"];let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Sc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ac,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"];let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],i=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??i??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??i??n["--persona-muted"],n["--persona-header-control-size"]=n["--persona-components-header-controlSize"]??"32px",n["--persona-header-control-icon-size"]=n["--persona-components-header-controlIconSize"]??"20px";let l=e.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let u=n["--persona-components-history-railHeader-border"];u&&(n["--persona-history-rail-header-border"]=u);let p=n["--persona-components-history-railHeader-minHeight"];p&&(n["--persona-history-rail-header-min-height"]=p);for(let[M,ee]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let pe=n[`--persona-components-history-overlay-${M}`];pe&&(n[`--persona-history-overlay-${ee}`]=pe)}for(let[M,ee]of[["background","bg"],["borderRadius","radius"]]){let pe=n[`--persona-components-history-menu-${M}`];pe&&(n[`--persona-history-menu-${ee}`]=pe)}let g=e.components?.history?.motion;if(g){let M=we=>{if(we===void 0)return;let me=String(we).trim();return/^\d+(\.\d+)?$/.test(me)?`${me}ms`:me},ee=M(g.enterDurationMs);ee!==void 0&&(n["--persona-history-enter-ms"]=ee);let pe=M(g.exitDurationMs);pe!==void 0&&(n["--persona-history-exit-ms"]=pe),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let y=n["--persona-components-history-dangerForeground"];y&&(n["--persona-history-danger-fg"]=y),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let M of["scrim","shadow"]){let ee=n[`--persona-components-history-confirm-${M}`];ee&&(n[`--persona-history-confirm-${M}`]=ee)}for(let[M,ee]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let pe=n[`--persona-components-tooltip-${M}`];pe&&(n[`--persona-tooltip-${ee}`]=pe)}e.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[M,ee]of[["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let pe=n[`--persona-components-messageActions-${M}`];pe&&(n[`--persona-message-action-${ee}`]=pe)}n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let m=n["--persona-components-introCard-background"],b=n["--persona-components-introCard-shadow"],x=(!m||m==="transparent"||m==="none")&&(!b||b==="none"),T=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=x&&T==="1.5rem"?"1.5rem 0":T,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let H=n["--persona-components-markdown-heading-h1-fontSize"];H&&(n["--persona-md-h1-size"]=H);let _=n["--persona-components-markdown-heading-h1-fontWeight"];_&&(n["--persona-md-h1-weight"]=_);let P=n["--persona-components-markdown-heading-h2-fontSize"];P&&(n["--persona-md-h2-size"]=P);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let B=n["--persona-components-markdown-prose-fontFamily"];B&&B!=="inherit"&&(n["--persona-md-prose-font-family"]=B),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let R=e.components,W=R?.iconButton;W&&(W.background&&(n["--persona-icon-btn-bg"]=W.background),W.border&&(n["--persona-icon-btn-border"]=W.border),W.color&&(n["--persona-icon-btn-color"]=W.color),W.padding&&(n["--persona-icon-btn-padding"]=W.padding),W.borderRadius&&(n["--persona-icon-btn-radius"]=W.borderRadius),W.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=W.hoverBackground),W.hoverColor&&(n["--persona-icon-btn-hover-color"]=W.hoverColor),W.activeBackground&&(n["--persona-icon-btn-active-bg"]=W.activeBackground),W.activeBorder&&(n["--persona-icon-btn-active-border"]=W.activeBorder));let U=R?.labelButton;U&&(U.background&&(n["--persona-label-btn-bg"]=U.background),U.border&&(n["--persona-label-btn-border"]=U.border),U.color&&(n["--persona-label-btn-color"]=U.color),U.padding&&(n["--persona-label-btn-padding"]=U.padding),U.borderRadius&&(n["--persona-label-btn-radius"]=U.borderRadius),U.hoverBackground&&(n["--persona-label-btn-hover-bg"]=U.hoverBackground),U.fontSize&&(n["--persona-label-btn-font-size"]=U.fontSize),U.gap&&(n["--persona-label-btn-gap"]=U.gap));let V=R?.toggleGroup;V&&(V.gap&&(n["--persona-toggle-group-gap"]=V.gap),V.borderRadius&&(n["--persona-toggle-group-radius"]=V.borderRadius));let Z=R?.artifact;if(Z?.toolbar){let M=Z.toolbar;M.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=M.iconHoverColor),M.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=M.iconHoverBackground),M.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=M.iconPadding),M.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=M.iconBorderRadius),M.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=M.iconBorder),M.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Cu(M.toggleGroupGap)),M.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=M.toggleBorderRadius),M.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Cu(M.toggleGroupPadding)),M.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=M.toggleGroupBorder),M.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=M.toggleGroupBorderRadius),M.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=pn(e,M.toggleGroupBackground)??M.toggleGroupBackground),M.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=M.copyBackground),M.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=M.copyBorder),M.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=M.copyColor),M.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Cu(M.copyBorderRadius)),M.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=M.copyPadding),M.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=M.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??M.copyMenuBackground),M.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=M.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??M.copyMenuBorder),M.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=M.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??M.copyMenuShadow),M.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=M.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??M.copyMenuBorderRadius),M.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=M.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??M.copyMenuItemHoverBackground),M.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=M.iconBackground),M.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=M.toolbarBorder)}if(Z?.tab){let M=Z.tab;M.background&&(n["--persona-artifact-tab-bg"]=M.background),M.activeBackground&&(n["--persona-artifact-tab-active-bg"]=M.activeBackground),M.activeBorder&&(n["--persona-artifact-tab-active-border"]=M.activeBorder),M.borderRadius&&(n["--persona-artifact-tab-radius"]=M.borderRadius),M.textColor&&(n["--persona-artifact-tab-color"]=M.textColor),M.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=M.hoverBackground),M.listBackground&&(n["--persona-artifact-tab-list-bg"]=M.listBackground),M.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=M.listBorderColor),M.listPadding&&(n["--persona-artifact-tab-list-padding"]=M.listPadding)}if(Z?.pane){let M=Z.pane;if(M.toolbarBackground){let ee=pn(e,M.toolbarBackground)??M.toolbarBackground;n["--persona-artifact-toolbar-bg"]=ee}}if(Z?.card){let M=Z.card;M.background&&(n["--persona-artifact-card-bg"]=M.background),M.border&&(n["--persona-artifact-card-border"]=M.border),M.borderRadius&&(n["--persona-artifact-card-radius"]=M.borderRadius),M.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=M.hoverBackground),M.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=M.hoverBorderColor)}if(Z?.inline){let M=Z.inline;M.background&&(n["--persona-artifact-inline-bg"]=pn(e,M.background)??M.background),M.border&&(n["--persona-artifact-inline-border"]=M.border),M.borderRadius&&(n["--persona-artifact-inline-radius"]=M.borderRadius),M.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=pn(e,M.chromeBackground)??M.chromeBackground),M.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=pn(e,M.chromeBorder)??M.chromeBorder),M.titleColor&&(n["--persona-artifact-inline-title-color"]=pn(e,M.titleColor)??M.titleColor),M.mutedColor&&(n["--persona-artifact-inline-muted-color"]=pn(e,M.mutedColor)??M.mutedColor),M.frameHeight&&(n["--persona-artifact-inline-frame-height"]=M.frameHeight)}let j=R?.code;j&&(j.keywordColor&&(n["--persona-code-keyword-color"]=j.keywordColor),j.stringColor&&(n["--persona-code-string-color"]=j.stringColor),j.commentColor&&(n["--persona-code-comment-color"]=j.commentColor),j.numberColor&&(n["--persona-code-number-color"]=j.numberColor),j.tagColor&&(n["--persona-code-tag-color"]=j.tagColor),j.attrColor&&(n["--persona-code-attr-color"]=j.attrColor),j.propertyColor&&(n["--persona-code-property-color"]=j.propertyColor),j.lineNumberColor&&(n["--persona-code-line-number-color"]=j.lineNumberColor),j.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=j.gutterBorderColor),j.background&&(n["--persona-code-bg"]=pn(e,j.background)??j.background));let X=n["--persona-surface"],ue=n["--persona-container"],xe=n["--persona-palette-colors-gray-100"]??"#f3f4f6",Ce=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ye=n["--persona-palette-colors-gray-300"]??"#d1d5db",oe=!ue||ue===X,le=oe?xe:ue,ae=oe?Ce:ue;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??le,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ae,oe&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ye),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??le,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??le,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??le,n}var jy={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 iA={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"}}},aA={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},zy=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ma=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",lA=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ma()},Mc=e=>lA(e),cA=e=>Ea(e),dA=e=>{let t=si(aA,e??{})??{};return Ea({...t,palette:{...t.palette,colors:{...iA.colors,...t.palette?.colors}}},{validate:!1})},yr=e=>{let t=Mc(e),n=zy(e?.theme),o=zy(e?.darkTheme);return t==="dark"?dA(si(n??{},o??{})):cA(n)},pA=e=>Ec(e),rs=(e,t)=>{let n=yr(t),o=pA(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Mc(t))},ai=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ma())});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(Ma());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};var br=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Uy=null;var Tu=()=>{if(Uy!==null)return Uy;if(typeof navigator>"u")return!1;let t=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(t)},uA="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",kc=(e,t)=>{console.warn(`[persona] ${e} shortcut: ${t}`)},Pc=e=>{let t=e.toLowerCase().split("+").map(r=>r.trim()),n=t.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of t)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return kc("unknown modifier in",e),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(kc("unsupported",e),null):(n==="space"&&(o.key=" "),o)},gA=e=>uA.split(" ").find(t=>t.toLowerCase()===e)??(e===" "?"Space":e.length===1?e.toUpperCase():e[0].toUpperCase()+e.slice(1)),qy=(e,t)=>{let n=Pc(e);if(!n)return"";let o=Tu(),r=gA(n.key);if(!t&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[t?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},Lc=e=>qy(e,!1),ka=e=>qy(e,!0),fA=(e,t)=>t.key?.toLowerCase()===e.key&&(Tu()?t.metaKey:t.ctrlKey)===e.mod&&!(Tu()?t.ctrlKey:t.metaKey)&&t.shiftKey===e.shift&&t.altKey===e.alt,mA=e=>{if(!(e instanceof HTMLElement))return!1;let t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable},Vy=e=>{let t=new Map,n=e?.ownerDocument??(typeof document<"u"?document:null),o=(s,i)=>{if((s.scope??"widget")==="page")return!0;if(!e)return!1;let l=i.composedPath?.();return l?.length?l.includes(e):e.contains(i.target)},r=s=>{if(s.isComposing||!t.size)return;let i=s.composedPath?.()[0]??s.target;for(let l of t.values())if(fA(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&mA(i))){s.preventDefault();try{l.run(s)}catch(d){kc(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let i=Pc(s.combo);if(!i)return()=>{};let l=`${i.mod?"m":""}${i.shift?"s":""}${i.alt?"a":""}${i.key}`,d=t.get(l);return d?(kc(`${d.id} already owns`,s.combo),()=>{}):(t.set(l,{...s,parsed:i}),s.element?.setAttribute("aria-keyshortcuts",ka(s.combo)),()=>{t.get(l)?.id===s.id&&t.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){t.clear(),n?.removeEventListener("keydown",r)}}};function mo(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Ky(e){let t=mo(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Hc(e){if(typeof e!="string")return"";let t=e.indexOf(`
27
27
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
28
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Sr(e){let t=Ef(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 jo(e){switch(Sr(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Ef(e.path);return t?t.toUpperCase():"File"}}}function Mf(e){let t=e.markdown??"";return e.file?{filename:jn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Vi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var pd="http://www.w3.org/2000/svg";function kf(e){let t=document.createElementNS(pd,"svg");t.setAttribute("class",Hn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(pd,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(pd,"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 Uo=(e,t,n)=>{let o=n;for(let r of t){let s=y("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Lf(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Uo(e,t,0)}var ud="persona-artifact-status-label",Pf="persona-artifact-status-detail",Rf="data-artifact-status-label",gd=new Map,If=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function us(e){e&&gd.delete(e)}function Dv(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?jo(t):e.artifactType==="component"?"Component":"Document"}function gs(e,t,n){let o=Dv(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=gd.get(a);e.status!=="complete"&&i===void 0&&(i=If(),gd.set(a,i));let p=i===void 0?0:Math.max(0,If()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",g=d?0:c.length,b=d||c===""?0:c.split(`
29
- `).length,f=e.artifactType==="markdown"?e.file:void 0,x={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:g,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(x);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:r}}catch{return{label:r}}}function Ov(e){e.className=ud,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 Tr(e,t,n){let o=e.querySelector(`:scope > .${ud}`);o||(o=y("span",ud),e.appendChild(o)),o.getAttribute(Rf)!==t.label&&(Ov(o),Lf(o,t.label,n),o.setAttribute(Rf,t.label));let r=e.querySelector(`:scope > .${Pf}`),s=t.detail;s?(r||(r=y("span",Pf),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var Nv={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"},Fv=15e4,Ki={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 _v(e,t){let n=(e||"").trim().toLowerCase();if(n&&Ki[n])return Ki[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Ki[r])return Ki[r]}}return null}function Gi(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,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){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var $v=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"]),jv=[{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=>$v.has(e)?"keyword":"plain"}];function Wf(e){return Gi(e,jv)}var Uv=[{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 zv(e){let t=Gi(e,Uv);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var qv=[{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 Hf(e){let t=Gi(e,qv),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let 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===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var Vv=[{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 Kv(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of Gi(p,Vv))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),f=b?r+b.index:o,x=e.slice(r,f),C=c==="script"?Wf(x):Hf(x);for(let S of C)t.push(S);r=f}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function Gv(e,t){switch(t){case"html":return Kv(e);case"css":return Hf(e);case"js":return Wf(e);case"json":return zv(e)}}function Jv(e){let t=Sg(),n=y("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=Nv[r];if(a){let i=y("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
30
- `);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
- `)),n=y("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Bf(e,t,n){let o=e.length<=Fv?_v(t,n):null,r=o?Gv(e,o):[{type:"plain",value:e}];return Jv(r)}function zo(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Fi)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",f.id),f.destructive&&x.setAttribute("data-destructive",""),f.icon){let S=se(f.icon,16,"currentColor",1.5);S&&x.appendChild(S)}let C=document.createElement("span");C.textContent=f.label,x.appendChild(C),x.addEventListener("click",S=>{S.stopPropagation(),c(),n(f.id)}),a.appendChild(x)}let i=null;function p(){if(!s)return;let f=o.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=x=>{!a.contains(x.target)&&!o.contains(x.target)&&c()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function g(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:g,destroy:b}}function it(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=y("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=se(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,g]of Object.entries(i))p.setAttribute(c,g);return p}function lo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=y("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=se(t,s??14,"currentColor",2);b&&c.appendChild(b)}let g=y("span");if(g.textContent=n,c.appendChild(g),i&&c.addEventListener("click",i),p)for(let[b,f]of Object.entries(p))c.setAttribute(b,f);return c}function co(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=y("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let g;c.icon?g=it({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(g=y("button","persona-icon-btn"+(c.className?" "+c.className:"")),g.type="button",g.setAttribute("aria-label",c.label),g.title=c.label,g.textContent=c.label,g.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),g.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:g}),s.appendChild(g)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Ji(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=y("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=y("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let g=se(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",d.appendChild(g)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=zo({items:o,onSelect:f=>{d.setAttribute("aria-expanded","false"),r(f)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",f=>{f.stopPropagation();let x=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",x?"false":"true"),b.toggle()}),d.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),d.click())}),{element:d,setLabel:f=>{c.textContent=f,d.setAttribute("aria-label",f)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var Yi="persona-artifact-custom-action-btn";function fs(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Yi+(n?" persona-artifact-doc-copy-btn":"");o=y("button",r)}else{let r="persona-icon-btn "+Yi+(n?" persona-artifact-doc-icon-btn":"");o=y("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=y("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=lo({icon:e.icon,label:e.label,className:Yi+(n?" persona-artifact-doc-copy-btn":"")}):o=it({icon:e.icon,label:e.label,className:Yi+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function ma(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 Df(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?jn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?jo(n):i==="component"?"Component":"Document",c=document.createElement("div");c.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let x=document.createElement("div");if(x.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",x.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let C=t?.config?.features?.artifacts,S={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},k=gs(S,C,"card");Tr(x,k,C)}else s&&us(s),x.textContent=d;if(b.append(f,x),c.append(g,b),a==="complete"){let C=t?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let k={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let R of C)try{if(R.visible===void 0||R.visible(k)){let E=fs(R);E.setAttribute("data-artifact-custom-action",R.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let S=lo({label:"Download",className:"persona-flex-shrink-0"});S.title=`Download ${r}`,S.setAttribute("data-download-artifact",s),c.append(S)}return c}var Xi=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Df(e,t)});if(i)return i}return Df(e,t)};var qo=new WeakMap;function fd(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=qo.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function $f(e){return qo.has(e)}function Yv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let a=e.componentProps,i=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:i,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Of(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?jn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?jo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Xv(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 Nf=180,Qv=240,Zv=.8,ex=300,tx=500,nx="cubic-bezier(0.2, 0, 0, 1)",Ff=240,ox=.35;function rx(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:Nf,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let k of a)k.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(tx,Math.max(ex,Qv+d*Zv))),g=Math.round(c*ox),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:Ff,delay:g,easing:"ease-out",fill:"backwards"}):null,x=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:nx});e.style.height=`${p}px`;let C=!1,S=()=>{C||(C=!0,i(),r())};Promise.allSettled([x.finished,f?.finished].filter(Boolean)).then(S),window.setTimeout(S,Math.max(c,g+Ff)+120)},Nf)}function sx(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 ha="--persona-artifact-inline-body-height";function ax(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,g=t?.fadeMask;g===!0?(d=!0,c=!0):g===!1?(d=!1,c=!1):g&&typeof g=="object"?(d=g.top===!0,c=g.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let b=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:f}}function _f(e,t){let n=Yv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=sx(o),p=o?.inlineActions??[],d=ax(o),c=d.completeDisplay==="card",g=null,b=n,f=y("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let x=ee=>Xi(Xv(ee),t),C=ee=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(ha),f.replaceChildren(x(ee)),qo.set(f,ge=>{f.replaceChildren(x(ge))})};if(c&&n.status==="complete")return C(n),f;let S=Qi(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>g??d.viewMode}),k=y("div","persona-artifact-inline-body");k.appendChild(S.el);let R=ee=>{let ge=ee.status!=="complete",ne=ge?d.streamingHeight:d.completeHeight,me=typeof ne=="number";me?f.style.setProperty(ha,`${ne}px`):f.style.removeProperty(ha);let ve=!!S.el.querySelector(".persona-code-pre"),ye=!!S.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",ve),k.classList.toggle("persona-artifact-inline-body--sized",me&&ye),k.classList.toggle("persona-artifact-inline-body--cap",!ge&&!ye&&typeof d.completeHeight=="number")},E=n.status,P=(ee,ge)=>{E!=="complete"&&ee.status==="complete"?(typeof d.completeHeight=="number"?f.style.setProperty(ha,`${d.completeHeight}px`):f.style.removeProperty(ha),Uf(k,ge?.suppressTransition?"none":d.transition,ee.id,()=>{S.update(ee),R(ee)})):S.update(ee),R(ee),E=ee.status};R(n);let B=d.overflow==="clip"&&a&&!!n.id;if(B&&(k.setAttribute("data-expand-artifact-inline",n.id),k.setAttribute("role","button"),k.setAttribute("tabindex","0"),k.classList.add("persona-cursor-pointer"),k.setAttribute("aria-label",`Open ${Of(n).title} in panel`)),!r)return f.appendChild(k),qo.set(f,P),f;let N=y("div","persona-artifact-inline-chrome");N.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let $=y("div","persona-artifact-inline-chrome-lead"),z=y("span","persona-flex persona-items-center persona-flex-shrink-0"),q=se("file-text",16,"currentColor",2);q&&z.appendChild(q);let X=y("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),A=y("span","persona-artifact-inline-type");$.append(z,X,A);let J=y("div","persona-artifact-inline-chrome-actions"),Z=y("span","persona-flex persona-items-center persona-gap-1"),ce=()=>g??d.viewMode,Y=i?co({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:ce(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ee=>{let ge=ee==="source"?"source":"rendered";ge!==ce()&&(g=ge,S.update(b),R(b))}}):null,he=s?it({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;he&&n.id&&he.setAttribute("data-copy-artifact",n.id);let te=a?it({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;te&&n.id&&te.setAttribute("data-expand-artifact-inline",n.id),J.appendChild(Z),Y&&J.appendChild(Y.element),he&&J.appendChild(he),te&&J.appendChild(te),N.append($,J),f.append(N,k);let be=ee=>{let{title:ge,typeLabel:ne}=Of(ee);X.textContent=ge,X.title=ge,B&&k.setAttribute("aria-label",`Open ${ge} in panel`);let me=ee.status!=="complete";if(me){A.classList.contains("persona-artifact-inline-status")||(A.className="persona-artifact-inline-status",A.removeAttribute("data-preserve-animation"),A.replaceChildren());let ve=gs(ee,o,"inline-chrome");Tr(A,ve,o)}else us(ee.id),A.className="persona-artifact-inline-type",A.removeAttribute("data-preserve-animation"),A.replaceChildren(),A.textContent=ne;if(he&&he.classList.toggle("persona-hidden",me),Y){let ve=ee.artifactType==="markdown"?ee.file:void 0,ye=!1;if(!me&&ve&&d.viewMode!=="source"){let De=Sr(ve);De==="markdown"?ye=!0:(De==="html"||De==="svg")&&(ye=o?.filePreview?.enabled!==!1)}Y.element.classList.toggle("persona-hidden",!ye),Y.setSelected(ce())}if(Z.replaceChildren(),!me&&p.length>0){let ve=ma(ee);if(ve)for(let ye of p)try{if(ye.visible===void 0||ye.visible(ve)){let De=fs(ye,{documentChrome:!0});De.setAttribute("data-artifact-custom-action",ye.id),De.classList.add("persona-flex-shrink-0"),Z.appendChild(De)}}catch{}}};return be(n),qo.set(f,(ee,ge)=>{if(c&&E!=="complete"&&ee.status==="complete"){let ne=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let me=ee,ve=!1,ye=De=>{me=De,ve=!0};qo.set(f,ye),rx(f,ne,{swap:()=>{C(me),ve=!1,qo.set(f,ye)},onSettled:()=>{ve?C(me):qo.set(f,De=>{f.replaceChildren(x(De))})}});return}(ee.status!=="complete"||ee.id!==b.id)&&(g=null),b=ee,P(ee,ge),be(ee)}),f}var jf=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>_f(e,t)});if(i)return i}return _f(e,t)};var md=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)})}},Dn=new md;Dn.register("PersonaArtifactCard",Xi,{bubbleChrome:!1});Dn.register("PersonaArtifactInline",jf,{bubbleChrome:!1});function ya(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Vi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var hd=!1;function ix(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Uf(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||hd||s){o();return}hd=!0;let a=ix(n);e.style.setProperty("view-transition-name",a);let i=()=>{hd=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var lx="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",cx="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function dx(e){let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function px(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 ux=220;function gx(){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 fx(e){return`
32
- <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function mx(e,t,n){let o=y("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=y("div","persona-artifact-frame-loading-indicator");r.appendChild(kf());let s=null;return n.label!==!1&&(s=y("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function hx(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(E=>clearTimeout(E)),d.clear()},g=(E,P)=>{let B=setTimeout(()=>{d.delete(B),E()},P);d.add(B)},b=()=>{a&&a.parentElement&&a.remove(),a=null},f=()=>{if(a||p)return;let E=mx(r,s,o);a=E.el,e.appendChild(a),i=Date.now(),o.label!==!1&&g(E.revealLabel,o.labelDelayMs)},x=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),g(b,ux))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",R)},S=()=>{if(p||(p=!0,C(),c(),!a))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-i));E>0?g(x,E):x()};function k(E){if(n===null)return;let P=E.data;!P||P.persona!=="artifact-preview-ready"||P.token!==n||E.source===t.contentWindow&&S()}function R(){let E=P=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>P()):setTimeout(P,0)};E(()=>E(()=>S()))}return g(f,o.delayMs),g(S,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",k):t.addEventListener("load",R),()=>{p=!0,c(),C(),b()}}function Qi(e,t){let{config:n}=t,o=t.registry??Dn,r=t.bodyLayout,s=n.markdown?hr(n.markdown):null,a=es(n.sanitize),i=e,p=!1,d=te=>{let be=no()!==null;s&&!be&&!p&&(p=!0,Zr(()=>he(i)));let ee=s?s(te):_n(te);return s&&be&&a?a(ee):ee},c=y("div","persona-artifact-preview-body"),g=null,b=null,f=null,x=()=>{f&&(f(),f=null),g=null,b=null},C=null,S=null,k=null,R=!1,E=()=>{C=null,S=null,k=null,R=!1},P=null,B=null,N=()=>{P=null,B=null},$=40,z=0,q=te=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>te()):setTimeout(te,0),X=te=>te.scrollHeight-te.clientHeight-te.scrollTop<=$,A=te=>{if(!r)return;let be=te.scrollHeight-te.clientHeight>1,ee=te.scrollHeight-te.clientHeight-te.scrollTop;te.classList.toggle("persona-artifact-fade-top",r.fadeTop&&be&&te.scrollTop>1),te.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&be&&ee>1)},J=te=>{z||(z=q(()=>{z=0,te.scrollTop=te.scrollHeight,A(te)}))},Z=(te,be,ee,ge)=>{let ne=!!r,me=ee.id+"|"+(ne?"w":"p");if(!C||k!==me||C.parentElement!==c){x(),N(),c.replaceChildren();let De=y("pre",lx+" persona-code-pre"),at=y("code","persona-code");if(De.appendChild(at),ne){let je=y("div","persona-artifact-source-window");if(je.appendChild(De),c.appendChild(je),!(r?.overflow==="clip")&&typeof je.addEventListener=="function"){let Pe=()=>je.scrollHeight-je.clientHeight>1;je.addEventListener("scroll",()=>{X(je)&&(R=!1),A(je)},{passive:!0}),je.addEventListener("wheel",$e=>{Pe()&&$e.deltaY<0&&(R=!0)},{passive:!0}),je.addEventListener("touchmove",()=>{Pe()&&(R=!0)},{passive:!0})}C=je}else c.appendChild(De),C=De;S=at,k=me}let ve=ne?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ge),ve.classList.toggle("persona-artifact-source-window--clip",ge&&r?.overflow==="clip"));let ye=ve?X(ve):!0;if(S.replaceChildren(Bf(te,be?.language,be?.path)),ve){let De=ee.status!=="complete";ge&&De&&r?.followOutput&&!R&&ye?J(ve):De||(R=!1),A(ve)}},ce=te=>{x(),E(),N(),c.replaceChildren();let be=y("div",cx);be.innerHTML=d(te),c.appendChild(be)},Y=te=>{let be=te.id,ee=n.features?.artifacts,ge=gs(te,ee,"status-body");if(P&&B===be&&P.parentElement===c){let ve=P.querySelector(".persona-artifact-status-view-text");ve&&Tr(ve,ge,ee);return}x(),E(),c.replaceChildren();let ne=y("div","persona-artifact-status-view"),me=y("div","persona-artifact-status-view-text");Tr(me,ge,ee),ne.appendChild(me),c.appendChild(ne),P=ne,B=be},he=te=>{i=te;let be=t.resolveViewMode?.(te)??r?.viewMode??"rendered",ee=te.artifactType==="markdown"?te.file:void 0,ge=te.status!=="complete";ge||us(te.id);let ne=ge?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ne=="number";if(r?.streamingView==="status"&&ge){Y(te);return}if(ee){let ye=Vi(te.markdown??""),De=Sr(ee),at=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ge&&be==="rendered"&&at&&(De==="html"||De==="svg")){let Ke=te.id+"\0"+ye;if(g&&b===Ke&&g.parentElement===c)return;E(),N(),x(),c.replaceChildren();let Pe=n.features?.artifacts?.filePreview,$e=Pe?.iframeSandbox??"allow-scripts";!Pe?.dangerouslyAllowSameOrigin&&$e.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),$e=$e.split(/\s+/).filter(tt=>tt&&tt!=="allow-same-origin").join(" "));let Ae=px(Pe?.loading),ie=y("div","persona-artifact-frame"),Ie=y("iframe","persona-artifact-iframe");Ie.setAttribute("sandbox",$e),Ie.setAttribute("data-artifact-id",te.id);let dt=null;Ae.enabled&&Ae.injectReadySignal?(dt=gx(),Ie.srcdoc=ye+fx(dt)):Ie.srcdoc=ye,ie.appendChild(Ie),c.appendChild(ie),Ae.enabled&&(f=hx(ie,Ie,dt,Ae,te.id,n)),g=ie,b=Ke;return}if(x(),!ge&&De==="markdown"&&be==="rendered"){ce(ye);return}Z(ye,{language:ee.language,path:ee.path},te,me);return}if(te.artifactType==="markdown"){if(be==="source"){x(),Z(te.markdown??"",void 0,te,me);return}ce(te.markdown??"");return}x(),E(),N(),c.replaceChildren();let ve=te.component?o.get(te.component):void 0;if(ve){let De={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let at=ve(te.props??{},De);if(at){c.appendChild(at);return}}catch{}}c.appendChild(dx(te))};return he(e),{el:c,update(te){he(te)}}}var zf=require("idiomorph"),Zi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;zf.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var qf=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var yd={index:-1,draft:""};function Vf(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Kf(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Gf(){return new Map}function Jf(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Yf(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Xf(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qf(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function el(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Un(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function po(e,t){return Un(e)-e.scrollTop<=t}function tl(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function nl(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Zf(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function bd(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function em(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ba={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yx=["pre","code","a","script","style"],ol=e=>({type:e?.type??ba.type,placeholder:e?.placeholder??ba.placeholder,speed:e?.speed??ba.speed,duration:e?.duration??ba.duration,buffer:e?.buffer??ba.buffer}),nm=[{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"}],va=new Map;for(let e of nm)va.set(e.name,e);var om=e=>{va.set(e.name,e)},rm=e=>{nm.some(t=>t.name===e)||va.delete(e)},sm=()=>Array.from(va.keys()),ms=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:va.get(e)??null,rl=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
- `);return s<0?"":e.slice(0,s)}return e},bx=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},vx=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},vd=/\s/,xx=(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},Cx=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(vd.test(s[i])){let p=i;for(;p<s.length&&vd.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!vd.test(s[d]);)p.appendChild(bx(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},wx=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(vx(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},xa=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??yx).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)xx(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Cx:wx;for(let g of i)c(g,n,d);return r.innerHTML},sl=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ca=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},tm=new WeakMap,Ax=(e,t)=>{if(!e.styles)return;let n=tm.get(t);if(n||(n=new Set,tm.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},xd=new WeakMap,Sx=(e,t)=>{if(!e.onAttach)return;let n=xd.get(t);if(n||(n=new Map,xd.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},am=e=>{let t=xd.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},al=(e,t)=>{Ax(e,t),Sx(e,t)};function Cd(e,t=$t){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var wa=0,Vo=null;function wd(e=document){if(wa++,wa===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Vo={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,wa=Math.max(0,wa-1),wa===0&&Vo)){let n=e.body,o=e.defaultView??window;n.style.overflow=Vo.originalOverflow,n.style.position=Vo.originalPosition,n.style.top=Vo.originalTop,n.style.width=Vo.originalWidth,o.scrollTo(0,Vo.scrollY),Vo=null}}}var Aa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Mt=e=>(e?.launcher?.mountMode??"floating")==="docked",Ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",rn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Aa.side,width:t?.width??Aa.width,animate:t?.animate??Aa.animate,reveal:t?.reveal??Aa.reveal,maxHeight:t?.maxHeight??Aa.maxHeight}};var Ad=e=>e==="followUp"?"follow-up":e,Sd=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},Tx=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},im=new WeakSet,Ex=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,Mx=e=>{Ex()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Td=e=>{var R,E,P;let{item:t,index:n,surface:o,source:r,variant:s,streaming:a,config:i,plugins:p,chipsConfig:d,session:c,getTextarea:g,eventTarget:b}=e,f=o==="followUp",x=t.behavior,C=()=>{if(c.isStreaming())return;let B={suggestion:{...t},surface:o,source:r,behavior:x},N=b.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:B,bubbles:!0,composed:!0,cancelable:!0}));if(f&&b.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!N)return;for(let z of p)if(z.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:i})===!1)return;let $=g();if(x==="fill"){$.value=t.prompt,$.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),$.focus();return}$.value="",c.sendMessage(t.prompt)},S=()=>{let B=y("button",`persona-suggestion persona-suggestion--${s}`);if(B.type="button",B.disabled=a,B.dataset.suggestionId=t.id,B.dataset.emphasis=t.emphasis,B.dataset.behavior=x,s==="chip"&&(d?.fontFamily&&(B.style.fontFamily=Tx(d.fontFamily)),d?.fontWeight&&(B.style.fontWeight=d.fontWeight),d?.paddingX&&(B.style.paddingLeft=d.paddingX,B.style.paddingRight=d.paddingX),d?.paddingY&&(B.style.paddingTop=d.paddingY,B.style.paddingBottom=d.paddingY)),t.icon){let $=se(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);$&&($.classList.add("persona-suggestion__icon"),t.iconColor&&($.style.color=t.iconColor),B.appendChild($))}let N=y("span","persona-suggestion__copy");if(N.appendChild(ke("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&N.appendChild(ke("span",{className:"persona-suggestion__description",text:t.description})),B.appendChild(N),s!=="chip"){let $=se("arrow-right",16,"currentColor",1.8);$&&($.classList.add("persona-suggestion__arrow"),B.appendChild($))}return B.addEventListener("click",C),B},k=null;for(let B of p)if(B.renderSuggestion&&(k=B.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:a,config:i,defaultRenderer:S,select:C}),k))break;return k??(k=S()),(R=k.dataset).suggestionId||(R.suggestionId=t.id),(E=k.dataset).behavior||(E.behavior=x),(P=k.dataset).emphasis||(P.emphasis=t.emphasis),k instanceof HTMLButtonElement||k.setAttribute("aria-disabled",a?"true":"false"),k},Sa=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},a=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){s();return}let g=getComputedStyle(e).direction==="rtl",b=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),f=4,x=b<=f,C=b>=c-f,S=g?!C:!x,k=g?!x:!C;e.toggleAttribute("data-scroll-left",S),e.toggleAttribute("data-scroll-right",k)},i=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};e.addEventListener("scroll",i,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(i):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",i),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,g,b,f,x,C)=>{e.replaceChildren(),t.length=0,n.length=0;let S=C?.source??"config",k=C?.surface??(S==="config"?"starter":"followUp"),R=k==="followUp",E=C?.variant??"chip",P=C?.behavior??"send",B=C?.overflow??"wrap",N=C?.config??{},$=C?.plugins??[],z=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,q=R?"followUps":"starters";!im.has(N)&&N.debug===!0&&E!=="chip"&&N.suggestions?.[q]?.overflow!==void 0&&(im.add(N),console.info(`[persona] suggestions.${q}.overflow applies to the "chip" variant only; the "${E}" variant manages its own stacking.`));let X=he=>he.map(Sd).filter(te=>te!==null).map(te=>({...te,behavior:te.behavior??P})),A=X(c??[]);$.forEach(he=>{he.transformSuggestions&&(A=X(he.transformSuggestions({suggestions:A.map(te=>({...te})),surface:k,source:S,config:N})))});let J=z===void 0?A:A.slice(0,z);if(!J.length){e.hidden=!0,o=null,s();return}if(!R&&(f??g.getMessages()).some(te=>te.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Ad(k),e.dataset.variant=E,e.dataset.overflow=B;let Z=document.createDocumentFragment(),ce=g.isStreaming();J.forEach((he,te)=>{let be=Td({item:he,index:te,surface:k,source:S,variant:E,streaming:ce,config:N,plugins:$,chipsConfig:x,session:g,getTextarea:()=>b,eventTarget:e});Z.appendChild(be),n.push(be),[...be instanceof HTMLButtonElement?[be]:[],...Array.from(be.querySelectorAll("button"))].forEach(ge=>{t.includes(ge)||(ge.disabled=ce,t.push(ge))})}),e.appendChild(Z),a(),i();let Y=JSON.stringify({normalized:J,surface:k,variant:E,source:S});Y!==o&&(o=Y,Mx(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:J.map(he=>({...he})),surface:k,source:S,variant:E},bubbles:!0,composed:!0})),R&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:J.map(he=>he.prompt)},bubbles:!0,composed:!0})))}}};var un={"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 kx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",il=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=kx,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=y("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,g=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),x=ke("button",{className:Hn("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=se(g,s,"currentColor",1);return C?(C.style.display="block",x.appendChild(C)):x.textContent=b,p.appendChild(x),jt({anchor:x,trigger:p,text:()=>x.getAttribute("aria-label")??d,enabled:c}),{button:x,wrapper:p}},Lx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ll=(e,t={})=>{let{wrapperClassName:n=Lx,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",g=a.borderWidth??"",b=a.borderColor??"",f=a.borderRadius??"",x=a.paddingX??"",C=a.paddingY??"",S=a.tooltipText??"Clear chat",k=a.showTooltip??!0,R=y("div",n),E=!!(g||b),P=ke("button",{className:Hn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:d||Jt.actionIconColor,backgroundColor:c||void 0,border:E?`${g||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),B=se(p,r,"currentColor",1);return B&&(B.style.display="block",P.appendChild(B)),R.appendChild(P),jt({anchor:P,trigger:R,text:()=>P.getAttribute("aria-label")??S,enabled:k}),{button:P,wrapper:R}};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))"},Ed={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},Px={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},uo=e=>{let{config:t,showClose:n=!0}=e,o=ke("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=ke("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let B=parseFloat(s)||24,N=se(p,B*.6,"currentColor",1);N?d.replaceChildren(N):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let B=y("img");B.src=t.launcher.iconUrl,B.alt="",B.className="persona-rounded-xl persona-object-cover",B.style.height=s,B.style.width=s,d.replaceChildren(B)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=ke("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor,...Ed}}),b=ke("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor,...Px}});c.append(g,b),i?o.append(c):o.append(d,c);let f=r.clearChat??{},x=f.enabled??!0,C=f.placement??"inline",S=null,k=null;if(x){let N=ll(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=N.button,k=N.wrapper,C==="top-right"&&(k.style.right="48px"),C==="inline"&&o.appendChild(k)}let R=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:E,wrapper:P}=il(t,{showClose:n,wrapperClassName:R});return a!=="top-right"&&o.appendChild(P),{header:o,iconHolder:d,headerTitle:g,headerSubtitle:b,closeButton:E,closeButtonWrapper:P,clearChatButton:S,clearChatButtonWrapper:k}},Er=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Md=e=>{let t=uo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function Rx(e,t,n){if(t?.length)for(let o of t){let r=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Jt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=se(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=y("div","persona-relative");s.appendChild(r);let a=zo({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var kd=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Ji({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=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=y("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Jt.titleColor,Object.assign(c.style,Ed),c.textContent=a.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let P=r.onTitleClick;d.addEventListener("click",B=>{B.target.closest("button")||P()}),d.addEventListener("keydown",B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),P())})}let E=r?.titleRowHover;E&&(d.style.borderRadius=E.borderRadius??"10px",d.style.padding=E.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=E.background??"",d.style.borderColor=E.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let g=a.closeButtonSize??"32px",b=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=g,f.style.width=g,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Jt.actionIconColor;let x=a.closeButtonIconName??"x",C=se(x,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f);let S=y("div","persona-flex persona-items-center persona-gap-1");p||Rx(S,r?.trailingActions,r?.onAction??s),S.appendChild(b),i.appendChild(S);let k=y("div");k.style.display="none";let R=y("span");return R.style.display="none",{header:i,iconHolder:k,headerTitle:c,headerSubtitle:R,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},cl={default:Md,minimal:kd},Ld=e=>cl[e]??cl.default,hs=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=y("div");i.style.display="none";let p=y("span"),d=y("span"),c=y("button");c.style.display="none";let g=y("div");return g.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Ld(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var dl=e=>{let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let p=t.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let d=p.getComputedStyle(t).lineHeight;if(!d||!d.trim().endsWith("px"))return o;let c=parseFloat(d);return Number.isFinite(c)&&c>0?c:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let a=()=>{let p=t.style.maxHeight;if(p!==s){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return s=`${d}px`,t.style.maxHeight=s,d},i=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,a());t.style.height=`${p}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:i}},pl=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,g=t.size??"40px",b=t.backgroundColor,f=t.textColor,x=y("div","persona-send-button-wrapper"),C=ke("button",{className:Hn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),S=null,k=null;if(n){let P=parseFloat(t.iconSize??"")||Math.round((parseFloat(g)||24)*.5),B=t.iconStrokeWidth??2,N=f?.trim()||"currentColor";r?(S=se(r,P,N,B),S?C.appendChild(S):C.textContent=o):C.textContent=o,k=se(s,P,N,B)}else C.textContent=p;C.setAttribute("aria-label",a),x.appendChild(C),jt({anchor:C,trigger:x,text:()=>C.getAttribute("aria-label")??"",enabled:c});let R="send";return{button:C,wrapper:x,setMode:P=>{if(P===R)return;R=P;let B=P==="stop"?i:a;if(C.setAttribute("aria-label",B),n){if(S&&k){let N=P==="stop"?k:S;C.replaceChildren(N)}}else C.textContent=P==="stop"?d:p}}},ul=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,b=y("div","persona-send-button-wrapper"),f=ke("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=se(i,d,g||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let S=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return jt({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??S,enabled:k}),{button:f,wrapper:b}},gl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=y("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??io).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=y("div","persona-send-button-wrapper"),c=ke("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),g=se(s,p,"currentColor",1.5);g?c.appendChild(g):c.textContent="\u{1F4CE}",c.addEventListener("click",f=>{f.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return jt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},fl=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=y("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ml=()=>ke("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Mr=e=>{let{config:t}=e,n=ke("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=ml(),r=ke("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=dl(t);a();let i=pl(t),p=ul(t),d=gl(t),c=fl(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let g=ke("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&f.append(p.wrapper),f.append(i.wrapper),g.append(b,f),r.append(g),r.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:b,rightActions:f,setSendButtonMode:i.setMode}};var lm=()=>{let e=ke("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=se("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=y("span","persona-pill-peek__text"),r=y("span","persona-pill-peek__caret"),s=se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},hl=e=>{let{config:t}=e,n=ke("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ml(),r=fl(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=dl(t);s.style.maxHeight="100px",a();let i=pl(t),p=ul(t),d=gl(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=ke("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=y("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&g.append(d.wrapper);let b=y("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",x=>{x.target!==i.button&&x.target!==i.wrapper&&x.target!==p?.button&&x.target!==p?.wrapper&&x.target!==d?.button&&x.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(g,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let f=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:g,rightActions:b,setSendButtonMode:i.setMode}};var Ix=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}},Wx=(e,t)=>{if(!e)return null;let n=Ix(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Hx=(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},Bx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Pd=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(":"))},Rd=320,um=320,Dx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ox=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Nx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Fx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),_x=e=>{if(!e||e.length===0)return null;let t=ke("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ke("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=y("span","persona-mention-chip-icon"),s=se(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(ke("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},$x=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(pa(o.ref,{readonly:!0,render:t}))}return n},cm="\uE000",dm="\uE001",jx=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${cm}${r}:${b}${dm}`,a=t.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),i=n(a);if(!t.every((b,f)=>b.kind==="text"||i.includes(s(f)))){e.replaceChildren($x(t,o));return}e.innerHTML=i;let d=new RegExp(`${cm}${r}:(\\d+)${dm}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let b=c.nextNode();b;b=c.nextNode())g.push(b);for(let b of g){let f=b;for(let x=d.exec(f.data);x;x=d.exec(f.data)){let C=t[Number(x[1])],S=f.splitText(x.index);S.data=S.data.slice(x[0].length),C?.kind==="mention"&&S.parentNode?.insertBefore(pa(C.ref,{readonly:!0,render:o}),S),f=S}}},Ux=(e,t,n)=>{if(e.length===0)return null;try{let o=y("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=y("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Rd}px`,d.style.maxHeight=`${um}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),Bx(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},zx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Pd(o.audio))return;let r=y("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rd}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},qx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Pd(o.video))return;let r=y("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Rd}px`,r.style.maxHeight=`${um}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Vx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Pd(o.data))return;let r=y("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},kr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Id=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:kr};if(t){let r=t(o);if(r!==null)return r}return kr()},Kx=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=y("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},pm=(e,t,n="div")=>{let o=y(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Ta=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Wd=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let x=y("div");return x.style.display="none",x.id=`actions-${e.id}`,x.setAttribute("data-actions-for",e.id),x}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],b=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let f=(x,C,S)=>{let k=it({icon:x,label:C,size:14,className:"persona-message-action-btn"});return k.setAttribute("data-action",S),k};return o&&b.appendChild(f("copy","Copy message","copy")),a&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},ys=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,g=d?.show??!1,b=p?.position??"left",f=d?.position??"below",x=Ta(e.role,i),C=y("div",x.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=Dx(e),k=e.content?.trim()??"",E=S.length>0&&k===Ii,P=ol(s?.widgetConfig?.features?.streamAnimation),B=s?.widgetConfig?.features?.streamAnimation?.plugins,N=e.role==="assistant"&&P.type!=="none"?ms(P.type,B):null,$=e.role==="assistant"&&N?.isAnimating?.(e)===!0,z=e.role==="assistant"&&N!==null&&(!!e.streaming||$);z&&N?.bubbleClass&&C.classList.add(N.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),z&&N&&(N.containerClass&&q.classList.add(N.containerClass),q.style.setProperty("--persona-stream-step",`${P.speed}ms`),q.style.setProperty("--persona-stream-duration",`${P.duration}ms`));let X=z?rl(e.content??"",P.buffer,N,e,!!e.streaming):e.content??"",A=()=>{let ne=t({text:X,message:e,streaming:!!e.streaming,raw:e.rawContent});return z&&N?.wrap==="char"?xa(ne,"char",e.id,{skipTags:N.skipTags}):z&&N?.wrap==="word"?xa(ne,"word",e.id,{skipTags:N.skipTags}):ne},J=null;if(E?(J=document.createElement("div"),J.innerHTML=A(),J.style.display="none",q.appendChild(J)):e.contentSegments?.length?jx(q,e.contentSegments,ne=>t({text:ne,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=A(),z&&N?.useCaret&&!E&&k){let ne=sl(),me=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=me[me.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(ne,ve.nextSibling);else{let ye=q.lastElementChild;ye?ye.appendChild(ne):q.appendChild(ne)}}if(g&&f==="inline"&&e.createdAt){let ne=pm(e,d,"span");ne.classList.add("persona-timestamp-inline");let me=q.lastElementChild;me?me.appendChild(ne):q.appendChild(ne)}if(S.length>0){let ne=Ux(S,!E&&!!k,()=>{E&&J&&(J.style.display="")});ne?C.appendChild(ne):E&&J&&(J.style.display="")}let Z=Ox(e);if(Z.length>0){let ne=zx(Z);ne&&C.appendChild(ne)}let ce=Nx(e);if(ce.length>0){let ne=qx(ce);ne&&C.appendChild(ne)}let Y=Fx(e);if(Y.length>0){let ne=Vx(Y);ne&&C.appendChild(ne)}let he=e.contentSegments?.length?null:_x(e.contextMentions);if(he&&C.appendChild(he),C.appendChild(q),g&&f==="below"&&e.createdAt){let ne=pm(e,d);ne.classList.add("persona-mt-1"),C.appendChild(ne)}let te=e.role==="assistant"?Wx(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ne=!!(X&&X.trim()),me=P.placeholder==="skeleton",ve=me&&P.buffer==="line"&&ne;if(ne)ve&&C.appendChild(Ca());else if(me)C.appendChild(Ca());else{let ye=Id("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ye&&C.appendChild(ye)}}if(te&&e.stopReason&&!e.streaming&&(k||(q.style.display="none"),C.appendChild(Hx(e.stopReason,te))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ne=Wd(e,o,r);C.appendChild(ne)}if(!c||e.role==="system")return C;let ee=y("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=Kx(p,e.role);return b==="right"||b==="left"&&e.role==="user"?ee.append(C,ge):ee.append(ge,C),ee},gm=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ys(e,t,n,o,r,s)};var Gx=40,Jx=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=se(t.name,Gx);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ke("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ke("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},fm=(e,t,n={})=>{let o=ke("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=y("h2","persona-welcome-title"),s=y("p","persona-welcome-subtitle");return{host:ke("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},bs=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},bl=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",Jx(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Yx="data-persona-welcome-plugin",mm="data-persona-welcome-overlay",yl="persona-welcome-overlay-active",Hd=new WeakMap,hm=(e,t,n)=>{n.setAttribute(Yx,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(mm,""),e.classList.contains(yl)||(Hd.set(e,e.scrollTop),e.classList.add(yl),e.scrollTop=0)},ym=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(mm),e.classList.contains(yl)&&(e.classList.remove(yl),e.scrollTop=Hd.get(e)??e.scrollTop,Hd.delete(e))},bm=()=>{let e=ke("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},vl=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ke("div",{className:Ta("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(ke("div",{className:"persona-flex"},r)),e.hidden=!1},Xx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,vm=(e,t)=>{if(Xx()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,t(n))};return n.finished.then(r).catch(r),n};var Qx="Hello \u{1F44B}",Zx="I can answer questions and help you get things done here.",xm=new WeakSet,wn=(e,t)=>!!e&&e[t]!==void 0,eC=(e,t)=>{!e||e.debug!==!0||!t.length||xm.has(e)||(xm.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},go=e=>{let t=e?.welcome,n=e?.copy,o=wn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":wn(t,"dismiss")?t.dismiss:"never",s=[];return wn(t,"title")&&wn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),wn(t,"subtitle")&&wn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),wn(t,"variant")&&wn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&wn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&wn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),eC(e,s),{title:wn(t,"title")?t.title:n?.welcomeTitle??Qx,subtitle:wn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??Zx,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Go=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var Cm=e=>{let t=e?.launcher?.enabled??!0,n=Mt(e);if(Ko(e)){let c=e?.launcher?.composerBar??{},g=y("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??$t);let b=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",g.appendChild(b);let f=y("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??$t),{wrapper:g,panel:b,pillRoot:f}}if(n){let c=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(g),{wrapper:c,panel:g}}if(!t){let c=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,g.style.width="100%",c.appendChild(g),{wrapper:c,panel:g}}let r=e?.launcher??{},s=r.position&&un[r.position]?un[r.position]:un["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??$t);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??pn;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},Bd=e=>{let t=ke("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Ad(e)}});return t.hidden=!0,t},wm=(e,t)=>{let n=Bd("starter"),o=fm(e,n,{flatShadow:Mt(e)}),r=go(e);bl(o,r),bs(t,o.host,Go(r,e?.initialMessages));let s=bm();return vl(s,r.message,e),{welcome:o,greetingHost:s}},tC=(e,t)=>{let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=il(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let $=ll(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=$.button,i=$.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=ke("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=ke("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let{welcome:c,greetingHost:g}=wm(e,d),{host:b,title:f,subtitle:x}=c,C=c.starterSuggestions,S=y("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),k=Bd("followUp"),R=$o(e,!0);R&&(S.style.maxWidth=R,S.style.marginLeft="auto",S.style.marginRight="auto",S.style.width="100%"),d.append(b,g,S,k);let E=ke("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"}}),P=hl({config:e}),{root:B,textNode:N}=lm();return n.append(p,r,d,E),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:S,starterSuggestions:C,transcriptSuggestions:k,composerOverlay:E,suggestions:P.suggestions,textarea:P.textarea,sendButton:P.sendButton,sendButtonWrapper:P.sendButtonWrapper,micButton:P.micButton,micButtonWrapper:P.micButtonWrapper,composerForm:P.composerForm,statusText:P.statusText,welcomeHost:b,welcomeIconHolder:c.iconHolder,greetingHost:g,introTitle:f,introSubtitle:x,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:p,footer:P.footer,attachmentButton:P.attachmentButton,attachmentButtonWrapper:P.attachmentButtonWrapper,attachmentInput:P.attachmentInput,attachmentPreviewsContainer:P.attachmentPreviewsContainer,actionsRow:P.actionsRow,leftActions:P.leftActions,rightActions:P.rightActions,setSendButtonMode:P.setSendButtonMode,peekBanner:B,peekTextNode:N}},Am=(e,t=!0)=>{if(Ko(e))return tC(e,t);let n=ke("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?hs(e,o,{showClose:t}):uo({config:e,showClose:t}),a=ke("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let{welcome:i,greetingHost:p}=wm(e,a),{host:d,title:c,subtitle:g}=i,b=i.starterSuggestions,f=y("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),x=Bd("followUp"),C=$o(e,!1);C&&(f.style.maxWidth=C,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),a.append(d,p,f,x);let S=Mr({config:e}),k=e?.layout?.showFooter!==!1;r?Er(n,s,e):(s.header.style.display="none",Er(n,s,e)),n.append(a);let R=ke("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 k||(S.footer.style.display="none"),n.append(S.footer),n.append(R),{container:n,body:a,messagesWrapper:f,starterSuggestions:b,transcriptSuggestions:x,composerOverlay:R,suggestions:S.suggestions,textarea:S.textarea,sendButton:S.sendButton,sendButtonWrapper:S.sendButtonWrapper,micButton:S.micButton,micButtonWrapper:S.micButtonWrapper,composerForm:S.composerForm,statusText:S.statusText,welcomeHost:d,welcomeIconHolder:i.iconHolder,greetingHost:p,introTitle:c,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:S.footer,attachmentButton:S.attachmentButton,attachmentButtonWrapper:S.attachmentButtonWrapper,attachmentInput:S.attachmentInput,attachmentPreviewsContainer:S.attachmentPreviewsContainer,actionsRow:S.actionsRow,leftActions:S.leftActions,rightActions:S.rightActions,setSendButtonMode:S.setSendButtonMode}};var Dd=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
28
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ss(e){let t=Ky(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 vr(e){switch(ss(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Ky(e.path);return t?t.toUpperCase():"File"}}}function Ic(e){let t=e.markdown??"";return e.file?{filename:mo(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Hc(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}function Rc(e){let t=new Blob([e.content],{type:e.mime}),n=URL.createObjectURL(t),o=document.createElement("a");o.href=n,o.download=e.filename,o.click(),URL.revokeObjectURL(n)}var Eu="http://www.w3.org/2000/svg";function Gy(e){let t=document.createElementNS(Eu,"svg");t.setAttribute("class",jn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Eu,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Eu,"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 Cr=(e,t,n)=>{let o=n;for(let r of t){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function Yy(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),Cr(e,t,0)}var Mu="persona-artifact-status-label",Jy="persona-artifact-status-detail",Xy="data-artifact-status-label",ku=new Map,Qy=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function li(e){e&&ku.delete(e)}function hA(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?vr(t):e.artifactType==="component"?"Component":"Document"}function ci(e,t,n){let o=hA(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=e.id,l=ku.get(i);e.status!=="complete"&&l===void 0&&(l=Qy(),ku.set(i,l));let d=l===void 0?0:Math.max(0,Qy()-l),u=e.artifactType==="component",p=!u&&typeof e.markdown=="string"?e.markdown:"",g=u?0:p.length,y=u||p===""?0:p.split(`
29
+ `).length,m=e.artifactType==="markdown"?e.file:void 0,b={artifactId:i,artifactType:e.artifactType,title:e.title,typeLabel:o,file:m,chars:g,lines:y,elapsedMs:d,content:()=>u?"":p,surface:n};try{let x=s(b);return typeof x=="string"?{label:x}:x&&typeof x=="object"&&typeof x.label=="string"?{label:x.label,detail:typeof x.detail=="string"?x.detail:void 0}:{label:r}}catch{return{label:r}}}function yA(e){e.className=Mu,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 is(e,t,n){let o=e.querySelector(`:scope > .${Mu}`);o||(o=v("span",Mu),e.appendChild(o)),o.getAttribute(Xy)!==t.label&&(yA(o),Yy(o,t.label,n),o.setAttribute(Xy,t.label));let r=e.querySelector(`:scope > .${Jy}`),s=t.detail;s?(r||(r=v("span",Jy),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var bA={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"},vA=15e4,Wc={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 CA(e,t){let n=(e||"").trim().toLowerCase();if(n&&Wc[n])return Wc[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Wc[r])return Wc[r]}}return null}function Bc(e,t){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:e.slice(r,i)})};for(;o<e.length;){let i=!1;for(let l of t){l.re.lastIndex=o;let d=l.re.exec(e);if(d&&d.index===o&&d[0].length>0){s(o);let u=l.map?l.map(d[0]):l.type;n.push({type:u,value:d[0]}),o+=d[0].length,r=o,i=!0;break}}i||(o+=1)}return s(e.length),n}var wA=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"]),xA=[{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=>wA.has(e)?"keyword":"plain"}];function Zy(e){return Bc(e,xA)}var SA=[{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 AA(e){let t=Bc(e,SA);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var TA=[{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 eb(e){let t=Bc(e,TA),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<t.length&&t[i].value.trim()==="";)i+=1;let l=t[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return t}var EA=[{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 MA(e){let t=[],n=(s,i)=>{i&&t.push({type:s,value:i})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let i=e.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let i=e.indexOf(">",r),l=i===-1?o:i+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let i=e.indexOf(">",r),l=i===-1?o:i+1,d=e.slice(r,l);for(let p of Bc(d,EA))t.push(p);r=l;let u=/^<\s*(script|style)\b/i.exec(d);if(u&&!/\/>\s*$/.test(d)){let p=u[1].toLowerCase(),y=new RegExp("</\\s*"+p+"\\s*>","i").exec(e.slice(r)),m=y?r+y.index:o,b=e.slice(r,m),x=p==="script"?Zy(b):eb(b);for(let T of x)t.push(T);r=m}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let i=s===-1?o:s;n("plain",e.slice(r,i)),r=i}}return t}function kA(e,t){switch(t){case"html":return MA(e);case"css":return eb(e);case"js":return Zy(e);case"json":return AA(e)}}function PA(e){let t=kh(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=bA[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
30
+ `);for(let i=0;i<s.length;i+=1)i>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
+ `)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function tb(e,t,n){let o=e.length<=vA?CA(t,n):null,r=o?kA(e,o):[{type:"plain",value:e}];return PA(r)}function as(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:i}=e,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(ri)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let b of t){if(b.dividerBefore){let H=document.createElement("hr");l.appendChild(H)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",b.id),b.destructive&&x.setAttribute("data-destructive",""),b.icon){let H=de(b.icon,16,"currentColor",1.5);H&&x.appendChild(H)}let T=document.createElement("span");T.textContent=b.label,x.appendChild(T),x.addEventListener("click",H=>{H.stopPropagation(),g(),n(b.id)}),l.appendChild(x)}let d=null;function u(){if(!s)return;let b=o.getBoundingClientRect();l.style.top=`${b.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-b.right}px`,l.style.left="auto"):(l.style.left=`${b.left}px`,l.style.right="auto")}function p(){let b=l.classList.contains("persona-hidden");u(),l.classList.remove("persona-hidden"),b&&i?.(!0),requestAnimationFrame(()=>{let x=T=>{!l.contains(T.target)&&!o.contains(T.target)&&g()};document.addEventListener("click",x,!0),d=()=>document.removeEventListener("click",x,!0)})}function g(){let b=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,b&&i?.(!1)}function y(){l.classList.contains("persona-hidden")?p():g()}function m(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:p,hide:g,toggle:y,destroy:m}}function rt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=e,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let u=de(t,o??16,"currentColor",r??2);if(u&&d.appendChild(u),i&&d.addEventListener("click",i),l)for(let[p,g]of Object.entries(l))d.setAttribute(p,g);return d}function Fo(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:d}=e,u="persona-label-btn";o!=="default"&&(u+=" persona-label-btn--"+o),u+=" persona-label-btn--"+r,i&&(u+=" "+i);let p=v("button",u);if(p.type="button",p.setAttribute("aria-label",n),t){let y=de(t,s??14,"currentColor",2);y&&p.appendChild(y)}let g=v("span");if(g.textContent=n,p.appendChild(g),l&&p.addEventListener("click",l),d)for(let[y,m]of Object.entries(d))p.setAttribute(y,m);return p}function $o(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function d(){for(let p of l)p.btn.setAttribute("aria-pressed",p.id===i?"true":"false")}for(let p of t){let g;p.icon?g=rt({icon:p.icon,label:p.label,className:p.className,onClick:()=>{i=p.id,d(),o(p.id)}}):(g=v("button","persona-icon-btn"+(p.className?" "+p.className:"")),g.type="button",g.setAttribute("aria-label",p.label),g.title=p.label,g.textContent=p.label,g.addEventListener("click",()=>{i=p.id,d(),o(p.id)})),g.setAttribute("aria-pressed",p.id===i?"true":"false"),l.push({id:p.id,btn:g}),s.appendChild(g)}function u(p){i=p,d()}return{element:s,setSelected:u}}function Oc(e){let{label:t,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:i,onPrimary:l,position:d="bottom-left",portal:u,chevronLabel:p="More options",chevronIconSize:g,className:y,primaryClassName:m,chevronClassName:b}=e,x=v("div","persona-split-btn"+(y?" "+y:"")),T={label:t,className:"persona-split-btn-primary"+(m?" "+m:""),onClick:l},H=r&&n?rt({...T,icon:n,size:o??14}):Fo({...T,icon:n,iconSize:o??14}),_=rt({icon:"chevron-down",label:p,size:g??14,className:"persona-split-btn-chevron"+(b?" "+b:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});x.append(H,_);let P=null,A=()=>{if(P)return P;let B=(typeof u=="function"?u():u)??void 0;return P=as({items:s,onSelect:i,anchor:x,position:d,portal:B,onOpenChange:R=>{_.setAttribute("aria-expanded",R?"true":"false")}}),B||x.appendChild(P.element),P};return x.isConnected?A():requestAnimationFrame(()=>{P||A()}),_.addEventListener("click",B=>{B.stopPropagation(),A().toggle()}),{element:x,primaryButton:H,chevronButton:_,openMenu:()=>A().show(),closeMenu:()=>P?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{P?.destroy(),x.remove()}}}function Dc(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:d}=e,u=v("div","persona-combo-btn"+(l?" "+l:""));u.style.position="relative",u.style.display="inline-flex",u.style.alignItems="center",u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0"),u.setAttribute("aria-haspopup","true"),u.setAttribute("aria-expanded","false"),u.setAttribute("aria-label",t);let p=v("span","persona-combo-btn-label");p.textContent=t,u.appendChild(p);let g=de(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",u.appendChild(g)),d&&(u.style.borderRadius=d.borderRadius??"10px",u.style.padding=d.padding??"6px 4px 6px 12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=d.background??"",u.style.borderColor=d.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}));let y=as({items:o,onSelect:b=>{u.setAttribute("aria-expanded","false"),r(b)},anchor:u,position:s,portal:i});i||u.appendChild(y.element);let m=()=>u.getAttribute("data-persona-menu-locked")==="true";return u.addEventListener("click",b=>{if(b.stopPropagation(),m())return;let x=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",x?"false":"true"),y.toggle()}),u.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u.click())}),{element:u,setLabel:b=>{p.textContent=b,u.setAttribute("aria-label",b)},open:()=>{u.setAttribute("aria-expanded","true"),y.show()},close:()=>{u.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let b=!y.element.classList.contains("persona-hidden");u.setAttribute("aria-expanded",b?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),u.remove()}}}var _c="persona-artifact-custom-action-btn";function di(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+_c+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+_c+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=v("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Fo({icon:e.icon,label:e.label,className:_c+(n?" persona-artifact-doc-copy-btn":"")}):o=rt({icon:e.icon,label:e.label,className:_c+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Pa(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 nb(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?mo(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",i=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",d=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,u=n?vr(n):l==="component"?"Component":"Document",p=document.createElement("div");p.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&p.setAttribute("data-open-artifact",s);let g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let y=document.createElement("div");y.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=r;let b=document.createElement("div");if(b.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",b.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let x=t?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},H=ci(T,x,"card");is(b,H,x)}else s&&li(s),b.textContent=u;if(y.append(m,b),p.append(g,y),i==="complete"){let x=t?.config?.features?.artifacts?.cardActions;if(x&&x.length>0){let H={artifactId:s||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let _ of x)try{if(_.visible===void 0||_.visible(H)){let P=di(_);P.setAttribute("data-artifact-custom-action",_.id),P.className=`${P.className} persona-flex-shrink-0`,p.append(P)}}catch{}}let T=Fo({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),p.append(T)}return p}var Nc=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>nb(e,t)});if(l)return l}return nb(e,t)};var wr=new WeakMap;function Pu(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=wr.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function ab(e){return wr.has(e)}function LA(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete",r=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0;if(e.artifactType==="component"){let i=e.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let s=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function ob(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?mo(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?vr(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function HA(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 rb=180,IA=240,RA=.8,WA=300,BA=500,OA="cubic-bezier(0.2, 0, 0, 1)",sb=240,DA=.35;function _A(e,t,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let i=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:rb,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let H of i)H.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let d=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!d||Math.abs(d-t)<1){l(),r();return}let u=Math.abs(t-d),p=Math.round(Math.min(BA,Math.max(WA,IA+u*RA))),g=Math.round(p*DA),y=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,m=y?y.animate([{opacity:0},{opacity:1}],{duration:sb,delay:g,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${d}px`}],{duration:p,easing:OA});e.style.height=`${d}px`;let x=!1,T=()=>{x||(x=!0,l(),r())};Promise.allSettled([b.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(p,g+sb)+120)},rb)}function NA(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 La="--persona-artifact-inline-body-height";function FA(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,i=t?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:t?.followOutput!==!1,u,p,g=t?.fadeMask;g===!0?(u=!0,p=!0):g===!1?(u=!1,p=!1):g&&typeof g=="object"?(u=g.top===!0,p=g.bottom===!0):l==="clip"?(u=!1,p=!0):(u=!0,p=!0);let y=t?.transition==="none"?"none":"auto",m=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:u,fadeBottom:p,transition:y,completeDisplay:m}}function ib(e,t){let n=LA(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=NA(o),d=o?.inlineActions??[],u=FA(o),p=u.completeDisplay==="card",g=null,y=n,m=v("div","persona-artifact-inline persona-w-full persona-max-w-full");m.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&m.setAttribute("data-artifact-inline",n.id);let b=M=>Nc(HA(M),t),x=null,T=M=>{x?.destroy(),x=null,m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(La),m.replaceChildren(b(M)),wr.set(m,ee=>{m.replaceChildren(b(ee))})};if(p&&n.status==="complete")return T(n),m;let H=Fc(n,{config:t.config,bodyLayout:u,resolveViewMode:()=>g??u.viewMode});x=H;let _=v("div","persona-artifact-inline-body");_.appendChild(H.el);let P=M=>{let ee=M.status!=="complete",pe=ee?u.streamingHeight:u.completeHeight,we=typeof pe=="number";we?m.style.setProperty(La,`${pe}px`):m.style.removeProperty(La);let me=!!H.el.querySelector(".persona-code-pre"),Se=!!H.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");_.classList.toggle("persona-artifact-content-flush",me),_.classList.toggle("persona-artifact-inline-body--sized",we&&Se),_.classList.toggle("persona-artifact-inline-body--cap",!ee&&!Se&&typeof u.completeHeight=="number")},A=n.status,B=(M,ee)=>{A!=="complete"&&M.status==="complete"?(typeof u.completeHeight=="number"?m.style.setProperty(La,`${u.completeHeight}px`):m.style.removeProperty(La),cb(_,ee?.suppressTransition?"none":u.transition,M.id,()=>{H.update(M),P(M)})):H.update(M),P(M),A=M.status};P(n);let R=u.overflow==="clip"&&i&&!!n.id;if(R&&(_.setAttribute("data-expand-artifact-inline",n.id),_.setAttribute("role","button"),_.setAttribute("tabindex","0"),_.classList.add("persona-cursor-pointer"),_.setAttribute("aria-label",`Open ${ob(n).title} in panel`)),!r)return m.appendChild(_),wr.set(m,B),m;let W=v("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let U=v("div","persona-artifact-inline-chrome-lead"),V=v("span","persona-flex persona-items-center persona-flex-shrink-0"),Z=de("file-text",16,"currentColor",2);Z&&V.appendChild(Z);let j=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),X=v("span","persona-artifact-inline-type");U.append(V,j,X);let ue=v("div","persona-artifact-inline-chrome-actions"),xe=v("span","persona-flex persona-items-center persona-gap-1"),Ce=()=>g??u.viewMode,ye=l?$o({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:Ce(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:M=>{let ee=M==="source"?"source":"rendered";ee!==Ce()&&(g=ee,H.update(y),P(y))}}):null,oe=s?rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;oe&&n.id&&oe.setAttribute("data-copy-artifact",n.id);let le=i?rt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;le&&n.id&&le.setAttribute("data-expand-artifact-inline",n.id),ue.appendChild(xe),ye&&ue.appendChild(ye.element),oe&&ue.appendChild(oe),le&&ue.appendChild(le),W.append(U,ue),m.append(W,_);let ae=M=>{let{title:ee,typeLabel:pe}=ob(M);j.textContent=ee,j.title=ee,R&&_.setAttribute("aria-label",`Open ${ee} in panel`);let we=M.status!=="complete";if(we){X.classList.contains("persona-artifact-inline-status")||(X.className="persona-artifact-inline-status",X.removeAttribute("data-preserve-animation"),X.replaceChildren());let me=ci(M,o,"inline-chrome");is(X,me,o)}else li(M.id),X.className="persona-artifact-inline-type",X.removeAttribute("data-preserve-animation"),X.replaceChildren(),X.textContent=pe;if(oe&&oe.classList.toggle("persona-hidden",we),ye){let me=M.artifactType==="markdown"?M.file:void 0,Se=!1;if(!we&&me&&u.viewMode!=="source"){let Le=ss(me);Le==="markdown"?Se=!0:(Le==="html"||Le==="svg")&&(Se=o?.filePreview?.enabled!==!1)}ye.element.classList.toggle("persona-hidden",!Se),ye.setSelected(Ce())}if(xe.replaceChildren(),!we&&d.length>0){let me=Pa(M);if(me)for(let Se of d)try{if(Se.visible===void 0||Se.visible(me)){let Le=di(Se,{documentChrome:!0});Le.setAttribute("data-artifact-custom-action",Se.id),Le.classList.add("persona-flex-shrink-0"),xe.appendChild(Le)}}catch{}}};return ae(n),wr.set(m,(M,ee)=>{if(p&&A!=="complete"&&M.status==="complete"){let pe=m.isConnected?m.getBoundingClientRect().height:0;A="complete";let we=M,me=!1,Se=Le=>{we=Le,me=!0};wr.set(m,Se),_A(m,pe,{swap:()=>{T(we),me=!1,wr.set(m,Se)},onSettled:()=>{me?T(we):wr.set(m,Le=>{m.replaceChildren(b(Le))})}});return}(M.status!=="complete"||M.id!==y.id)&&(g=null),y=M,B(M,ee),ae(M)}),m}var lb=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:t.config,defaultRenderer:()=>ib(e,t)});if(l)return l}return ib(e,t)};var Lu=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)})}},to=new Lu;to.register("PersonaArtifactCard",Nc,{bubbleChrome:!1});to.register("PersonaArtifactInline",lb,{bubbleChrome:!1});function Ha(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Hc(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Hu=!1;function $A(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function cb(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(t!=="auto"||!e||typeof r!="function"||Hu||s){o();return}Hu=!0;let i=$A(n);e.style.setProperty("view-transition-name",i);let l=()=>{Hu=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var jA="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",zA="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function UA(e){let t=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function qA(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 VA=220;function KA(){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 GA(e){return`
32
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function YA(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:e,config:t});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Gy());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function JA(e,t,n,o,r,s){let i=null,l=0,d=!1,u=new Set,p=()=>{u.forEach(P=>clearTimeout(P)),u.clear()},g=(P,A)=>{let B=setTimeout(()=>{u.delete(B),P()},A);u.add(B)},y=()=>{i&&i.parentElement&&i.remove(),i=null},m=()=>{if(i||d)return;let P=YA(r,s,o);i=P.el,e.appendChild(i),l=Date.now(),o.label!==!1&&g(P.revealLabel,o.labelDelayMs)},b=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),g(y,VA))},x=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",H):t.removeEventListener("load",_)},T=()=>{if(d||(d=!0,x(),p(),!i))return;let P=Math.max(0,o.minVisibleMs-(Date.now()-l));P>0?g(b,P):b()};function H(P){if(n===null)return;let A=P.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||P.source===t.contentWindow&&T()}function _(){let P=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};P(()=>P(()=>T()))}return g(m,o.delayMs),g(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",H):t.addEventListener("load",_),()=>{d=!0,p(),x(),y()}}function Fc(e,t){let{config:n}=t,o=t.registry??to,r=t.bodyLayout,s=n.markdown?Xr(n.markdown):null,i=Vs(n.sanitize),l=e,d=!1,u=oe=>{let le=Bo()!==null;s&&!le&&!d&&(d=!0,qs(()=>ye(l)));let ae=s?s(oe):co(oe);return s&&le&&i?i(ae):ae},p=v("div","persona-artifact-preview-body"),g=null,y=null,m=null,b=()=>{m&&(m(),m=null),g=null,y=null},x=null,T=null,H=null,_=!1,P=()=>{x=null,T=null,H=null,_=!1},A=null,B=null,R=()=>{A=null,B=null},W=40,U=0,V=oe=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>oe()):setTimeout(oe,0),Z=oe=>oe.scrollHeight-oe.clientHeight-oe.scrollTop<=W,j=oe=>{if(!r)return;let le=oe.scrollHeight-oe.clientHeight>1,ae=oe.scrollHeight-oe.clientHeight-oe.scrollTop;oe.classList.toggle("persona-artifact-fade-top",r.fadeTop&&le&&oe.scrollTop>1),oe.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&le&&ae>1)},X=oe=>{U||(U=V(()=>{U=0,oe.scrollTop=oe.scrollHeight,j(oe)}))},ue=(oe,le,ae,M)=>{let ee=!!r,pe=ae.id+"|"+(ee?"w":"p");if(!x||H!==pe||x.parentElement!==p){b(),R(),p.replaceChildren();let Se=v("pre",jA+" persona-code-pre"),Le=v("code","persona-code");if(Se.appendChild(Le),ee){let He=v("div","persona-artifact-source-window");if(He.appendChild(Se),p.appendChild(He),!(r?.overflow==="clip")&&typeof He.addEventListener=="function"){let Oe=()=>He.scrollHeight-He.clientHeight>1;He.addEventListener("scroll",()=>{Z(He)&&(_=!1),j(He)},{passive:!0}),He.addEventListener("wheel",We=>{Oe()&&We.deltaY<0&&(_=!0)},{passive:!0}),He.addEventListener("touchmove",()=>{Oe()&&(_=!0)},{passive:!0})}x=He}else p.appendChild(Se),x=Se;T=Le,H=pe}let we=ee?x:null;we&&(we.classList.toggle("persona-artifact-source-window--fixed",M),we.classList.toggle("persona-artifact-source-window--clip",M&&r?.overflow==="clip"));let me=we?Z(we):!0;if(T.replaceChildren(tb(oe,le?.language,le?.path)),we){let Se=ae.status!=="complete";M&&Se&&r?.followOutput&&!_&&me?X(we):Se||(_=!1),j(we)}},xe=oe=>{b(),P(),R(),p.replaceChildren();let le=v("div",zA);le.innerHTML=u(oe),p.appendChild(le)},Ce=oe=>{let le=oe.id,ae=n.features?.artifacts,M=ci(oe,ae,"status-body");if(A&&B===le&&A.parentElement===p){let we=A.querySelector(".persona-artifact-status-view-text");we&&is(we,M,ae);return}b(),P(),p.replaceChildren();let ee=v("div","persona-artifact-status-view"),pe=v("div","persona-artifact-status-view-text");is(pe,M,ae),ee.appendChild(pe),p.appendChild(ee),A=ee,B=le},ye=oe=>{l=oe;let le=t.resolveViewMode?.(oe)??r?.viewMode??"rendered",ae=oe.artifactType==="markdown"?oe.file:void 0,M=oe.status!=="complete";M||li(oe.id);let ee=M?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof ee=="number";if(r?.streamingView==="status"&&M){Ce(oe);return}if(ae){let me=Hc(oe.markdown??""),Se=ss(ae),Le=n.features?.artifacts?.filePreview?.enabled!==!1;if(!M&&le==="rendered"&&Le&&(Se==="html"||Se==="svg")){let Qe=oe.id+"\0"+me;if(g&&y===Qe&&g.parentElement===p)return;P(),R(),b(),p.replaceChildren();let Oe=n.features?.artifacts?.filePreview,We=Oe?.iframeSandbox??"allow-scripts";!Oe?.dangerouslyAllowSameOrigin&&We.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."),We=We.split(/\s+/).filter(Ae=>Ae&&Ae!=="allow-same-origin").join(" "));let tt=qA(Oe?.loading),ve=v("div","persona-artifact-frame"),Ne=v("iframe","persona-artifact-iframe");Ne.setAttribute("sandbox",We),Ne.setAttribute("data-artifact-id",oe.id);let ft=null;tt.enabled&&tt.injectReadySignal?(ft=KA(),Ne.srcdoc=me+GA(ft)):Ne.srcdoc=me,ve.appendChild(Ne),p.appendChild(ve),tt.enabled&&(m=JA(ve,Ne,ft,tt,oe.id,n)),g=ve,y=Qe;return}if(b(),!M&&Se==="markdown"&&le==="rendered"){xe(me);return}ue(me,{language:ae.language,path:ae.path},oe,pe);return}if(oe.artifactType==="markdown"){if(le==="source"){b(),ue(oe.markdown??"",void 0,oe,pe);return}xe(oe.markdown??"");return}b(),P(),R(),p.replaceChildren();let we=oe.component?o.get(oe.component):void 0;if(we){let Se={message:{id:oe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Le=we(oe.props??{},Se);if(Le){p.appendChild(Le);return}}catch{}}p.appendChild(UA(oe))};return ye(e),{el:p,update(oe){ye(oe)},destroy(){b()}}}var db=require("idiomorph"),$c=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;db.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var pb=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Iu={index:-1,draft:""};function ub(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function gb(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 fb(){return new Map}function mb(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function hb(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function yb(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function bb(e){return e.role!=="assistant"||e.variant==="tool"||e.variant==="reasoning"?!1:e.variant==="approval"?!0:!!(e.content?.trim()||e.rawContent?.trim()||e.contentParts?.length)}function vb(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function ho(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ls(e,t){return ho(e)-e.scrollTop<=t}function Cb(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:u=!1}=e,p=n-o;return i||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&r&&(!u||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&l&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!r?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function wb(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function xb(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Ru(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0));return{targetScrollTop:t,spacerHeight:n}}function Sb(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ia={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},XA=["pre","code","a","script","style"],jc=e=>({type:e?.type??Ia.type,placeholder:e?.placeholder??Ia.placeholder,speed:e?.speed??Ia.speed,duration:e?.duration??Ia.duration,buffer:e?.buffer??Ia.buffer}),Tb=[{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"}],Ra=new Map;for(let e of Tb)Ra.set(e.name,e);var Eb=e=>{Ra.set(e.name,e)},Mb=e=>{Tb.some(t=>t.name===e)||Ra.delete(e)},kb=()=>Array.from(Ra.keys()),pi=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Ra.get(e)??null,zc=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
+ `);return s<0?"":e.slice(0,s)}return e},QA=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},ZA=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},Wu=/\s/,eT=(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},tT=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Wu.test(s[l])){let d=l;for(;d<s.length&&Wu.test(s[d]);)d+=1;i.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let u=l;for(;u<s.length&&!Wu.test(s[u]);)d.appendChild(QA(o,s[u],t,n.value)),n.value+=1,u+=1;i.appendChild(d),l=u}r.replaceChild(i,e)},nT=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?i.appendChild(o.createTextNode(d)):(i.appendChild(ZA(o,d,t,n.value)),n.value+=1));r.replaceChild(i,e)},Wa=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??XA).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=i.nextNode();for(;d;)eT(d,s)||l.push(d),d=i.nextNode();let u={value:o?.startIndex??0},p=t==="char"?tT:nT;for(let g of l)p(g,n,u);return r.innerHTML},Uc=(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},Ba=(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},Ab=new WeakMap,oT=(e,t)=>{if(!e.styles)return;let n=Ab.get(t);if(n||(n=new Set,Ab.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},Bu=new WeakMap,rT=(e,t)=>{if(!e.onAttach)return;let n=Bu.get(t);if(n||(n=new Map,Bu.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Pb=e=>{let t=Bu.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},qc=(e,t)=>{oT(e,t),rT(e,t)};function Ou(e,t=Xt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),i=s.position==="static"||s.position==="";return i&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{i&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Oa=0,xr=null;function Du(e=document){if(Oa++,Oa===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;xr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let t=!1;return()=>{if(!t&&(t=!0,Oa=Math.max(0,Oa-1),Oa===0&&xr)){let n=e.body,o=e.defaultView??window;n.style.overflow=xr.originalOverflow,n.style.position=xr.originalPosition,n.style.top=xr.originalTop,n.style.width=xr.originalWidth,o.scrollTo(0,xr.scrollY),xr=null}}}var Da={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ct=e=>(e?.launcher?.mountMode??"floating")==="docked",Sr=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",wn=e=>{let t=e?.launcher?.dock;return{side:t?.side??Da.side,width:t?.width??Da.width,animate:t?.animate??Da.animate,reveal:t?.reveal??Da.reveal,maxHeight:t?.maxHeight??Da.maxHeight}};var _u=e=>e==="followUp"?"follow-up":e,Nu=(e,t=0)=>{if(typeof e=="string"){let r=e.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=e.label.trim();if(!n)return null;let o=e.prompt?.trim()||n;return{id:e.id?.trim()||o||`suggestion-${t}`,label:n,prompt:o,description:e.description?.trim()||void 0,icon:e.icon,iconColor:e.iconColor?.trim()||void 0,behavior:e.behavior,emphasis:e.emphasis??"default"}},sT=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Lb=new WeakSet,iT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aT=e=>{iT()||e.forEach((t,n)=>{typeof t.animate=="function"&&t.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Fu=e=>{var _,P,A;let{item:t,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:d,chipsConfig:u,session:p,getTextarea:g,eventTarget:y}=e,m=o==="followUp",b=t.behavior,x=()=>{if(p.isStreaming())return;let B={suggestion:{...t},surface:o,source:r,behavior:b},R=y.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:B,bubbles:!0,composed:!0,cancelable:!0}));if(m&&y.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!R)return;for(let U of d)if(U.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:s,config:l})===!1)return;let W=g();if(b==="fill"){W.value=t.prompt,W.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),W.focus();return}W.value="",p.sendMessage(t.prompt)},T=()=>{let B=v("button",`persona-suggestion persona-suggestion--${s}`);if(B.type="button",B.disabled=i,B.dataset.suggestionId=t.id,B.dataset.emphasis=t.emphasis,B.dataset.behavior=b,s==="chip"&&(u?.fontFamily&&(B.style.fontFamily=sT(u.fontFamily)),u?.fontWeight&&(B.style.fontWeight=u.fontWeight),u?.paddingX&&(B.style.paddingLeft=u.paddingX,B.style.paddingRight=u.paddingX),u?.paddingY&&(B.style.paddingTop=u.paddingY,B.style.paddingBottom=u.paddingY)),t.icon){let W=de(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);W&&(W.classList.add("persona-suggestion__icon"),t.iconColor&&(W.style.color=t.iconColor),B.appendChild(W))}let R=v("span","persona-suggestion__copy");if(R.appendChild(ge("span",{className:"persona-suggestion__label",text:t.label})),t.description&&s!=="chip"&&R.appendChild(ge("span",{className:"persona-suggestion__description",text:t.description})),B.appendChild(R),s!=="chip"){let W=de("arrow-right",16,"currentColor",1.8);W&&(W.classList.add("persona-suggestion__arrow"),B.appendChild(W))}return B.addEventListener("click",x),B},H=null;for(let B of d)if(B.renderSuggestion&&(H=B.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:T,select:x}),H))break;return H??(H=T()),(_=H.dataset).suggestionId||(_.suggestionId=t.id),(P=H.dataset).behavior||(P.behavior=b),(A=H.dataset).emphasis||(A.emphasis=t.emphasis),H instanceof HTMLButtonElement||H.setAttribute("aria-disabled",i?"true":"false"),H},_a=e=>{let t=[],n=[],o=null,r=null,s=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},i=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){s();return}let p=Math.max(0,e.scrollWidth-e.clientWidth);if(p<=1){s();return}let g=getComputedStyle(e).direction==="rtl",y=Math.min(p,Math.max(0,Math.abs(e.scrollLeft))),m=4,b=y<=m,x=y>=p-m,T=g?!x:!b,H=g?!b:!x;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",H)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};e.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(p,g,y,m,b,x)=>{e.replaceChildren(),t.length=0,n.length=0;let T=x?.source??"config",H=x?.surface??(T==="config"?"starter":"followUp"),_=H==="followUp",P=x?.variant??"chip",A=x?.behavior??"send",B=x?.overflow??"wrap",R=x?.config??{},W=x?.plugins??[],U=typeof x?.maxItems=="number"?Math.max(0,Math.floor(x.maxItems)):void 0,V=_?"followUps":"starters";!Lb.has(R)&&R.debug===!0&&P!=="chip"&&R.suggestions?.[V]?.overflow!==void 0&&(Lb.add(R),console.info(`[persona] suggestions.${V}.overflow applies to the "chip" variant only; the "${P}" variant manages its own stacking.`));let Z=ye=>ye.map(Nu).filter(oe=>oe!==null).map(oe=>({...oe,behavior:oe.behavior??A})),j=Z(p??[]);W.forEach(ye=>{ye.transformSuggestions&&(j=Z(ye.transformSuggestions({suggestions:j.map(oe=>({...oe})),surface:H,source:T,config:R})))});let X=U===void 0?j:j.slice(0,U);if(!X.length){e.hidden=!0,o=null,s();return}if(!_&&(m??g.getMessages()).some(oe=>oe.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=_u(H),e.dataset.variant=P,e.dataset.overflow=B;let ue=document.createDocumentFragment(),xe=g.isStreaming();X.forEach((ye,oe)=>{let le=Fu({item:ye,index:oe,surface:H,source:T,variant:P,streaming:xe,config:R,plugins:W,chipsConfig:b,session:g,getTextarea:()=>y,eventTarget:e});ue.appendChild(le),n.push(le),[...le instanceof HTMLButtonElement?[le]:[],...Array.from(le.querySelectorAll("button"))].forEach(M=>{t.includes(M)||(M.disabled=xe,t.push(M))})}),e.appendChild(ue),i(),l();let Ce=JSON.stringify({normalized:X,surface:H,variant:P,source:T});Ce!==o&&(o=Ce,aT(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:X.map(ye=>({...ye})),surface:H,source:T,variant:P},bubbles:!0,composed:!0})),_&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:X.map(ye=>ye.prompt)},bubbles:!0,composed:!0})))}}};var In={"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 lT="persona-header-control",cT="persona-header-control--glyph",dT="persona-header-control--sparse",pT=20,uT={x:[1.4,1.05]},Hb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",gT="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Vc=(e,t,n={})=>{let{iconSize:o,iconText:r}=n,[s,i]=uT[t]??[1,1.5],l=!o;e.classList.toggle(cT,l),e.classList.toggle(dT,l&&s!==1);let d=parseFloat(o??"")||pT,u=de(t,`${Math.round(d*s)}px`,"currentColor",i);u?(u.style.display="block",l||(u.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((i/1.5).toFixed(4))})`),e.replaceChildren(u)):r&&(e.textContent=r)},cs=e=>{let{ariaLabel:t,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:i=Hb,size:l,iconSize:d,color:u,backgroundColor:p,borderWidth:g,borderColor:y,borderRadius:m,paddingX:b,paddingY:x,hidden:T,extraClassName:H,attrs:_}=e,P=v("div",i),A=!!(g||y),B=ge("button",{className:jn(lT,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!m&&"persona-rounded-full",H),attrs:{type:"button","aria-label":t,..._},style:{width:l,height:l,minWidth:l,minHeight:l,display:T?"none":void 0,color:u||un.actionIconColor,backgroundColor:p,border:A?`${g||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:m,paddingLeft:b,paddingRight:b,paddingTop:x,paddingBottom:x}});return r?Vc(B,r,{iconSize:d,iconText:s}):s&&(B.textContent=s),P.appendChild(B),Qt({anchor:B,trigger:P,text:()=>B.getAttribute("aria-label")??t,hint:o,enabled:n}),{button:B,wrapper:P}},ui=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Hb,buttonSize:r,iconSize:s}=t,i=e?.launcher??{},l=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,{button:u,wrapper:p}=cs({ariaLabel:l,tooltip:d,iconName:i.closeButtonIconName??"x",iconText:i.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??i.closeButtonSize,iconSize:s,color:i.closeButtonColor,backgroundColor:i.closeButtonBackgroundColor,borderWidth:i.closeButtonBorderWidth,borderColor:i.closeButtonBorderColor,borderRadius:i.closeButtonBorderRadius,paddingX:i.closeButtonPaddingX,paddingY:i.closeButtonPaddingY,hidden:!n});return{button:u,wrapper:p}},gi=(e,t={})=>{let{wrapperClassName:n=gT,buttonSize:o,iconSize:r}=t,i=(e?.launcher??{}).clearChat??{},l=i.tooltipText??"Clear chat",d=i.showTooltip??!0,{button:u,wrapper:p}=cs({ariaLabel:l,tooltip:d,iconName:i.iconName??"refresh-cw",wrapperClassName:n,size:o??i.size,iconSize:r,color:i.iconColor,backgroundColor:i.backgroundColor,borderWidth:i.borderWidth,borderColor:i.borderColor,borderRadius:i.borderRadius,paddingX:i.paddingX,paddingY:i.paddingY});return{button:u,wrapper:p}};var un={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))",minHeight:"var(--persona-header-min-height, auto)"},$u={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},fT={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},jo=e=>{let{config:t,showClose:n=!0}=e,o=ge("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{minHeight:un.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=t?.launcher??{},s=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,u=ge("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(d){let B=parseFloat(s)||24,R=de(d,B*.6,"currentColor",1);R?u.replaceChildren(R):u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let B=v("img");B.src=t.launcher.iconUrl,B.alt="",B.className="persona-rounded-xl persona-object-cover",B.style.height=s,B.style.width=s,u.replaceChildren(B)}else u.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=ge("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:un.titleColor,...$u}}),y=ge("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:un.subtitleColor,...fT}});p.append(g,y),l?o.append(p):o.append(u,p);let m=r.clearChat??{},b=m.enabled??!0,x=m.placement??"inline",T=null,H=null;if(b){let R=gi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=R.button,H=R.wrapper,x==="top-right"&&(H.style.right="48px"),x==="inline"&&o.appendChild(H)}let _=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:A}=ui(t,{showClose:n,wrapperClassName:_});return i!=="top-right"&&o.appendChild(A),{header:o,iconHolder:u,headerTitle:g,headerSubtitle:y,closeButton:P,closeButtonWrapper:A,clearChatButton:T,clearChatButtonWrapper:H}},ds=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var ju=e=>{let t=jo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return t};function mT(e,t,n){if(t?.length)for(let o of t){let{button:r,wrapper:s}=cs({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?Lc(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let i=ka(o.shortcut);i&&r.setAttribute("aria-keyshortcuts",i)}if(o.menuItems?.length){let i=as({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()})}else r.addEventListener("click",()=>n?.(o.id));e.appendChild(s)}}var zu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,i=t?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=un.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,u,p;if(d){let A=Dc({label:i.title??"Chat Assistant",menuItems:d.menuItems,onSelect:B=>{let R=U=>{U===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:B}}))},W=d.onSelect(B);W instanceof Promise?W.then(R,()=>{}):R(W)},hover:d.hover,className:""});u=A.element,u.style.color=un.titleColor,p=u.querySelector(".persona-combo-btn-label")??u}else{if(u=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=un.titleColor,Object.assign(p.style,$u),p.textContent=i.title??"Chat Assistant",u.appendChild(p),r?.onTitleClick){u.style.cursor="pointer",u.setAttribute("role","button"),u.setAttribute("tabindex","0");let B=r.onTitleClick;u.addEventListener("click",R=>{R.target.closest("button")||B()}),u.addEventListener("keydown",R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),B())})}let A=r?.titleRowHover;A&&(u.style.borderRadius=A.borderRadius??"10px",u.style.padding=A.padding??"6px 4px 6px 12px",u.style.margin="-6px 0 -6px -12px",u.style.border="1px solid transparent",u.style.transition="background-color 0.15s ease, border-color 0.15s ease",u.style.width="fit-content",u.style.flex="none",u.addEventListener("mouseenter",()=>{u.style.backgroundColor=A.background??"",u.style.borderColor=A.border??""}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="",u.style.borderColor="transparent"}))}l.appendChild(u);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:y,wrapper:m}=ui(t,{showClose:n,wrapperClassName:g});o&&y.addEventListener("click",o);let b=v("div","persona-flex persona-items-center persona-gap-1");d||mT(b,r?.trailingActions,r?.onAction??s);let x=i.clearChat??{},T=null,H=null;if(x.enabled??!0){let A=x.placement??"inline",B=gi(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});T=B.button,H=B.wrapper,A==="top-right"?H.style.right="48px":b.appendChild(H)}b.appendChild(m),l.appendChild(b);let _=v("div");_.style.display="none";let P=v("span");return P.style.display="none",{header:l,iconHolder:_,headerTitle:p,headerSubtitle:P,closeButton:y,closeButtonWrapper:m,clearChatButton:T,clearChatButtonWrapper:H}},Kc={default:ju,minimal:zu},Uu=e=>Kc[e]??Kc.default,fi=(e,t,n)=>{if(t?.render){let i=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let d=v("span"),u=v("span"),p=v("button");p.style.display="none";let g=v("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:d,headerSubtitle:u,closeButton:p,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=Uu(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Gc=e=>{let t=v("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20,r=()=>{let d=t.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let u=d.getComputedStyle(t).lineHeight;if(!u||!u.trim().endsWith("px"))return o;let p=parseFloat(u);return Number.isFinite(p)&&p>0?p:o},s=`${n*o}px`;t.style.maxHeight=s,t.style.overflowY="auto";let i=()=>{let d=t.style.maxHeight;if(d!==s){let p=parseFloat(d);if(Number.isFinite(p)&&p>0)return p}let u=n*r();return s=`${u}px`,t.style.maxHeight=s,u},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,i());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:l}},Yc=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",i=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",d=e?.copy?.sendButtonLabel??"Send",u=e?.copy?.stopButtonLabel??"Stop",p=t.showTooltip??!1,g=t.size??"40px",y=t.backgroundColor,m=t.textColor,b=v("div","persona-send-button-wrapper"),x=ge("button",{className:jn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!y&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&y||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:n?"0":t.paddingX||void 0,paddingRight:n?"0":t.paddingX||void 0,paddingTop:n?"0":t.paddingY||void 0,paddingBottom:n?"0":t.paddingY||void 0}}),T=null,H=null;if(n){let A=parseFloat(t.iconSize??"")||Math.round((parseFloat(g)||24)*.5),B=t.iconStrokeWidth??2,R=m?.trim()||"currentColor";r?(T=de(r,A,R,B),T?x.appendChild(T):x.textContent=o):x.textContent=o,H=de(s,A,R,B)}else x.textContent=d;x.setAttribute("aria-label",i),b.appendChild(x),Qt({anchor:x,trigger:b,text:()=>x.getAttribute("aria-label")??"",enabled:p});let _="send";return{button:x,wrapper:b,setMode:A=>{if(A===_)return;_=A;let B=A==="stop"?l:i;if(x.setAttribute("aria-label",B),n){if(T&&H){let R=A==="stop"?H:T;x.replaceChildren(R)}}else x.textContent=A==="stop"?u:d}}},Jc=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let i=e?.sendButton?.size??"40px",l=t.iconName??"mic",d=t.iconSize??i,u=parseFloat(d)||24,p=t.backgroundColor??e?.sendButton?.backgroundColor,g=t.iconColor??e?.sendButton?.textColor,y=v("div","persona-send-button-wrapper"),m=ge("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":t.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=de(l,u,g||"currentColor",1.5);x?m.appendChild(x):m.textContent="\u{1F3A4}",y.appendChild(m);let T=t.tooltipText??"Start voice recognition",H=t.showTooltip??!1;return Qt({anchor:m,trigger:y,text:()=>m.getAttribute("aria-label")??T,enabled:H}),{button:m,wrapper:y}},Xc=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??No).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,d=Math.round(l*.6),u=v("div","persona-send-button-wrapper"),p=ge("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":t.buttonTooltipText??"Attach file"},style:{width:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),g=de(s,d,"currentColor",1.5);g?p.appendChild(g):p.textContent="\u{1F4CE}",p.addEventListener("click",m=>{m.preventDefault(),r.click()}),u.appendChild(p);let y=t.buttonTooltipText??"Attach file";return Qt({anchor:p,trigger:u,text:()=>p.getAttribute("aria-label")??y}),{button:p,wrapper:u,input:r,previewsContainer:o}},Qc=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let i=v("a");i.href=t.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},Zc=()=>ge("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ps=e=>{let{config:t}=e,n=ge("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=Zc(),r=ge("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=Gc(t);i();let l=Yc(t),d=Jc(t),u=Xc(t),p=Qc(t);u&&(u.previewsContainer.style.gap="8px",r.append(u.previewsContainer,u.input)),r.append(s);let g=ge("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return u&&y.append(u.wrapper),d&&m.append(d.wrapper),m.append(l.wrapper),g.append(y,m),r.append(g),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),n.append(o,r,p),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:p,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:g,leftActions:y,rightActions:m,setSendButtonMode:l.setMode}};var Ib=()=>{let e=ge("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=v("span","persona-pill-peek__icon"),n=de("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=de("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ed=e=>{let{config:t}=e,n=ge("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Zc(),r=Qc(t);r.style.display="none";let{textarea:s,attachAutoResize:i}=Gc(t);s.style.maxHeight="100px",i();let l=Yc(t),d=Jc(t),u=Xc(t);u&&u.previewsContainer.classList.add("persona-pill-composer__previews");let p=ge("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");u&&g.append(u.wrapper);let y=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&y.append(d.wrapper),y.append(l.wrapper),p.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&b.target!==u?.button&&b.target!==u?.wrapper&&s.focus()}),u&&p.append(u.input),p.append(g,s,y),u&&n.append(u.previewsContainer),n.append(o,p,r);let m=p;return{footer:n,suggestions:o,composerForm:p,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:u?.button??null,attachmentButtonWrapper:u?.wrapper??null,attachmentInput:u?.input??null,attachmentPreviewsContainer:u?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:y,setSendButtonMode:l.setMode}};var hT=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}},yT=(e,t)=>{if(!e)return null;let n=hT(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},bT=(e,t)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},vT=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},qu=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(":"))},Vu=320,Ob=320,CT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),wT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),xT=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ST=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),AT=e=>{if(!e||e.length===0)return null;let t=ge("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=ge("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=de(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(ge("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},TT=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ta(o.ref,{readonly:!0,render:t}))}return n},Rb="\uE000",Wb="\uE001",ET=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Rb}${r}:${y}${Wb}`,i=t.map((y,m)=>y.kind==="text"?y.text:s(m)).join(""),l=n(i);if(!t.every((y,m)=>y.kind==="text"||l.includes(s(m)))){e.replaceChildren(TT(t,o));return}e.innerHTML=l;let u=new RegExp(`${Rb}${r}:(\\d+)${Wb}`),p=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),g=[];for(let y=p.nextNode();y;y=p.nextNode())g.push(y);for(let y of g){let m=y;for(let b=u.exec(m.data);b;b=u.exec(m.data)){let x=t[Number(b[1])],T=m.splitText(b.index);T.data=T.data.slice(b[0].length),x?.kind==="mention"&&T.parentNode?.insertBefore(Ta(x.ref,{readonly:!0,render:o}),T),m=T}}},MT=(e,t,n)=>{if(e.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((l,d)=>{let u=v("img");u.alt=l.alt?.trim()||`Attached image ${d+1}`,u.loading="lazy",u.decoding="async",u.referrerPolicy="no-referrer",u.style.display="block",u.style.width="100%",u.style.maxWidth=`${Vu}px`,u.style.maxHeight=`${Ob}px`,u.style.height="auto",u.style.objectFit="contain",u.style.borderRadius="10px",u.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",u.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;r+=1,u.addEventListener("error",()=>{p||(p=!0,r=Math.max(0,r-1),u.remove(),r===0&&i())}),u.addEventListener("load",()=>{p=!0}),vT(l.image)?(u.src=l.image,o.appendChild(u)):(p=!0,r=Math.max(0,r-1),u.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},kT=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!qu(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vu}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},PT=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!qu(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Vu}px`,r.style.maxHeight=`${Ob}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},LT=e=>{if(e.length===0)return null;try{let t=v("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!qu(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},us=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Ku=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:us};if(t){let r=t(o);if(r!==null)return r}return us()},HT=(e,t)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=t==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Bb=(e,t,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Na=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},Gu=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,i=t.showReadAloud??!1;if(!o&&!r&&!s&&!i){let b=v("div");return b.style.display="none",b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id),b}let l=t.visibility??"hover",d=t.align??"right",u=t.layout??"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],y=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id);let m=(b,x,T)=>{let H=rt({icon:b,label:x,size:14,className:"persona-message-action-btn"});return H.setAttribute("data-action",T),H};return o&&y.appendChild(m("copy","Copy message","copy")),i&&y.appendChild(m("volume-2","Read aloud","read-aloud")),r&&y.appendChild(m("thumbs-up","Upvote","upvote")),s&&y.appendChild(m("thumbs-down","Downvote","downvote")),y},mi=(e,t,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",d=i.avatar,u=i.timestamp,p=d?.show??!1,g=u?.show??!1,y=d?.position??"left",m=u?.position??"below",b=Na(e.role,l),x=v("div",b.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(x.style.backgroundColor="transparent",x.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=CT(e),H=e.content?.trim()??"",P=T.length>0&&H===Qs,A=jc(s?.widgetConfig?.features?.streamAnimation),B=s?.widgetConfig?.features?.streamAnimation?.plugins,R=e.role==="assistant"&&A.type!=="none"?pi(A.type,B):null,W=e.role==="assistant"&&R?.isAnimating?.(e)===!0,U=e.role==="assistant"&&R!==null&&(!!e.streaming||W);U&&R?.bubbleClass&&x.classList.add(R.bubbleClass);let V=document.createElement("div");V.classList.add("persona-message-content"),e.streaming&&V.classList.add("persona-content-streaming"),U&&R&&(R.containerClass&&V.classList.add(R.containerClass),V.style.setProperty("--persona-stream-step",`${A.speed}ms`),V.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let Z=U?zc(e.content??"",A.buffer,R,e,!!e.streaming):e.content??"",j=()=>{let ee=t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&R?.wrap==="char"?Wa(ee,"char",e.id,{skipTags:R.skipTags}):U&&R?.wrap==="word"?Wa(ee,"word",e.id,{skipTags:R.skipTags}):ee},X=null;if(P?(X=document.createElement("div"),X.innerHTML=j(),X.style.display="none",V.appendChild(X)):e.contentSegments?.length?ET(V,e.contentSegments,ee=>t({text:ee,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):V.innerHTML=j(),U&&R?.useCaret&&!P&&H){let ee=Uc(),pe=V.querySelectorAll(".persona-stream-char, .persona-stream-word"),we=pe[pe.length-1];if(we?.parentNode)we.parentNode.insertBefore(ee,we.nextSibling);else{let me=V.lastElementChild;me?me.appendChild(ee):V.appendChild(ee)}}if(g&&m==="inline"&&e.createdAt){let ee=Bb(e,u,"span");ee.classList.add("persona-timestamp-inline");let pe=V.lastElementChild;pe?pe.appendChild(ee):V.appendChild(ee)}if(T.length>0){let ee=MT(T,!P&&!!H,()=>{P&&X&&(X.style.display="")});ee?x.appendChild(ee):P&&X&&(X.style.display="")}let ue=wT(e);if(ue.length>0){let ee=kT(ue);ee&&x.appendChild(ee)}let xe=xT(e);if(xe.length>0){let ee=PT(xe);ee&&x.appendChild(ee)}let Ce=ST(e);if(Ce.length>0){let ee=LT(Ce);ee&&x.appendChild(ee)}let ye=e.contentSegments?.length?null:AT(e.contextMentions);if(ye&&x.appendChild(ye),x.appendChild(V),g&&m==="below"&&e.createdAt){let ee=Bb(e,u);ee.classList.add("persona-mt-1"),x.appendChild(ee)}let oe=e.role==="assistant"?yT(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let ee=!!(Z&&Z.trim()),pe=A.placeholder==="skeleton",we=pe&&A.buffer==="line"&&ee;if(ee)we&&x.appendChild(Ba());else if(pe)x.appendChild(Ba());else{let me=Ku("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);me&&x.appendChild(me)}}if(oe&&e.stopReason&&!e.streaming&&(H||(V.style.display="none"),x.appendChild(bT(e.stopReason,oe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let ee=Gu(e,o,r);x.appendChild(ee)}if(!p||e.role==="system")return x;let ae=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),M=HT(d,e.role);return y==="right"||y==="left"&&e.role==="user"?ae.append(x,M):ae.append(M,x),ae},Db=(e,t,n,o,r,s)=>{let i=n??{};return e.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):mi(e,t,n,o,r,s)};var IT=40,RT=(e,t)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}if(typeof t=="function"){let n=null;try{n=t()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){e.hidden=!0;return}e.appendChild(n),e.hidden=!1;return}if(t.type==="lucide"){let n=de(t.name,IT);if(!n){e.hidden=!0;return}e.appendChild(n)}else t.type==="image"?e.appendChild(ge("img",{className:"persona-welcome-icon-image",attrs:{src:t.url,alt:t.alt}})):e.appendChild(ge("span",{className:"persona-welcome-icon-text",text:t.text}));e.hidden=!1},_b=(e,t,n={})=>{let o=ge("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),s=v("p","persona-welcome-subtitle");return{host:ge("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,t),iconHolder:o,title:r,subtitle:s,starterSuggestions:t}},hi=(e,t,n)=>{t.hidden=!n,t.style.display=n?"":"none",e.classList.toggle("persona-gap-6",n),e.classList.toggle("persona-gap-3",!n)},nd=(e,t)=>{e.title.textContent=t.title,e.subtitle.textContent=t.subtitle,e.subtitle.hidden=t.subtitle==="",RT(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},WT="data-persona-welcome-plugin",Nb="data-persona-welcome-overlay",td="persona-welcome-overlay-active",Yu=new WeakMap,Ju=(e,t,n)=>{n.setAttribute(WT,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(Nb,""),e.classList.contains(td)||(Yu.set(e,e.scrollTop),e.classList.add(td),e.scrollTop=0)},Xu=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(Nb),e.classList.contains(td)&&(e.classList.remove(td),e.scrollTop=Yu.get(e)??e.scrollTop,Yu.delete(e))},Fb=()=>{let e=ge("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},od=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ge("div",{className:Na("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:t,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});e.appendChild(ge("div",{className:"persona-flex"},r)),e.hidden=!1},BT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,$b=(e,t)=>{if(BT()||typeof e.animate!="function"||!e.isConnected)return t(null),null;let n=e.getBoundingClientRect(),o=e.parentElement,r=0,s=0,i=0;if(o){let b=getComputedStyle(o);r=parseFloat(b.rowGap)||0;let x=e.previousElementSibling,T=e.nextElementSibling,_=o.getBoundingClientRect().top+(parseFloat(b.borderTopWidth)||0)+(parseFloat(b.paddingTop)||0)-o.scrollTop;s=Math.max(0,x?n.top-x.getBoundingClientRect().bottom-r:n.top-_),i=Math.max(0,T?T.getBoundingClientRect().top-n.bottom-r:0)}let l=e.style.overflow;e.style.overflow="hidden";let d=getComputedStyle(e),u=parseFloat(d.paddingTop)||0,p=parseFloat(d.paddingBottom)||0,g=e.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${u}px`,paddingBottom:`${p}px`,marginTop:`${s}px`,marginBottom:`${i}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),y=!1,m=()=>{y||(y=!0,e.style.overflow=l,t(g))};return g.finished.then(m).catch(m),g};var OT="Hello \u{1F44B}",DT="I can answer questions and help you get things done here.",jb=new WeakSet,qn=(e,t)=>!!e&&e[t]!==void 0,_T=(e,t)=>{!e||e.debug!==!0||!t.length||jb.has(e)||(jb.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},zo=e=>{let t=e?.welcome,n=e?.copy,o=qn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":qn(t,"dismiss")?t.dismiss:"never",s=[];return qn(t,"title")&&qn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),qn(t,"subtitle")&&qn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),qn(t,"variant")&&qn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&qn(t,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&qn(t,"dismiss")&&t.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),_T(e,s),{title:qn(t,"title")?t.title:n?.welcomeTitle??OT,subtitle:qn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??DT,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Ar=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var zb="16px",Qu="10px",Zu="14px",Ub=e=>{let t=e?.launcher?.enabled??!0,n=Ct(e);if(Sr(e)){let p=e?.launcher?.composerBar??{},g=v("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=p.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Xt);let y=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",g.appendChild(y);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=p.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Xt),{wrapper:g,panel:y,pillRoot:m}}if(n){let p=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return p.appendChild(g),{wrapper:p,panel:g}}if(!t){let p=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=e?.launcher?.width??"100%";return p.style.width=y,g.style.width="100%",p.appendChild(g),{wrapper:p,panel:g}}let r=e?.launcher??{},s=r.position&&In[r.position]?In[r.position]:In["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(e?.launcher?.zIndex??Xt);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),u=e?.launcher?.width??e?.launcherWidth??Hn;return l.style.width=u,l.style.maxWidth=u,i.appendChild(l),{wrapper:i,panel:l}},eg=e=>{let t=ge("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":_u(e)}});return t.hidden=!0,t},qb=(e,t)=>{let n=eg("starter"),o=_b(e,n,{flatShadow:Ct(e)}),r=zo(e);nd(o,r),hi(t,o.host,Ar(r,e?.initialMessages));let s=Fb();return od(s,r.message,e),{welcome:o,greetingHost:s}},NT=(e,t)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:zb,iconSize:Qu});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=e?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let W=gi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:zb,iconSize:Zu});i=W.button,l=W.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=ge("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),u=ge("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});u.style.setProperty("scrollbar-gutter","stable");let{welcome:p,greetingHost:g}=qb(e,u),{host:y,title:m,subtitle:b}=p,x=p.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),H=eg("followUp"),_=br(e,!0);_&&(T.style.maxWidth=_,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),u.append(y,g,T,H);let P=ge("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),A=ed({config:e}),{root:B,textNode:R}=Ib();return n.append(d,r,u,P),l&&n.appendChild(l),{container:n,body:u,messagesWrapper:T,starterSuggestions:x,transcriptSuggestions:H,composerOverlay:P,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:y,welcomeIconHolder:p.iconHolder,greetingHost:g,introTitle:m,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:B,peekTextNode:R}},Vb=(e,t=!0)=>{if(Sr(e))return NT(e,t);let n=ge("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?fi(e,o,{showClose:t}):jo({config:e,showClose:t}),i=ge("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:d}=qb(e,i),{host:u,title:p,subtitle:g}=l,y=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=eg("followUp"),x=br(e,!1);x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),i.append(u,d,m,b);let T=ps({config:e}),H=e?.layout?.showFooter!==!1;r?ds(n,s,e):(s.header.style.display="none",ds(n,s,e)),n.append(i);let _=ge("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 H||(T.footer.style.display="none"),n.append(T.footer),n.append(_),{container:n,body:i,messagesWrapper:m,starterSuggestions:y,transcriptSuggestions:b,composerOverlay:_,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:u,welcomeIconHolder:l.iconHolder,greetingHost:d,introTitle:p,introSubtitle:g,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};var tg=(e,t)=>{let n=v("button");n.type="button",n.innerHTML=`
34
34
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
35
35
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
36
36
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
37
- <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
38
- <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
37
+ <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
38
+ <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
39
39
  </span>
40
40
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
41
- `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Mt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let E=a.title??"Chat Assistant";p.textContent=E,p.setAttribute("title",E)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let E=a.subtitle??"Here to help you get answers fast";d.textContent=E,d.setAttribute("title",E)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let E=a.agentIconSize??"40px";if(g.style.height=E,g.style.width=E,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let P=parseFloat(E)||24,B=se(a.agentIconName,P*.6,"var(--persona-text-inverse, #ffffff)",2);B?(g.appendChild(B),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let E=a.agentIconSize??"40px";b.style.height=E,b.style.width=E,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let E=a.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,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 P=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,P=(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 B=parseFloat(E)||24,N=Math.max(B-P,8),$=se(a.callToActionIconName,N,"currentColor",2);$?f.appendChild($):f.textContent=a.callToActionIconText??"\u2197"}else f.textContent=a.callToActionIconText??"\u2197"}let x=a.position&&un[a.position]?un[a.position]:un["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",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:`${C} ${x}`,i||(n.style.zIndex=String(a.zIndex??$t));let k="1px solid var(--persona-border, #e5e7eb)",R="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??k,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:R,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="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},nC="teaser-dismissed",Tm=new Set,Sm=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${nC}`},oC=(e,t)=>{if(Tm.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},rC=(e,t)=>{if(Tm.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},sC=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,aC=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Mt(e??{})?null:t},Em=(e,t)=>{let n=y("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,a=null,i=null,p=null,d=!1,c=!1,g=!1,b=!1,f=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,x=()=>{p!==null&&(clearTimeout(p),p=null)},C=()=>{!s||!d||(d=!1,s.hidden=!0)},S=Y=>{x(),g=!0,C(),rC(Sm(o),Y&&f())},k=Y=>{!r||g||S(Y==="user"&&d)},R=()=>{p=null,!(!s||g||b)&&(c=!0,d=!0,s.hidden=!1,!(sC()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},E=()=>{!r||!s||g||c||b||oC(Sm(o),f())||(x(),p=setTimeout(R,Math.max(0,r.delayMs??0)))},P=()=>{S(f()),t()},B=Y=>{Y.stopPropagation(),S(f())},$=Dd(e,()=>{k("user"),t()}),z=()=>{x(),i?.removeEventListener("click",P),a?.removeEventListener("click",B),s?.remove(),s=null,i=null,a=null,d=!1},q=()=>{i=ke("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),i.addEventListener("click",P),a=ke("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",B),s=ke("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},i,a),n.insertBefore(s,$.element)},X=()=>{let Y=o.launcher?.position??"bottom-right",he=un[Y]??un["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",$.element.style.position="";return}n.className=Hn("persona-launcher-surface",he),n.setAttribute("data-teaser",Y),n.style.zIndex=String(o.launcher?.zIndex??$t),$.element.style.position="static"},A=Y=>{let he=aC(Y);if(r=he,!he){z();return}s||q(),i.textContent=he.text,a.hidden=he.dismissible===!1,a.setAttribute("aria-label",he.dismissLabel??"Dismiss message"),E()},J=Y=>{o=Y,$.update(Y),A(Y),X()},Z=(Y,he="user")=>{b=Y,Y&&k(he)},ce=()=>{z(),$.destroy(),n.remove()};return n.appendChild($.element),e&&(A(e),X()),{element:n,launcher:$,get teaser(){return s?{element:s,show:R,dismiss:S}:null},setPanelOpen:Z,update:J,destroy:ce}};var Mm=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Cm(e),s=Am(e,t),a={wrapper:n,panel:o,pillRoot:r},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{d.footer.replaceWith(b),d.footer=b}}},Od=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>Dd(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Em(e,n);return{instance:r,element:r.element}};var iC=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},lC=(e,t,n)=>`${iC(e)}plugin:${t}:${n}`,km=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>lC(e(),r,a);return{get:a=>{let i=s(a),p=o();if(p)try{return p.getItem(i)}catch{n=!0}return t.get(i)??null},set:(a,i)=>{let p=s(a),d=o();if(d)try{d.setItem(p,i);return}catch{n=!0}t.set(p,i)},remove:a=>{let i=s(a);t.delete(i);let p=o();if(p)try{p.removeItem(i)}catch{n=!0}}}}};var vs=new Set,cC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),dC=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},Lm=(e,t)=>{let n=vs.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=se(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Nd=(e,t)=>{let n=e.reasoning,o=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&vs.has(e.id),i=n.status!=="complete",p=dC(e,r.previewMaxLines??3),d=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");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",f=t?.reasoning??{},x=String(n.startedAt??Date.now()),C=()=>{let ce=y("span","");return ce.setAttribute("data-tool-elapsed",x),ce.textContent=Ti(n),ce},S=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:Ti(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(g.textContent=S,c.appendChild(g)):S instanceof HTMLElement?c.appendChild(S):(g.textContent=b,c.appendChild(g));let k=y("span","persona-text-xs persona-text-persona-primary");k.textContent=Fg(n),c.appendChild(k);let R=r.loadingAnimation??"none",E=f.activeTextTemplate,P=f.completeTextTemplate,B=i?E:P,N=S instanceof HTMLElement,$=(ce,Y)=>{g.textContent="";let he=Ei(ce,""),te=0;for(let be of he){let ee=be.styles.length>0?(()=>{let ge=y("span",be.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return g.appendChild(ge),ge})():g;if(be.isDuration&&i)ee.appendChild(C());else{let ge=be.isDuration?Ti(n):be.text;Y?te=Uo(ee,ge,te):ee.appendChild(document.createTextNode(ge))}}};if(!N&&B)if(k.style.display="none",g.style.display="",i&&R!=="none"){let ce=f.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),R==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),$(B,!1)):(g.classList.add(`persona-tool-loading-${R}`),g.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),$(B,!0))}else $(B,!1);else if(!N&&i&&R!=="none"){g.style.display="";let ce=f.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),R==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ce}ms`);else{g.classList.add(`persona-tool-loading-${R}`),g.style.setProperty("--persona-tool-anim-duration",`${ce}ms`),R==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Y=g.textContent||b;g.textContent="",Uo(g,Y,0)}n.status==="complete"&&(g.style.display="none")}else N||(n.status==="complete"?g.style.display="none":g.style.display="");let z=null;if(s){z=y("div","persona-flex persona-items-center");let Y=se(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show";let he=y("div","persona-flex persona-items-center persona-ml-auto");he.append(z),d.append(c,he)}else d.append(c);let q=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let ce=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});cC(q,ce)||(q.textContent=p),q.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,q),o;let X=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");X.style.display=a?"":"none";let A=n.chunks.join(""),J=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=A||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),X.appendChild(J),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),z){z.innerHTML="";let Y=se(a?"chevron-up":"chevron-down",16,"currentColor",2);Y?z.appendChild(Y):z.textContent=a?"Hide":"Show"}X.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,X),o};var xs=new Set,pC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),uC=(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(`
43
- `);let r=Bo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
- `):""},Fd=(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)"},gC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=uC(e,o?.previewMaxLines??3),a=n?_g(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=Xc(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=Xc(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Pm=(e,t,n)=>{let o=xs.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=se(o?"chevron-up":"chevron-down",16,c,2);g?d.appendChild(g):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},_d=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&xs.has(e.id),{summary:p,previewText:d,isActive:c}=gC(e,t),g=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let b=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let x=String(n.startedAt??Date.now()),C=()=>{let A=y("span","");return A.setAttribute("data-tool-elapsed",x),A.textContent=aa(n),A},S=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:aa(n),createElapsedElement:C});typeof S=="string"&&S.trim()?(f.textContent=S,b.appendChild(f)):S instanceof HTMLElement?b.appendChild(S):(f.textContent=p,b.appendChild(f));let k=s.loadingAnimation??"none",R=o.activeTextTemplate,E=o.completeTextTemplate,P=c?R:E,B=S instanceof HTMLElement,N=(A,J)=>{f.textContent="";let Z=n.name?.trim()||"tool",ce=Ei(A,Z),Y=0;for(let he of ce){let te=he.styles.length>0?(()=>{let be=y("span",he.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return f.appendChild(be),be})():f;if(he.isDuration&&c)te.appendChild(C());else{let be=he.isDuration?aa(n):he.text;J?Y=Uo(te,be,Y):te.appendChild(document.createTextNode(be))}}};if(!B)if(c&&k!=="none"){let A=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),k==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${A}ms`),P&&N(P,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${A}ms`),k==="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)),P)N(P,!0);else{let J=f.textContent||p;f.textContent="",Uo(f,J,0)}}else P&&N(P,!1);let $=null;if(a){$=y("div","persona-flex persona-items-center");let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",J=se(i?"chevron-up":"chevron-down",16,A,2);J?$.appendChild(J):$.textContent=i?"Hide":"Show";let Z=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Z.append($),g.append(b,Z)}else g.append(b);let z=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(z.setAttribute("data-persona-collapsed-preview","tool"),z.style.display="none",z.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let A=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});pC(z,A)||(z.textContent=d),z.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(g,z),r;let q=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let A=y("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?A.style.color=o.contentTextColor:o.headerTextColor&&(A.style.color=o.headerTextColor),A.textContent=n.name,q.appendChild(A)}if(n.args!==void 0){let A=y("div","persona-space-y-1"),J=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Arguments";let Z=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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Fd(Z,o),Z.textContent=Bo(n.args),A.append(J,Z),q.appendChild(A)}if(n.chunks&&n.chunks.length){let A=y("div","persona-space-y-1"),J=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Activity";let Z=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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Fd(Z,o),Z.textContent=n.chunks.join(""),A.append(J,Z),q.appendChild(A)}if(n.status==="complete"&&n.result!==void 0){let A=y("div","persona-space-y-1"),J=y("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(J.style.color=o.labelTextColor),J.textContent="Result";let Z=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");Z.style.fontSize="0.75rem",Z.style.lineHeight="1rem",Fd(Z,o),Z.textContent=Bo(n.result),A.append(J,Z),q.appendChild(A)}if(n.status==="complete"&&typeof n.duration=="number"){let A=y("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(A.style.color=o.contentTextColor),A.textContent=`Duration: ${n.duration}ms`,q.appendChild(A)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),$){$.innerHTML="";let A=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",J=se(i?"chevron-up":"chevron-down",16,A,2);J?$.appendChild(J):$.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",z.style.display=i?"none":z.textContent||z.childNodes.length?"":"none"})(),r.append(g,z,q),r};var Lr=new Map,xl=e=>{let n=(e.startsWith(Wn)?e.slice(Wn.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)},Rm=e=>e?.approval!==!1?e?.approval:void 0,Im=(e,t)=>{let n=Rm(t)?.detailsDisplay??"collapsed";return Lr.get(e)??n==="expanded"},Wm=(e,t,n)=>{let o=Rm(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=se(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Hm=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=Im(e,n);Wm(o,s,n),r.style.display=s?"":"none"};var Cl=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",c=se(p,20,d,2);c&&i.appendChild(c);let g=y("div","persona-flex-1 persona-min-w-0"),b=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let $=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",n.status),n.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):n.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):n.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),b.appendChild($)}g.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Wn)?ea(n.toolName):void 0,S=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,R=S||(k?n.description:`The assistant wants to use \u201C${C??xl(n.toolName)}\u201D.`),E=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=R,g.appendChild(E),n.reason){let $=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");$.setAttribute("data-approval-reason","true"),o?.reasonColor?$.style.color=o.reasonColor:o?.descriptionColor&&($.style.color=o.descriptionColor);let z=y("span","persona-font-medium");z.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,$.appendChild(z),$.appendChild(document.createTextNode(n.reason)),g.appendChild($)}let P=o?.detailsDisplay??"collapsed",B=!!n.description&&!k,N=B||!!n.parameters;if(P!=="hidden"&&N){let $=Im(e.id,t),z=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");z.type="button",z.setAttribute("data-expand-header","true"),z.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=y("span");q.setAttribute("data-approval-details-label","true");let X=y("span","persona-inline-flex persona-items-center");X.setAttribute("data-approval-details-chevron","true"),z.append(q,X),Wm(z,$,t),g.appendChild(z);let A=y("div");if(A.setAttribute("data-approval-details","true"),A.style.display=$?"":"none",B){let J=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(J.style.color=o.descriptionColor),J.textContent=n.description,A.appendChild(J)}if(n.parameters){let J=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(J.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(J.style.color=o.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=Bo(n.parameters),A.appendChild(J)}g.appendChild(A)}if(r){let $=y("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let z=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");z.type="button",z.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",z.style.color=o?.approveButtonTextColor??"#ffffff",z.setAttribute("data-approval-action","approve");let q=se("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",z.appendChild(q));let X=document.createTextNode(o?.approveLabel??"Approve");z.appendChild(X);let A=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");A.type="button",A.style.backgroundColor=o?.denyButtonColor??"transparent",A.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",A.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,A.setAttribute("data-approval-action","deny");let J=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",A.appendChild(J));let Z=document.createTextNode(o?.denyLabel??"Deny");A.appendChild(Z),$.append(z,A),g.appendChild($)}return a.append(i,g),s.appendChild(a),s};function fC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Bm(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,g=e.container??fC(t),b=!1,f=null,x=()=>{if(!b)return;let k=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${k.width}px`),a&&(n.style.maxWidth=`${k.width}px`);let R=n.getBoundingClientRect(),E=i?.()??null,P=E!=null?k.top+E:k.top,B=o==="top-start"||o==="top-end"?P-r-R.height:k.bottom+r,$=o==="bottom-end"||o==="top-end"?k.right-R.width:k.left,z=a?.()??null;if(z!=null){let q=Math.max(k.left,k.right-R.width);$=Math.min(Math.max(k.left+z,k.left),q)}n.style.top=`${B}px`,n.style.left=`${$}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},S=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),g.appendChild(n),x();let k=(t.ownerDocument??document).defaultView??window,R=t.ownerDocument??document,E=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}x()},P=N=>{let $=typeof N.composedPath=="function"?N.composedPath():[];$.includes(n)||$.includes(t)||(C(),c?.("outside"))},B=k.setTimeout(()=>{R.addEventListener("pointerdown",P,!0)},0);k.addEventListener("scroll",E,!0),k.addEventListener("resize",E),f=()=>{k.clearTimeout(B),R.removeEventListener("pointerdown",P,!0),k.removeEventListener("scroll",E,!0),k.removeEventListener("resize",E)},d?.()};return{get isOpen(){return b},open:S,close:C,toggle:()=>b?C():S(),reposition:x,destroy:C}}function Dm(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var mC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Om=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Pr=(e,t)=>{Om(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},hC=e=>e?.approval!==!1?e?.approval:void 0,yC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Lr.get(e)??n==="expanded"},$d=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},bC=(e,t)=>{let n=y("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Wn)?ea(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??xl(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},vC=e=>{let t=y("div","persona-approval-resolved"),n=se("ban",15,"currentColor",2);n&&t.appendChild(n);let o=y("span","persona-approval-resolved-name");return o.textContent=e.toolName?xl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},xC=(e,t,n,o,r,s,a)=>{let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",g=d||c,b=g&&yC(t.id,o),f=o?.showDetailsLabel??"Show details",x=o?.hideDetailsLabel??"Hide details",C=y("button","persona-approval-head");C.type="button",g?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?x:f)):C.setAttribute("data-static","true");let S=y("span","persona-approval-logo"),k=se("shield-check",16,"currentColor",2);k&&S.appendChild(k),C.appendChild(S);let R=bC(n,o);if(g){let z=y("span","persona-approval-toggle");z.setAttribute("aria-hidden","true");let q=se("chevron-down",14,"currentColor",2);q&&z.appendChild(q),R.append(" "),R.appendChild(z)}C.appendChild(R),i.appendChild(C);let E=y("div","persona-approval-body");if(g){let z=y("div","persona-approval-details");if(z.setAttribute("data-role","params"),z.hidden=!b,d){let q=y("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,z.appendChild(q)}if(c){let q=y("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=Bo(n.parameters),z.appendChild(q)}E.appendChild(z)}if(n.reason){let z=y("p","persona-approval-reason");o?.reasonColor?z.style.color=o.reasonColor:o?.descriptionColor&&(z.style.color=o.descriptionColor);let q=y("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,z.append(q,document.createTextNode(n.reason)),E.appendChild(z)}let P=y("div","persona-approval-actions"),B=null,N=z=>{o?.approveButtonColor&&(z.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(z.style.color=o.approveButtonTextColor)},$=y("button","persona-approval-deny");if($.type="button",$.setAttribute("data-action","deny"),o?.denyButtonColor&&($.style.background=o.denyButtonColor),o?.denyButtonTextColor&&($.style.color=o.denyButtonTextColor),$.append(o?.denyLabel??"Deny"),a){let z=y("div","persona-approval-split"),q=y("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),N(q),q.append(o?.approveLabel??"Always allow",$d("\u23CE"));let X=y("button","persona-approval-caret");X.type="button",X.setAttribute("data-action","toggle-menu"),X.setAttribute("aria-label","More options"),N(X);let A=se("chevron-down",15,"currentColor",2);A&&X.appendChild(A),z.append(q,X),P.append(z,$),$.append($d("Esc"));let J=y("div","persona-approval-menu"),Z=y("button","persona-approval-menu-item");Z.type="button",Z.append("Allow once",$d("\u2318\u23CE")),J.appendChild(Z),B=Bm({anchor:z,content:J,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,B),Z.addEventListener("click",()=>{Pr(e,t.id),r()})}else{let z=y("button","persona-approval-primary persona-approval-primary--solo");z.type="button",z.setAttribute("data-action","allow"),N(z),z.append(o?.approveLabel??"Allow"),P.append(z,$)}return E.appendChild(P),i.appendChild(E),i.addEventListener("click",z=>{let q=z.target instanceof Element?z.target.closest("[data-action]"):null;if(!q)return;let X=q.getAttribute("data-action");if(X==="toggle-params"){let A=i.querySelector('[data-role="params"]');if(A){let J=A.hidden;A.hidden=!J,C.setAttribute("aria-expanded",J?"true":"false"),C.setAttribute("aria-label",J?x:f),Lr.set(t.id,J)}return}if(X==="toggle-menu"){B?.toggle();return}if(X==="always"){Pr(e,t.id),r({remember:!0});return}if(X==="allow"){Pr(e,t.id),r();return}if(X==="deny"){Pr(e,t.id),s();return}}),i},Nm=()=>{let e=mC();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=hC(a);if(i.status!=="pending"){if(Pr(e,o.id),i.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return vC(i)}Om(e,o.id);let d=p?.enableAlwaysAllow===!0,c=xC(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=b=>{Dm(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),Pr(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Pr(e,o);e.latestPendingApprovalId=null}}};var Ea=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 Ma=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var CC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),wC=new Set(["step_start","execution_start"]),AC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),SC=new Set(["step_complete","agent_turn_complete"]),TC=new Set(["flow_complete","agent_complete"]),Fm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$m=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),gn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Rr=(e,t)=>{let n=e[t];return $m(n)?n:void 0};function jd(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function wl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function EC(e,t){return typeof t.type=="string"?t.type:e}function MC(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 kC(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 _m(e){let t=Rr(e,"result"),n=[Rr(e,"tokens"),Rr(e,"totalTokens"),t?Rr(t,"tokens"):void 0,Rr(e,"usage"),t?Rr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=gn(o.output)??gn(o.outputTokens)??gn(o.completionTokens);if(r!==void 0)return r}return gn(e.outputTokens)??gn(e.completionTokens)??(t?gn(t.outputTokens)??gn(t.completionTokens):void 0)}function LC(e){let t=Rr(e,"result");return gn(e.executionTime)??gn(e.executionTimeMs)??gn(e.execution_time)??gn(e.duration)??(t?gn(t.executionTime)??gn(t.executionTimeMs):void 0)}function PC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ka=class{constructor(t=PC){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:wl(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(!$m(n)){Fm.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=EC(t,n),r=this.now();if(CC.has(o)){this.startRun(r);return}if(wC.has(o)){this.run||this.startRun(r);return}if(AC.has(o)){if(!kC(o,n))return;let s=MC(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+jd(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wl(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(SC.has(o)){if(!this.run)return;let s=this.run,a=_m(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+jd(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:wl(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(TC.has(o)){if(!this.run)return;let s=this.run,a=_m(n),i=a??s.exactOutputTokens+jd(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:wl(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(Fm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:LC(n)??o-t.startedAt}};function Cs(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var RC={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)"}},IC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},WC=["flowName","stepName","reasoningText","text","name","tool","toolName"],HC=100;function BC(e,t){let n={...RC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return IC}function DC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function OC(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function NC(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function FC(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 _C(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 $C(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function jC(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 UC(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,i.appendChild(p),i}}function Ud(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Cs(d,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>g(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(g()),d;function g(){let b=y("div",""),f=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=se(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&x.appendChild(C);let S=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=o.timestampFormat??"relative";S.textContent=k==="relative"?DC(e.timestamp,n):OC(e.timestamp);let R=null;o.showSequenceNumbers!==!1&&(R=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(t+1));let E=BC(e.type,o.badgeColors),P=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");P.style.backgroundColor=E.bg,P.style.color=E.text,P.style.borderColor=E.text+"50",P.textContent=e.type;let B=o.descriptionFields??WC,N=NC(e.payload,B),$=null;N&&($=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=N);let z=y("div","persona-flex-1 persona-min-w-0"),q=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"),X=se("clipboard","12px","currentColor",1.5);return X&&q.appendChild(X),q.addEventListener("click",async A=>{A.stopPropagation(),await FC(_C(e)),q.innerHTML="";let J=se("check","12px","currentColor",1.5);J&&q.appendChild(J),setTimeout(()=>{q.innerHTML="";let Z=se("clipboard","12px","currentColor",1.5);Z&&q.appendChild(Z)},1500)}),f.appendChild(x),f.appendChild(S),R&&f.appendChild(R),f.appendChild(P),$&&f.appendChild($),f.appendChild(z),f.appendChild(q),b.appendChild(f),p&&b.appendChild(UC(e,a,i)),b}}function jm(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",g=r?.features?.eventStream??{},b=s.find(x=>x.renderEventStreamView);if(b?.renderEventStreamView&&r){let x=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(x)return{element:x,update:()=>{},destroy:()=>{}}}return f();function f(){let x=g.classNames,C=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Cs(C,x?.panel);let S=[],k="",R="",E=null,P=[],B={},N=0,$=el(),z=0,q=0,X=!1,A=null,J=!1,Z=0,ce=new Set,Y=new Map,he="",te="",be=null,ee,ge,ne,me,ve=null,ye=null,De=null;function at(){let j=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),G=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(Cs(G,x?.headerBar),a){ye=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ye.style.cursor="help",ve=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"),ve.textContent="-- tok/s",De=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"),De.style.display="none",De.style.pointerEvents="none";let Tt=ye,fn=De,Na=()=>{if(!fn.textContent)return;let mn=Tt.getBoundingClientRect(),pt=j.getBoundingClientRect();fn.style.left=`${mn.left-pt.left}px`,fn.style.top=`${mn.bottom-pt.top+4}px`,fn.style.display="block"},re=()=>{fn.style.display="none"};ye.addEventListener("mouseenter",Na),ye.addEventListener("mouseleave",re),ye.appendChild(ve)}let pe=y("div","persona-flex-1");ee=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ze=y("option","");ze.value="",ze.textContent="All events (0)",ee.appendChild(ze),ge=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"),ge.type="button",ge.title="Copy All";let Re=se("clipboard-copy","12px","currentColor",1.5);Re&&ge.appendChild(Re);let qe=y("span","persona-event-copy-all persona-text-xs");qe.textContent="Copy All",ge.appendChild(qe),ye&&G.appendChild(ye),G.appendChild(pe),G.appendChild(ee),G.appendChild(ge);let Ue=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Cs(Ue,x?.searchBar);let Be=se("search","14px","var(--persona-muted, #9ca3af)",1.5),Te=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");Be&&Te.appendChild(Be),ne=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"),Cs(ne,x?.searchInput),ne.type="text",ne.placeholder="Search event payloads...",me=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"),me.type="button",me.style.display="none";let ot=se("x","12px","currentColor",2);return ot&&me.appendChild(ot),Ue.appendChild(Te),Ue.appendChild(ne),Ue.appendChild(me),j.appendChild(G),j.appendChild(Ue),De&&j.appendChild(De),j}let je,Ke=s.find(j=>j.renderEventStreamToolbar);Ke?.renderEventStreamToolbar&&r?je=Ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>at(),eventCount:t.getSize(),filteredCount:0,onFilterChange:G=>{k=G,Le(),Ee()},onSearchChange:G=>{R=G,Le(),Ee()}})??at():je=at();let Pe=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");Pe.style.display="none";function $e(){if(!a||!ve||!ye)return;let j=a(),G=$C(j);ve.textContent=G;let pe=jC(j);De&&(De.textContent=pe,pe||(De.style.display="none")),ye.setAttribute("aria-label",pe?`Throughput: ${G}, ${pe}`:`Throughput: ${G}`)}let Ae=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ie=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ie.style.height="100%";let Ie=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");Cs(Ie,x?.scrollIndicator),Ie.style.display="none",Ie.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let dt=se(d,"14px","currentColor",2);dt&&Ie.appendChild(dt);let tt=y("span","");tt.textContent=c,Ie.appendChild(tt);let xt=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");xt.style.display="none",Ae.appendChild(ie),Ae.appendChild(xt),Ae.appendChild(Ie),C.setAttribute("tabindex","0"),C.appendChild(je),C.appendChild(Pe),C.appendChild(Ae);function An(){let j=t.getAll(),G={};for(let Ue of j)G[Ue.type]=(G[Ue.type]||0)+1;let pe=Object.keys(G).sort(),ze=pe.length!==P.length||!pe.every((Ue,Be)=>Ue===P[Be]),ue=!ze&&pe.some(Ue=>G[Ue]!==B[Ue]),Re=j.length!==Object.values(B).reduce((Ue,Be)=>Ue+Be,0);if(!ze&&!ue&&!Re||(P=pe,B=G,!ee))return;let qe=ee.value;if(ee.options[0].textContent=`All events (${j.length})`,ze){for(;ee.options.length>1;)ee.remove(1);for(let Ue of pe){let Be=y("option","");Be.value=Ue,Be.textContent=`${Ue} (${G[Ue]||0})`,ee.appendChild(Be)}qe&&pe.includes(qe)?ee.value=qe:qe&&(ee.value="",k="")}else for(let Ue=1;Ue<ee.options.length;Ue++){let Be=ee.options[Ue];Be.textContent=`${Be.value} (${G[Be.value]||0})`}}function Sn(){let j=t.getAll();if(k&&(j=j.filter(G=>G.type===k)),R){let G=R.toLowerCase();j=j.filter(pe=>pe.type.toLowerCase().includes(G)||pe.payload.toLowerCase().includes(G))}return j}function et(){return k!==""||R!==""}function Le(){N=0,z=0,$.resume(),Ie.style.display="none"}function xe(j){ce.has(j)?ce.delete(j):ce.add(j),be=j;let G=ie.scrollTop,pe=$.isFollowing();J=!0,$.pause(),Ee(),ie.scrollTop=G,pe&&$.resume(),J=!1}function nt(){return po(ie,50)}function Ee(){q=Date.now(),X=!1,$e(),An();let j=t.getEvictedCount();j>0?(Pe.textContent=`${j.toLocaleString()} older events truncated`,Pe.style.display=""):Pe.style.display="none",S=Sn();let G=S.length,pe=t.getSize()>0;G===0&&pe&&et()?(xt.textContent=R?`No events matching '${R}'`:"No events matching filter",xt.style.display="",ie.style.display="none"):(xt.style.display="none",ie.style.display=""),ge&&(ge.title=et()?`Copy Filtered (${G})`:"Copy All"),p&&!$.isFollowing()&&G>N&&(z+=G-N,tt.textContent=c?`${c}${z>0?` (${z})`:""}`:"",Ie.style.display=""),N=G;let ze=t.getAll(),ue=ze.length>0?ze[0].timestamp:0,Re=new Set(S.map(Be=>Be.id));for(let Be of ce)Re.has(Be)||ce.delete(Be);let qe=k!==he||R!==te,Ue=Y.size===0&&S.length>0;if(qe||Ue||S.length===0){ie.innerHTML="",Y.clear();let Be=document.createDocumentFragment();for(let Te=0;Te<S.length;Te++){let ot=Ud(S[Te],Te,ue,g,ce,xe,s,r);Y.set(S[Te].id,ot),Be.appendChild(ot)}ie.appendChild(Be),he=k,te=R,be=null}else{if(be!==null){let Te=Y.get(be);if(Te&&Te.parentNode===ie){let ot=S.findIndex(Tt=>Tt.id===be);if(ot>=0){let Tt=Ud(S[ot],ot,ue,g,ce,xe,s,r);ie.insertBefore(Tt,Te),Te.remove(),Y.set(be,Tt)}}be=null}let Be=new Set(S.map(Te=>Te.id));for(let[Te,ot]of Y)Be.has(Te)||(ot.remove(),Y.delete(Te));for(let Te=0;Te<S.length;Te++){let ot=S[Te];if(!Y.has(ot.id)){let Tt=Ud(ot,Te,ue,g,ce,xe,s,r);Y.set(ot.id,Tt),ie.appendChild(Tt)}}}$.isFollowing()&&(ie.scrollTop=ie.scrollHeight)}function we(){if(Date.now()-q>=HC){A!==null&&(cancelAnimationFrame(A),A=null),Ee();return}X||(X=!0,A=requestAnimationFrame(()=>{A=null,Ee()}))}let ae=(j,G)=>{if(!ge)return;ge.innerHTML="";let pe=se(j,"12px","currentColor",1.5);pe&&ge.appendChild(pe);let ze=y("span","persona-text-xs");ze.textContent="Copy All",ge.appendChild(ze),setTimeout(()=>{ge.innerHTML="";let ue=se("clipboard-copy","12px","currentColor",1.5);ue&&ge.appendChild(ue);let Re=y("span","persona-text-xs");Re.textContent="Copy All",ge.appendChild(Re),ge.disabled=!1},G)},Se=async()=>{if(ge){ge.disabled=!0;try{let j;et()?j=S:n?(j=await n(),j.length===0&&(j=t.getAll())):j=t.getAll();let G=j.map(pe=>{try{return JSON.parse(pe.payload)}catch{return pe.payload}});await navigator.clipboard.writeText(JSON.stringify(G,null,2)),ae("check",1500)}catch{ae("x",1500)}}},Tn=()=>{ee&&(k=ee.value,Le(),Ee())},oe=()=>{!ne||!me||(me.style.display=ne.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{R=ne.value,Le(),Ee()},150))},M=()=>{!ne||!me||(ne.value="",R="",me.style.display="none",E&&clearTimeout(E),Le(),Ee())},W=()=>{if(J)return;let j=ie.scrollTop,{action:G,nextLastScrollTop:pe}=tl({following:$.isFollowing(),currentScrollTop:j,lastScrollTop:Z,nearBottom:nt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Z=pe,G==="resume"?($.resume(),z=0,Ie.style.display="none"):G==="pause"&&($.pause(),p&&(tt.textContent=c,Ie.style.display=""))},h=j=>{let G=nl({following:$.isFollowing(),deltaY:j.deltaY,nearBottom:nt(),resumeWhenNearBottom:!0});G==="pause"?($.pause(),p&&(tt.textContent=c,Ie.style.display="")):G==="resume"&&($.resume(),z=0,Ie.style.display="none")},H=()=>{p&&(ie.scrollTop=ie.scrollHeight,$.resume(),z=0,Ie.style.display="none")},I=j=>{let G=j.target;if(!G||G.closest("button"))return;let pe=G.closest("[data-event-id]");if(!pe)return;let ze=pe.getAttribute("data-event-id");ze&&xe(ze)},D=j=>{if((j.metaKey||j.ctrlKey)&&j.key==="f"){j.preventDefault(),ne?.focus(),ne?.select();return}j.key==="Escape"&&(ne&&document.activeElement===ne?(M(),ne.blur(),C.focus()):o&&o())};ge&&ge.addEventListener("click",Se),ee&&ee.addEventListener("change",Tn),ne&&ne.addEventListener("input",oe),me&&me.addEventListener("click",M),ie.addEventListener("scroll",W),ie.addEventListener("wheel",h,{passive:!0}),ie.addEventListener("click",I),Ie.addEventListener("click",H),C.addEventListener("keydown",D);function K(){E&&clearTimeout(E),A!==null&&(cancelAnimationFrame(A),A=null),X=!1,Y.clear(),ge&&ge.removeEventListener("click",Se),ee&&ee.removeEventListener("change",Tn),ne&&ne.removeEventListener("input",oe),me&&me.removeEventListener("click",M),ie.removeEventListener("scroll",W),ie.removeEventListener("wheel",h),ie.removeEventListener("click",I),Ie.removeEventListener("click",H),C.removeEventListener("keydown",D)}return{element:C,update:we,destroy:K}}}function Al(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},p=g=>{let b=g;return s.findIndex(f=>f===b||f.contains(b))},d=g=>{let b=p(g.target);if(b<0)return;let f=b;if(g.key===r)f=Math.min(b+1,s.length-1);else if(g.key===o)f=Math.max(b-1,0);else if(g.key==="Home")f=0;else if(g.key==="End")f=s.length-1;else return;g.preventDefault(),f!==b&&t.onSelect(f)},c=g=>{let b=p(g.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(g,b){if(s=g,g.forEach((f,x)=>{f.setAttribute("role","tab");let C=x===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&x===0?0:-1}),a){let f=(b>=0?g[b]:void 0)??g[0];f&&typeof f.focus=="function"&&(i(f),f.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function Um(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=oe=>({start:oe===!1?!1:typeof oe=="object"&&oe?oe.start!==!1:!0,end:oe===!1?!1:typeof oe=="object"&&oe?oe.end!==!1:!0}),{start:c,end:g}=d(n?.tabFade),b=typeof document<"u"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{b?.classList.add("persona-hidden"),x.classList.remove("persona-artifact-drawer-open"),J?.hide()};b&&b.addEventListener("click",()=>{f(),t.onDismiss?.()});let x=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");x.setAttribute("data-persona-theme-zone","artifact-pane"),r&&x.classList.add("persona-artifact-pane-document");let C=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let S=y("span","persona-text-xs persona-font-medium persona-truncate");S.textContent=s;let k=it({icon:"x",label:a});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let R="rendered",E=co({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:oe=>{R=oe==="source"?"source":"rendered",ae()}}),P=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),B=n?.documentToolbarShowCopyLabel===!0,N=n?.documentToolbarShowCopyChevron===!0,$=n?.documentToolbarCopyMenuItems,z=!!(N&&$&&$.length>0),q=null,X,A=null,J=null;if(r&&(B||N)&&!z){if(X=B?lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):it({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),N){let oe=se("chevron-down",14,"currentColor",2);oe&&X.appendChild(oe)}}else r&&z?(q=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),X=B?lo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):it({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),A=it({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"}}),q.append(X,A)):r?X=it({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(X=it({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&X.classList.add("persona-hidden"));let Z=r?it({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):it({icon:"refresh-cw",label:"Refresh"}),ce=r?it({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):it({icon:"x",label:a}),Y=it({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&Y.classList.add("persona-hidden");let he=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),te=e.features?.artifacts?.toolbarActions??[],be=()=>{let oe=Ae.find(H=>H.id===ie)??Ae[Ae.length-1],M=oe?.id??null,W=oe?.artifactType==="markdown"?oe.markdown??"":"",h=oe?JSON.stringify({component:oe.component,props:oe.props},null,2):"";return{markdown:W,jsonPayload:h,id:M}},ee=async()=>{let oe=Ae.find(M=>M.id===ie)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(ya(oe))}catch{}};if(X.addEventListener("click",async()=>{let oe=n?.onDocumentToolbarCopyMenuSelect;if(oe&&z){let{markdown:M,jsonPayload:W,id:h}=be();try{await oe({actionId:"primary",artifactId:h,markdown:M,jsonPayload:W})}catch{}return}await ee()}),A&&$?.length){let oe=()=>x.closest("[data-persona-root]")??document.body,M=()=>{J=zo({items:$.map(W=>({id:W.id,label:W.label})),onSelect:async W=>{let{markdown:h,jsonPayload:H,id:I}=be(),D=n?.onDocumentToolbarCopyMenuSelect;try{D?await D({actionId:W,artifactId:I,markdown:h,jsonPayload:H}):W==="markdown"||W==="md"?await navigator.clipboard.writeText(h):W==="json"||W==="source"?await navigator.clipboard.writeText(H):await navigator.clipboard.writeText(h||H)}catch{}},anchor:q??A,position:"bottom-right",portal:oe()})};x.isConnected?M():requestAnimationFrame(M),A.addEventListener("click",W=>{W.stopPropagation(),J?.toggle()})}Z.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ae()}),ce.addEventListener("click",()=>{f(),t.onDismiss?.()});let ge=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)C.replaceChildren(),q?P.append(q,Z,ce):P.append(X,Z,ce),P.insertBefore(he,ce),P.insertBefore(Y,ce),C.append(E.element,ge,P);else{let oe=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");oe.append(X,he,Y,k),C.appendChild(S),C.appendChild(oe)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let ne=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&ne.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,ve=y("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ye=Al(ne,{onSelect:oe=>t.onSelect(Ae[oe].id)}),De=oe=>{let M=oe.scrollWidth-oe.clientWidth,W=M>1,h=Math.abs(oe.scrollLeft);oe.classList.toggle("persona-artifact-tab-fade-start",c&&W&&h>1),oe.classList.toggle("persona-artifact-tab-fade-end",g&&W&&h<M-1)},at=0,je=()=>{if(at)return;let oe=()=>{at=0,De(ne)};at=typeof requestAnimationFrame=="function"?requestAnimationFrame(oe):setTimeout(oe,0)};ne.addEventListener("scroll",()=>je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>De(ne)).observe(ne);let Ke=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Pe=()=>{Ke.scrollLeft=0},$e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Pe):setTimeout(Pe,0)};if(i){for(let oe of[ne,ve])oe.style.paddingLeft=i,oe.style.paddingRight=i;Ke.style.padding=i}x.appendChild(C),x.appendChild(ne),x.appendChild(ve),x.appendChild(Ke);let Ae=[],ie=null,Ie=!1,dt=!1,tt=!0,xt=!1,An=null,Sn="",et=null,Le=!1,xe=oe=>oe.artifactType==="markdown"&&!!oe.file||r?R:"rendered",nt=oe=>{r||(oe&&!Le?(C.insertBefore(E.element,S),Le=!0):!oe&&Le&&(E.element.remove(),Le=!1))},Ee=()=>ie&&Ae.find(oe=>oe.id===ie)||Ae[Ae.length-1],we=()=>{let oe=ma(Ee());if(!oe){he.replaceChildren();return}let M=te.filter(W=>W.visible===void 0||W.visible(oe)).map(W=>fs(W,{documentChrome:r,onClick:()=>{let h=ma(Ee());if(h)try{Promise.resolve(W.onClick(h)).catch(()=>{})}catch{}}}));he.replaceChildren(...M)},ae=()=>{we();let oe=r&&Ae.length<=1,M=!!me;if(ne.classList.toggle("persona-hidden",oe||M),ve.classList.toggle("persona-hidden",oe||!M),M&&me){let H=Ae.map(I=>I.id).join("|")+" "+(ie??"");if(H!==Sn){Sn=H;let I=me({records:Ae,selectedId:ie,onSelect:t.onSelect});ve.firstElementChild!==I&&ve.replaceChildren(I)}}else{ye.beforeRender(),ne.replaceChildren();let H=[],I=-1;for(let[D,K]of Ae.entries()){let j=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");j.type="button";let G=K.artifactType==="markdown"?K.file:void 0,pe=G?jn(G.path):K.title||K.id.slice(0,8),ze=G?.path||K.title||pe;j.textContent=pe,j.title=ze,j.setAttribute("aria-label",ze),K.id===ie&&(j.classList.add("persona-bg-persona-container","persona-border-persona-border"),I=D),j.addEventListener("click",()=>t.onSelect(K.id)),ne.appendChild(j),H.push(j)}if(ye.render(H,I),I>=0&&ie!==An){An=ie;let D=H[I];typeof D.scrollIntoView=="function"&&D.scrollIntoView({block:"nearest",inline:"nearest"})}De(ne)}let W=ie&&Ae.find(H=>H.id===ie)||Ae[Ae.length-1];if(!W){Ke.replaceChildren(),et=null,nt(!1);return}let h=W.artifactType==="markdown"?W.file:void 0;if(nt(!!h&&Sr(h)!=="other"),r){let H=h?jo(h):W.artifactType==="markdown"?"MD":W.component??"Component",I=(W.title||"Document").trim(),D=h?jn(h.path):I.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${D} \xB7 ${H}`}else S.textContent=h?jn(h.path):s;et?(et.el.parentElement!==Ke&&Ke.replaceChildren(et.el),et.update(W)):(et=Qi(W,{config:e,resolveViewMode:xe}),Ke.replaceChildren(et.el)),Ke.classList.toggle("persona-artifact-content-flush",!!Ke.querySelector(".persona-code-pre"))},Se=()=>{let oe=Ae.length>0;if(x.classList.toggle("persona-hidden",!oe),b){let h=((typeof x.closest=="function"?x.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;oe&&h&&Ie?(b.classList.remove("persona-hidden"),x.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),x.classList.remove("persona-artifact-drawer-open"))}},Tn=()=>{xt=!1,ae(),Se()};return{element:x,backdrop:b,update(oe){let M=oe.selectedId??oe.artifacts[oe.artifacts.length-1]?.id??null,W=M!==ie;Ae=oe.artifacts,ie=M,Ae.length>0&&(Ie=!0),xt=!0,tt&&Tn(),W&&Pe()},setMobileOpen(oe){Ie=oe,!oe&&b?(b.classList.add("persona-hidden"),x.classList.remove("persona-artifact-drawer-open")):Se()},setExpanded(oe){oe!==dt&&(dt=oe,$e());let M=se(oe?"minimize":"maximize",16,"currentColor",2);M&&Y.replaceChildren(M);let W=oe?"Collapse artifacts panel":"Expand artifacts panel";Y.setAttribute("aria-label",W),Y.title=W},setExpandToggleVisible(oe){Y.classList.toggle("persona-hidden",!oe)},setCopyButtonVisible(oe){r||X.classList.toggle("persona-hidden",!oe)},setCustomActions(oe){te=oe,we()},setTabFade(oe){let M=d(oe);M.start===c&&M.end===g||(c=M.start,g=M.end,De(ne))},setRenderTabBar(oe){oe!==me&&(me=oe,Sn="",ae())},setVisible(oe){oe!==tt&&(tt=oe,oe&&xt&&Tn())}}}function Zt(e){return e?.features?.artifacts?.enabled===!0}function zm(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"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function zC(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 qm=["panel","seamless","detached"];function zd(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&qm.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function qd(e){return!e||!Zt(e)?!1:zd(e)==="detached"}function La(e,t){if(!Zt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),zC(e),zm(e,t);return}let n=t.features?.artifacts?.layout,o=zd(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),zm(e,t)}function Pa(e,t){for(let i of qm)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"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=zd(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function Vm(e,t){return!t||!Zt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var qC=new Set(["__proto__","prototype","constructor"]),VC=new Set(["collapsed","card","panel","inline"]),Km=new Set(["markdown","component"]),KC=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tl=e=>!qC.has(e),Vd=e=>typeof e=="string"&&VC.has(e),Wr=e=>Object.keys(e).length>0;function zn(e,t,n,o){e.push({path:t,code:n,message:o})}var GC="Ignored because this key is not part of the persisted preference schema.",Sl="Ignored an unsupported value.",JC="Expected collapsed, panel, or inline.",YC='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gm={kind:"mode",message:Sl},ws={kind:"string",message:"Expected a CSS length string."},fo={kind:"boolean"},XC={paneWidth:ws,paneMaxWidth:ws,paneMinWidth:ws,expandedPanelWidth:ws,resizableMinWidth:ws,resizableMaxWidth:ws,expandLauncherPanelWhenOpen:fo,resizable:fo},QC={kind:"object",message:"Expected a preference object.",children:{showToolCalls:fo,showReasoning:fo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:Sl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:Sl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:Sl},expandable:fo,grouped:fo}},reasoningDisplay:{kind:"object",children:{expandable:fo,activePreview:fo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gm,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gm,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Km,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Km}}},filePreview:{kind:"object",children:{enabled:fo}},layout:{kind:"object",children:XC}}}}};function Jm(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:zn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:zn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:zn(o,n,"invalid_value",t.message);case"mode":return Vd(e)?on(e):zn(o,n,"invalid_value",t.message);case"modeMap":{if(!Ir(e))return zn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[a,i]of Object.entries(e)){let p=r?a:Lo(a);Tl(a)&&(r?r.has(a):KC.test(p))?Vd(i)?s[p]=on(i):zn(o,`${n}.${a}`,"invalid_value",JC):zn(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":YC)}return Wr(s)?s:void 0}case"object":{if(t.bareMode&&Vd(e))return on(e);if(!Ir(e))return zn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=i=>n?`${n}.${i}`:i;for(let i of Object.keys(e))(!Tl(i)||!r.includes(i))&&zn(o,s(i),"unknown_key",GC);let a={};for(let i of r){let p=t.children[i],d=Jm(e[i],p,s(i),o);if(p.deprecated&&e[i]!==void 0&&zn(o,s(i),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??i,g=a[c];a[c]=Ir(g)&&Ir(d)?{...g,...d}:d}return Wr(a)?a:void 0}}}function Kd(e){let t=[];return{preferences:(e===null?void 0:Jm(e,QC,"",t))??{},issues:t}}function As(e){if(Array.isArray(e))return e.map(As);if(!Ir(e))return e;let t={};for(let[n,o]of Object.entries(e))Tl(n)&&o!==void 0&&(t[n]=As(o));return t}function Ym(e,t){let n=As(e);for(let[o,r]of Object.entries(t)){if(!Tl(o)||r===void 0)continue;let s=n[o];n[o]=Ir(s)&&Ir(r)?Ym(s,r):As(r)}return n}function ZC(e){let t={},n;for(let r of e){let s=Kd(r).preferences;n=Xm(n,s.artifacts?.display),t=Ym(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function ew(e,t){if(t===void 0)return e===void 0?void 0:As(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...Wr(r)?{byMediaType:r}:{}};return Wr(s)?s:void 0}function Xm(e,t){if(t===void 0)return e===void 0?void 0:As(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=ew(n.files,t.files),a={...o?{default:o}:{},...Wr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return Wr(a)?a:void 0}function Gd(e={},t){let n=ZC(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=Xm(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function Ra(e){let t=e.preferences;return!t||!Wr(t)?e:{...e,features:Gd(e.features??{},[t])}}function tw(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 nw(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 ow(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function rw(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function Jd(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Qm(e,t,n,o,r,s){let a=tw(r,200),i=rw(t,n,o,200);i=Math.max(a,i);let p=nw(s);return p!==null&&(i=Math.min(i,p)),ow(e,a,i)}var Zm={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Yd=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=Zm[a]??Zm.init;s.classList.add("persona-form-card","persona-space-y-4");let p=y("div","persona-space-y-1"),d=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let x=y("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,p.appendChild(x)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{let C=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${x.name}`;let S=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");S.textContent=x.label,C.appendChild(S);let k=x.type??"text",R;k==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=k),R.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",R.id=`${t.id}-${a}-${x.name}`,R.name=x.name,R.placeholder=x.placeholder??"",x.required&&(R.required=!0),C.appendChild(R),c.appendChild(C)});let g=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=i.submitLabel??"Submit",g.appendChild(b),g.appendChild(f),c.appendChild(g),s.replaceChildren(p,c),c.addEventListener("submit",async x=>{x.preventDefault();let C=n.formEndpoint??"/form",S=new FormData(c),k={};S.forEach((R,E)=>{k[E]=R}),k.type=a,f.disabled=!0,b.textContent="Submitting\u2026";try{let R=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let E=await R.json();b.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(R){b.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Xd=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Ia=new Xd;var eh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sw=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),th=(e,t,n)=>{if(!eh(e)||!eh(t)||sw.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=th(e[r],t[r],s)}return o};function El(e,t){let n=th(e,t,"");return ds(n)}var nh=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var aw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},iw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Wa=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=aw(e),n=iw(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Qd=e=>typeof e=="string"?e:e==null?"":String(e),Hr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Qd(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=Qd(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Qd(n.text)}}},oh=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ha=e=>{let t=new Set(oh(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(oh(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},g=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!g)continue;if(g.handled){let b=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:b,resubmit:g.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var lw=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}},cw=e=>e.map(t=>({...t,streaming:!1})),dw=e=>e.map(t=>({...t,status:"complete"})),Ml=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?lw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?cw(n.messages):void 0,artifacts:n.artifacts?dw(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ss=require("partial-json");function pw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function uw(e,t){if(!pw(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 kl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,Ss.parse)(n,Ss.STR|Ss.OBJ),s=uw(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function rh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ll(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Dn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function sh(){let e=kl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ah(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 Ba(e){let t=ah(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 Pl(e){let t=ah(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 gw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=gw}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let g=null,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,f.appendChild(x);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let N=1;N<=5;N++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${N} star${N>1?"s":""}: ${d[N-1]}`),$.title=d[N-1],$.dataset.rating=String(N),$.innerHTML=`
41
+ `,n.addEventListener("click",t);let o=s=>{let i=s.launcher??{},l=Ct(s),d=n.querySelector("[data-role='launcher-title']");if(d){let P=i.title??"Chat Assistant";d.textContent=P,d.setAttribute("title",P)}let u=n.querySelector("[data-role='launcher-subtitle']");if(u){let P=i.subtitle??"Here to help you get answers fast";u.textContent=P,u.setAttribute("title",P)}let p=n.querySelector(".persona-flex-col");p&&(i.textHidden||l?p.style.display="none":p.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(i.agentIconHidden)g.style.display="none";else{let P=i.agentIconSize??"40px";if(g.style.height=P,g.style.width=P,i.agentIconBackgroundColor?(g.style.backgroundColor=i.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",i.agentIconName){let A=parseFloat(P)||24,B=de(i.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);B?(g.appendChild(B),g.style.display=""):(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}else i.iconUrl?g.style.display="none":(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let P=i.agentIconSize??"40px";y.style.height=P,y.style.width=P,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let P=i.callToActionIconSize??"32px";m.style.height=P,m.style.width=P,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(m.style.color=i.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let A=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,A=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",i.callToActionIconName){let B=parseFloat(P)||24,R=Math.max(B-A,8),W=de(i.callToActionIconName,R,"currentColor",1.5);W?m.appendChild(W):m.textContent=i.callToActionIconText??"\u2197"}else m.textContent=i.callToActionIconText??"\u2197"}let b=i.position&&In[i.position]?In[i.position]:In["bottom-right"],x="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${x} ${b}`,l||(n.style.zIndex=String(i.zIndex??Xt));let H="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",_="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??H,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:_,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}},FT="teaser-dismissed",Gb=new Set,Kb=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${FT}`},$T=(e,t)=>{if(Gb.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},jT=(e,t)=>{if(Gb.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},zT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,UT=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||Ct(e??{})?null:t},Yb=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,s=null,i=null,l=null,d=null,u=!1,p=!1,g=!1,y=!1,m=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{d!==null&&(clearTimeout(d),d=null)},x=()=>{!s||!u||(u=!1,s.hidden=!0)},T=Ce=>{b(),g=!0,x(),jT(Kb(o),Ce&&m())},H=Ce=>{!r||g||T(Ce==="user"&&u)},_=()=>{d=null,!(!s||g||y)&&(p=!0,u=!0,s.hidden=!1,!(zT()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},P=()=>{!r||!s||g||p||y||$T(Kb(o),m())||(b(),d=setTimeout(_,Math.max(0,r.delayMs??0)))},A=()=>{T(m()),t()},B=Ce=>{Ce.stopPropagation(),T(m())},W=tg(e,()=>{H("user"),t()}),U=()=>{b(),l?.removeEventListener("click",A),i?.removeEventListener("click",B),s?.remove(),s=null,l=null,i=null,u=!1},V=()=>{l=ge("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),i=ge("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",B),s=ge("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,W.element)},Z=()=>{let Ce=o.launcher?.position??"bottom-right",ye=In[Ce]??In["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",W.element.style.position="";return}n.className=jn("persona-launcher-surface",ye),n.setAttribute("data-teaser",Ce),n.style.zIndex=String(o.launcher?.zIndex??Xt),W.element.style.position="static"},j=Ce=>{let ye=UT(Ce);if(r=ye,!ye){U();return}s||V(),l.textContent=ye.text,i.hidden=ye.dismissible===!1,i.setAttribute("aria-label",ye.dismissLabel??"Dismiss message"),P()},X=Ce=>{o=Ce,W.update(Ce),j(Ce),Z()},ue=(Ce,ye="user")=>{y=Ce,Ce&&H(ye)},xe=()=>{U(),W.destroy(),n.remove()};return n.appendChild(W.element),e&&(j(e),Z()),{element:n,launcher:W,get teaser(){return s?{element:s,show:_,dismiss:T}:null},setPanelOpen:ue,update:X,destroy:xe}};var Jb=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Ub(e),s=Vb(e,t),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},u={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:i,panelElements:s,transcript:l,header:d,composer:u,replaceHeader:y=>(d.element.replaceWith(y.header),d.element=y.header,d.iconHolder=y.iconHolder,d.headerTitle=y.headerTitle,d.headerSubtitle=y.headerSubtitle,d.closeButton=y.closeButton,d.closeButtonWrapper=y.closeButtonWrapper,d.clearChatButton=y.clearChatButton,d.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{u.footer.replaceWith(y),u.footer=y}}},ng=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>tg(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Yb(e,n);return{instance:r,element:r.element}};var qT=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},VT=(e,t,n)=>`${qT(e)}plugin:${t}:${n}`,Xb=e=>{let t=new Map,n=!1,o=()=>{if(n||e()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>VT(e(),r,i);return{get:i=>{let l=s(i),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return t.get(l)??null},set:(i,l)=>{let d=s(i),u=o();if(u)try{u.setItem(d,l);return}catch{n=!0}t.set(d,l)},remove:i=>{let l=s(i);t.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};var yi=new Set,KT=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),GT=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
+ `):""},Qb=(e,t)=>{let n=yi.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=de(n?"chevron-up":"chevron-down",16,"currentColor",2);u?l.appendChild(u):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},og=(e,t)=>{let n=e.reasoning,o=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&yi.has(e.id),l=n.status!=="complete",d=GT(e,r.previewMaxLines??3),u=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",s&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",m=t?.reasoning??{},b=String(n.startedAt??Date.now()),x=()=>{let xe=v("span","");return xe.setAttribute("data-tool-elapsed",b),xe.textContent=ac(n),xe},T=m.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:y,previewText:d,isActive:l,config:t??{},elapsed:ac(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(g.textContent=T,p.appendChild(g)):T instanceof HTMLElement?p.appendChild(T):(g.textContent=y,p.appendChild(g));let H=v("span","persona-text-xs persona-text-persona-primary");H.textContent=zh(n),p.appendChild(H);let _=r.loadingAnimation??"none",P=m.activeTextTemplate,A=m.completeTextTemplate,B=l?P:A,R=T instanceof HTMLElement,W=(xe,Ce)=>{g.textContent="";let ye=lc(xe,""),oe=0;for(let le of ye){let ae=le.styles.length>0?(()=>{let M=v("span",le.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return g.appendChild(M),M})():g;if(le.isDuration&&l)ae.appendChild(x());else{let M=le.isDuration?ac(n):le.text;Ce?oe=Cr(ae,M,oe):ae.appendChild(document.createTextNode(M))}}};if(!R&&B)if(H.style.display="none",g.style.display="",l&&_!=="none"){let xe=m.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),_==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),W(B,!1)):(g.classList.add(`persona-tool-loading-${_}`),g.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),_==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),W(B,!0))}else W(B,!1);else if(!R&&l&&_!=="none"){g.style.display="";let xe=m.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),_==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${xe}ms`);else{g.classList.add(`persona-tool-loading-${_}`),g.style.setProperty("--persona-tool-anim-duration",`${xe}ms`),_==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let Ce=g.textContent||y;g.textContent="",Cr(g,Ce,0)}n.status==="complete"&&(g.style.display="none")}else R||(n.status==="complete"?g.style.display="none":g.style.display="");let U=null;if(s){U=v("div","persona-flex persona-items-center");let Ce=de(i?"chevron-up":"chevron-down",16,"currentColor",2);Ce?U.appendChild(Ce):U.textContent=i?"Hide":"Show";let ye=v("div","persona-flex persona-items-center persona-ml-auto");ye.append(U),u.append(p,ye)}else u.append(p);let V=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(V.setAttribute("data-persona-collapsed-preview","reasoning"),V.style.display="none",V.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&d){let xe=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:d,isActive:l,config:t??{}});KT(V,xe)||(V.textContent=d),V.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(u,V),o;let Z=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Z.style.display=i?"":"none";let j=n.chunks.join(""),X=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return X.textContent=j||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Z.appendChild(X),(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),U){U.innerHTML="";let Ce=de(i?"chevron-up":"chevron-down",16,"currentColor",2);Ce?U.appendChild(Ce):U.textContent=i?"Hide":"Show"}Z.style.display=i?"":"none",V.style.display=i?"none":V.textContent||V.childNodes.length?"":"none"})(),o.append(u,V,Z),o};var bi=new Set,YT=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),JT=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
43
+ `);let r=gr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
+ `):""},rg=(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)"},XT=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=JT(e,o?.previewMaxLines??3),i=n?Uh(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",d=t?.toolCall??{},u=i;return r==="tool-name"?u=n.name?.trim()||i:r==="tool-preview"&&s&&(u=s),l&&d.activeTextTemplate?u=cu(n,d.activeTextTemplate,u):!l&&d.completeTextTemplate&&(u=cu(n,d.completeTextTemplate,u)),{summary:u,previewText:s,isActive:l}},Zb=(e,t,n)=>{let o=bi.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(u){u.innerHTML="";let p=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=de(o?"chevron-up":"chevron-down",16,p,2);g?u.appendChild(g):u.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},sg=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=t?.features?.toolCallDisplay??{},i=s.expandable!==!1,l=i&&bi.has(e.id),{summary:d,previewText:u,isActive:p}=XT(e,t),g=v("button",i?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",i&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let y=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let b=String(n.startedAt??Date.now()),x=()=>{let j=v("span","");return j.setAttribute("data-tool-elapsed",b),j.textContent=ha(n),j},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:d,previewText:u,collapsedMode:s.collapsedMode??"tool-call",isActive:p,config:t??{},elapsed:ha(n),createElapsedElement:x});typeof T=="string"&&T.trim()?(m.textContent=T,y.appendChild(m)):T instanceof HTMLElement?y.appendChild(T):(m.textContent=d,y.appendChild(m));let H=s.loadingAnimation??"none",_=o.activeTextTemplate,P=o.completeTextTemplate,A=p?_:P,B=T instanceof HTMLElement,R=(j,X)=>{m.textContent="";let ue=n.name?.trim()||"tool",xe=lc(j,ue),Ce=0;for(let ye of xe){let oe=ye.styles.length>0?(()=>{let le=v("span",ye.styles.map(ae=>`persona-tool-text-${ae}`).join(" "));return m.appendChild(le),le})():m;if(ye.isDuration&&p)oe.appendChild(x());else{let le=ye.isDuration?ha(n):ye.text;X?Ce=Cr(oe,le,Ce):oe.appendChild(document.createTextNode(le))}}};if(!B)if(p&&H!=="none"){let j=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),H==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${j}ms`),A&&R(A,!1);else if(m.classList.add(`persona-tool-loading-${H}`),m.style.setProperty("--persona-tool-anim-duration",`${j}ms`),H==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)R(A,!0);else{let X=m.textContent||d;m.textContent="",Cr(m,X,0)}}else A&&R(A,!1);let W=null;if(i){W=v("div","persona-flex persona-items-center");let j=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=de(l?"chevron-up":"chevron-down",16,j,2);X?W.appendChild(X):W.textContent=l?"Hide":"Show";let ue=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ue.append(W),g.append(y,ue)}else g.append(y);let U=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!l&&p&&s.activePreview&&u){let j=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:u,isActive:p,config:t??{}});YT(U,j)||(U.textContent=u),U.style.display=""}if(!l&&p&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(g,U),r;let V=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(V.style.display=l?"":"none",o.contentBackgroundColor&&(V.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(V.style.color=o.contentTextColor),o.contentPaddingX&&(V.style.paddingLeft=o.contentPaddingX,V.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(V.style.paddingTop=o.contentPaddingY,V.style.paddingBottom=o.contentPaddingY),n.name){let j=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?j.style.color=o.contentTextColor:o.headerTextColor&&(j.style.color=o.headerTextColor),j.textContent=n.name,V.appendChild(j)}if(n.args!==void 0){let j=v("div","persona-space-y-1"),X=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Arguments";let ue=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",rg(ue,o),ue.textContent=gr(n.args),j.append(X,ue),V.appendChild(j)}if(n.chunks&&n.chunks.length){let j=v("div","persona-space-y-1"),X=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Activity";let ue=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",rg(ue,o),ue.textContent=n.chunks.join(""),j.append(X,ue),V.appendChild(j)}if(n.status==="complete"&&n.result!==void 0){let j=v("div","persona-space-y-1"),X=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(X.style.color=o.labelTextColor),X.textContent="Result";let ue=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ue.style.fontSize="0.75rem",ue.style.lineHeight="1rem",rg(ue,o),ue.textContent=gr(n.result),j.append(X,ue),V.appendChild(j)}if(n.status==="complete"&&typeof n.duration=="number"){let j=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(j.style.color=o.contentTextColor),j.textContent=`Duration: ${n.duration}ms`,V.appendChild(j)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),W){W.innerHTML="";let j=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",X=de(l?"chevron-up":"chevron-down",16,j,2);X?W.appendChild(X):W.textContent=l?"Hide":"Show"}V.style.display=l?"":"none",U.style.display=l?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(g,U,V),r};var gs=new Map,rd=e=>{let n=(e.startsWith(Zn)?e.slice(Zn.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)},ev=e=>e?.approval!==!1?e?.approval:void 0,tv=(e,t)=>{let n=ev(t)?.detailsDisplay??"collapsed";return gs.get(e)??n==="expanded"},nv=(e,t,n)=>{let o=ev(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=de(t?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},ov=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=tv(e,n);nv(o,s,n),r.style.display=s?"":"none"};var sd=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",u=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",p=de(d,20,u,2);p&&l.appendChild(p);let g=v("div","persona-flex-1 persona-min-w-0"),y=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(m.style.color=o.titleColor),m.textContent=o?.title??"Approval Required",y.appendChild(m),!r){let W=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");W.setAttribute("data-approval-status",n.status),n.status==="approved"?(W.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",W.style.color="var(--persona-palette-colors-success-700, #15803d)",W.textContent="Approved"):n.status==="denied"?(W.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",W.style.color="var(--persona-palette-colors-error-700, #b91c1c)",W.textContent="Denied"):n.status==="timeout"&&(W.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",W.style.color="var(--persona-palette-colors-warning-700, #b45309)",W.textContent="Timeout"),y.appendChild(W)}g.appendChild(y);let x=n.toolType==="webmcp"||n.toolName.startsWith(Zn)?da(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),H=!n.toolName,_=T||(H?n.description:`The assistant wants to use \u201C${x??rd(n.toolName)}\u201D.`),P=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(P.style.color=o.descriptionColor),P.textContent=_,g.appendChild(P),n.reason){let W=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");W.setAttribute("data-approval-reason","true"),o?.reasonColor?W.style.color=o.reasonColor:o?.descriptionColor&&(W.style.color=o.descriptionColor);let U=v("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,W.appendChild(U),W.appendChild(document.createTextNode(n.reason)),g.appendChild(W)}let A=o?.detailsDisplay??"collapsed",B=!!n.description&&!H,R=B||!!n.parameters;if(A!=="hidden"&&R){let W=tv(e.id,t),U=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let V=v("span");V.setAttribute("data-approval-details-label","true");let Z=v("span","persona-inline-flex persona-items-center");Z.setAttribute("data-approval-details-chevron","true"),U.append(V,Z),nv(U,W,t),g.appendChild(U);let j=v("div");if(j.setAttribute("data-approval-details","true"),j.style.display=W?"":"none",B){let X=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(X.style.color=o.descriptionColor),X.textContent=n.description,j.appendChild(X)}if(n.parameters){let X=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(X.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(X.style.color=o.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=gr(n.parameters),j.appendChild(X)}g.appendChild(j)}if(r){let W=v("div","persona-flex persona-gap-2 persona-mt-2");W.setAttribute("data-approval-buttons","true");let U=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let V=de("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);V&&(V.style.marginRight="4px",U.appendChild(V));let Z=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(Z);let j=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");j.type="button",j.style.backgroundColor=o?.denyButtonColor??"transparent",j.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",j.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,j.setAttribute("data-approval-action","deny");let X=de("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",j.appendChild(X));let ue=document.createTextNode(o?.denyLabel??"Deny");j.appendChild(ue),W.append(U,j),g.appendChild(W)}return i.append(l,g),s.appendChild(i),s};function QT(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function rv(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:d=2147483e3,onOpen:u,onDismiss:p}=e,g=e.container??QT(t),y=!1,m=null,b=()=>{if(!y)return;let H=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${H.width}px`),i&&(n.style.maxWidth=`${H.width}px`);let _=n.getBoundingClientRect(),P=l?.()??null,A=P!=null?H.top+P:H.top,B=o==="top-start"||o==="top-end"?A-r-_.height:H.bottom+r,W=o==="bottom-end"||o==="top-end"?H.right-_.width:H.left,U=i?.()??null;if(U!=null){let V=Math.max(H.left,H.right-_.width);W=Math.min(Math.max(H.left+U,H.left),V)}n.style.top=`${B}px`,n.style.left=`${W}px`},x=()=>{y&&(y=!1,m&&(m(),m=null),n.remove())},T=()=>{if(y)return;y=!0,d!=null&&(n.style.zIndex=String(d)),g.appendChild(n),b();let H=(t.ownerDocument??document).defaultView??window,_=t.ownerDocument??document,P=()=>{if(!t.isConnected){x(),p?.("anchor-removed");return}b()},A=R=>{let W=typeof R.composedPath=="function"?R.composedPath():[];W.includes(n)||W.includes(t)||(x(),p?.("outside"))},B=H.setTimeout(()=>{_.addEventListener("pointerdown",A,!0)},0);H.addEventListener("scroll",P,!0),H.addEventListener("resize",P),m=()=>{H.clearTimeout(B),_.removeEventListener("pointerdown",A,!0),H.removeEventListener("scroll",P,!0),H.removeEventListener("resize",P)},u?.()};return{get isOpen(){return y},open:T,close:x,toggle:()=>y?x():T(),reposition:b,destroy:x}}function sv(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var ZT=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),iv=(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))},fs=(e,t)=>{iv(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)},eE=e=>e?.approval!==!1?e?.approval:void 0,tE=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return gs.get(e)??n==="expanded"},ig=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},nE=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Zn)?da(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let i=r??rd(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=i,n.appendChild(d),l){n.append(" from ");let u=document.createElement("strong");u.textContent=l,n.appendChild(u)}return n},oE=e=>{let t=v("div","persona-approval-resolved"),n=de("ban",15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?rd(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},rE=(e,t,n,o,r,s,i)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${t.id}`,l.setAttribute("data-message-id",t.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",u=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",g=u||p,y=g&&tE(t.id,o),m=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",x=v("button","persona-approval-head");x.type="button",g?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",y?"true":"false"),x.setAttribute("aria-label",y?b:m)):x.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),H=de("shield-check",16,"currentColor",2);H&&T.appendChild(H),x.appendChild(T);let _=nE(n,o);if(g){let U=v("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let V=de("chevron-down",14,"currentColor",2);V&&U.appendChild(V),_.append(" "),_.appendChild(U)}x.appendChild(_),l.appendChild(x);let P=v("div","persona-approval-body");if(g){let U=v("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!y,u){let V=v("p","persona-approval-desc");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,U.appendChild(V)}if(p){let V=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(V.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.textContent=gr(n.parameters),U.appendChild(V)}P.appendChild(U)}if(n.reason){let U=v("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let V=v("span","persona-approval-reason-label");V.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(V,document.createTextNode(n.reason)),P.appendChild(U)}let A=v("div","persona-approval-actions"),B=null,R=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},W=v("button","persona-approval-deny");if(W.type="button",W.setAttribute("data-action","deny"),o?.denyButtonColor&&(W.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(W.style.color=o.denyButtonTextColor),W.append(o?.denyLabel??"Deny"),i){let U=v("div","persona-approval-split"),V=v("button","persona-approval-primary");V.type="button",V.setAttribute("data-action","always"),R(V),V.append(o?.approveLabel??"Always allow",ig("\u23CE"));let Z=v("button","persona-approval-caret");Z.type="button",Z.setAttribute("data-action","toggle-menu"),Z.setAttribute("aria-label","More options"),R(Z);let j=de("chevron-down",15,"currentColor",2);j&&Z.appendChild(j),U.append(V,Z),A.append(U,W),W.append(ig("Esc"));let X=v("div","persona-approval-menu"),ue=v("button","persona-approval-menu-item");ue.type="button",ue.append("Allow once",ig("\u2318\u23CE")),X.appendChild(ue),B=rv({anchor:U,content:X,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,B),ue.addEventListener("click",()=>{fs(e,t.id),r()})}else{let U=v("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),R(U),U.append(o?.approveLabel??"Allow"),A.append(U,W)}return P.appendChild(A),l.appendChild(P),l.addEventListener("click",U=>{let V=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!V)return;let Z=V.getAttribute("data-action");if(Z==="toggle-params"){let j=l.querySelector('[data-role="params"]');if(j){let X=j.hidden;j.hidden=!X,x.setAttribute("aria-expanded",X?"true":"false"),x.setAttribute("aria-label",X?b:m),gs.set(t.id,X)}return}if(Z==="toggle-menu"){B?.toggle();return}if(Z==="always"){fs(e,t.id),r({remember:!0});return}if(Z==="allow"){fs(e,t.id),r();return}if(Z==="deny"){fs(e,t.id),s();return}}),l},av=()=>{let e=ZT();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let d=eE(i);if(l.status!=="pending"){if(fs(e,o.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return oE(l)}iv(e,o.id);let u=d?.enableAlwaysAllow===!0,p=rE(e,o,l,d,r,s,u);if(u){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let g=y=>{sv(y)||o.id===e.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),fs(e,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])fs(e,o);e.latestPendingApprovalId=null}}};var Fa=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 $a=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var sE=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),iE=new Set(["step_start","execution_start"]),aE=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),lE=new Set(["step_complete","agent_turn_complete"]),cE=new Set(["flow_complete","agent_complete"]),lv=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),dv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ms=(e,t)=>{let n=e[t];return dv(n)?n:void 0};function ag(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function id(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function dE(e,t){return typeof t.type=="string"?t.type:e}function pE(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 uE(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 cv(e){let t=ms(e,"result"),n=[ms(e,"tokens"),ms(e,"totalTokens"),t?ms(t,"tokens"):void 0,ms(e,"usage"),t?ms(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=Rn(o.output)??Rn(o.outputTokens)??Rn(o.completionTokens);if(r!==void 0)return r}return Rn(e.outputTokens)??Rn(e.completionTokens)??(t?Rn(t.outputTokens)??Rn(t.completionTokens):void 0)}function gE(e){let t=ms(e,"result");return Rn(e.executionTime)??Rn(e.executionTimeMs)??Rn(e.execution_time)??Rn(e.duration)??(t?Rn(t.executionTime)??Rn(t.executionTimeMs):void 0)}function fE(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ja=class{constructor(t=fE){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:id(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(!dv(n)){lv.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=dE(t,n),r=this.now();if(sE.has(o)){this.startRun(r);return}if(iE.has(o)){this.run||this.startRun(r);return}if(aE.has(o)){if(!uE(o,n))return;let s=pE(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+ag(i.visibleCharCount),d=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:id(l,d),outputTokens:l,durationMs:d,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(lE.has(o)){if(!this.run)return;let s=this.run,i=cv(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+ag(s.visibleCharCount),u=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:id(d,u),outputTokens:d,durationMs:u,source:l?"usage":"estimate"};return}if(cE.has(o)){if(!this.run)return;let s=this.run,i=cv(n),l=i??s.exactOutputTokens+ag(s.visibleCharCount),d=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:id(l,u),outputTokens:l,durationMs:u,source:d},this.run=null;return}if(lv.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:gE(n)??o-t.startedAt}};var{setLoader:fI,load:mE}=lo({fallbackImport:()=>import("@runtypelabs/persona/event-stream-view")});var pv=mE;function ad(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},d=g=>{let y=g;return s.findIndex(m=>m===y||m.contains(y))},u=g=>{let y=d(g.target);if(y<0)return;let m=y;if(g.key===r)m=Math.min(y+1,s.length-1);else if(g.key===o)m=Math.max(y-1,0);else if(g.key==="Home")m=0;else if(g.key==="End")m=s.length-1;else return;g.preventDefault(),m!==y&&t.onSelect(m)},p=g=>{let y=d(g.target);y>=0&&l(s[y])};return e.addEventListener("keydown",u),e.addEventListener("focusin",p),{beforeRender(){i=typeof document<"u"&&e.contains(document.activeElement)},render(g,y){if(s=g,g.forEach((m,b)=>{m.setAttribute("role","tab");let x=b===y;m.setAttribute("aria-selected",x?"true":"false"),m.tabIndex=x||y<0&&b===0?0:-1}),i){let m=(y>=0?g[y]:void 0)??g[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){e.removeEventListener("keydown",u),e.removeEventListener("focusin",p)}}}function uv(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),u=S=>({start:S===!1?!1:typeof S=="object"&&S?S.start!==!1:!0,end:S===!1?!1:typeof S=="object"&&S?S.end!==!1:!0}),{start:p,end:g}=u(n?.tabFade),y=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{y?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),j?.closeMenu()};y&&y.addEventListener("click",()=>{m(),t.onDismiss?.()});let b=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");b.setAttribute("data-persona-theme-zone","artifact-pane"),r&&b.classList.add("persona-artifact-pane-document");let x=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");x.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&x.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let H=rt({icon:"x",label:i});H.addEventListener("click",()=>{m(),t.onDismiss?.()});let _="rendered",P=$o({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:S=>{_=S==="source"?"source":"rendered",F()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),B=n?.documentToolbarShowCopyLabel===!0,R=n?.documentToolbarShowCopyChevron===!0,W=n?.documentToolbarCopyMenuItems,U=!!(R&&W&&W.length>0),V=null,Z,j=null;if(r&&(B||R)&&!U){if(Z=B?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let S=de("chevron-down",14,"currentColor",2);S&&Z.appendChild(S)}}else r&&U?(j=Oc({label:"Copy",icon:"copy",iconSize:14,iconOnly:!B,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(W??[]).map(S=>({id:S.id,label:S.label})),position:"bottom-right",portal:()=>b.closest("[data-persona-root]")??document.body,onSelect:S=>{we(S)}}),V=j.element,Z=j.primaryButton):r?Z=rt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Z=rt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Z.classList.add("persona-hidden"));let X=r?rt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):rt({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||X.classList.add("persona-hidden");let ue=r?rt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):rt({icon:"x",label:i}),xe=rt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&xe.classList.add("persona-hidden");let Ce=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ye=e.features?.artifacts?.toolbarActions??[],oe=()=>{let S=Ae.find(K=>K.id===Fe)??Ae[Ae.length-1],I=S?.id??null,L=S?.artifactType==="markdown"?S.markdown??"":"",O=S?JSON.stringify({component:S.component,props:S.props},null,2):"",{filename:Y,mime:Q,content:G}=Ic({title:S?.title,markdown:S?.markdown??"",file:S?.file});return{markdown:L,jsonPayload:O,id:I,file:S?.file,suggestedFilename:Y,mime:Q,content:G}},le=()=>{let{suggestedFilename:S,mime:I,content:L}=oe();L&&Rc({filename:S,mime:I,content:L})},ae=S=>{let{id:I,...L}=oe();return{actionId:S,artifactId:I,...L}},M=async()=>{let S=Ae.find(I=>I.id===Fe)??Ae[Ae.length-1];try{return await navigator.clipboard.writeText(Ha(S)),!0}catch{return!1}},ee=null,pe=()=>{ee?.();let S=Z.querySelector("svg"),I=Number(S?.getAttribute("width"))||16,L=de("check",I,"currentColor",2);if(!S||!L)return;S.replaceWith(L);let O=Z.querySelector("span");O&&(O.textContent="Copied");let Y=setTimeout(()=>ee?.(),2e3);ee=()=>{clearTimeout(Y),L.replaceWith(S),O&&(O.textContent="Copy"),ee=null}};Z.addEventListener("click",async()=>{let S=n?.onDocumentToolbarCopyMenuSelect;if(S&&U){try{if(await S(ae("primary"))===!1){await M()&&pe();return}pe()}catch{}return}await M()&&pe()});async function we(S){let I=n?.onDocumentToolbarCopyMenuSelect;try{if(I&&await I(ae(S))!==!1)return;if(S==="download"){le();return}let{markdown:L,jsonPayload:O}=oe();S==="markdown"||S==="md"?await navigator.clipboard.writeText(L):S==="json"||S==="source"?await navigator.clipboard.writeText(O):await navigator.clipboard.writeText(L||O),pe()}catch{}}X.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}F()}),ue.addEventListener("click",()=>{m(),t.onDismiss?.()});let me=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)x.replaceChildren(),V?A.append(V,X,ue):A.append(Z,X,ue),A.insertBefore(Ce,ue),A.insertBefore(xe,ue),x.append(P.element,me,A);else{let S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");S.append(Z,Ce,xe,H),x.appendChild(T),x.appendChild(S)}l&&(x.style.paddingLeft=l,x.style.paddingRight=l);let Se=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");d&&Se.style.setProperty("--persona-artifact-tab-fade-size",d);let Le=e.features?.artifacts?.renderTabBar,He=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Qe=ad(Se,{onSelect:S=>t.onSelect(Ae[S].id)}),Oe=S=>{let I=S.scrollWidth-S.clientWidth,L=I>1,O=Math.abs(S.scrollLeft);S.classList.toggle("persona-artifact-tab-fade-start",p&&L&&O>1),S.classList.toggle("persona-artifact-tab-fade-end",g&&L&&O<I-1)},We=0,tt=()=>{if(We)return;let S=()=>{We=0,Oe(Se)};We=typeof requestAnimationFrame=="function"?requestAnimationFrame(S):setTimeout(S,0)};Se.addEventListener("scroll",()=>tt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Oe(Se)).observe(Se);let ve=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ne=()=>{ve.scrollLeft=0},ft=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ne):setTimeout(Ne,0)};if(l){for(let S of[Se,He])S.style.paddingLeft=l,S.style.paddingRight=l;ve.style.padding=l}b.appendChild(x),b.appendChild(Se),b.appendChild(He),b.appendChild(ve);let Ae=[],Fe=null,at=!1,Gt=!1,Ut=!0,Vn=!1,et=null,nt="",wt=null,Zt=!1,vo=S=>S.artifactType==="markdown"&&!!S.file||r?_:"rendered",Rt=S=>{r||(S&&!Zt?(x.insertBefore(P.element,T),Zt=!0):!S&&Zt&&(P.element.remove(),Zt=!1))},Ko=()=>Fe&&Ae.find(S=>S.id===Fe)||Ae[Ae.length-1],vs=()=>{let S=Pa(Ko());if(!S){Ce.replaceChildren();return}let I=ye.filter(L=>L.visible===void 0||L.visible(S)).map(L=>di(L,{documentChrome:r,onClick:()=>{let O=Pa(Ko());if(O)try{Promise.resolve(L.onClick(O)).catch(()=>{})}catch{}}}));Ce.replaceChildren(...I)},F=()=>{vs();let S=r&&Ae.length<=1,I=!!Le;if(Se.classList.toggle("persona-hidden",S||I),He.classList.toggle("persona-hidden",S||!I),I&&Le){let Y=Ae.map(Q=>Q.id).join("|")+" "+(Fe??"");if(Y!==nt){nt=Y;let Q=Le({records:Ae,selectedId:Fe,onSelect:t.onSelect});He.firstElementChild!==Q&&He.replaceChildren(Q)}}else{Qe.beforeRender(),Se.replaceChildren();let Y=[],Q=-1;for(let[G,K]of Ae.entries()){let ce=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ce.type="button";let dt=K.artifactType==="markdown"?K.file:void 0,st=dt?mo(dt.path):K.title||K.id.slice(0,8),xt=dt?.path||K.title||st;ce.textContent=st,ce.title=xt,ce.setAttribute("aria-label",xt),K.id===Fe&&(ce.classList.add("persona-bg-persona-container","persona-border-persona-border"),Q=G),ce.addEventListener("click",()=>t.onSelect(K.id)),Se.appendChild(ce),Y.push(ce)}if(Qe.render(Y,Q),Q>=0&&Fe!==et){et=Fe;let G=Y[Q];typeof G.scrollIntoView=="function"&&G.scrollIntoView({block:"nearest",inline:"nearest"})}Oe(Se)}let L=Fe&&Ae.find(Y=>Y.id===Fe)||Ae[Ae.length-1];if(!L){ve.replaceChildren(),wt?.destroy(),wt=null,Rt(!1);return}let O=L.artifactType==="markdown"?L.file:void 0;if(Rt(!!O&&ss(O)!=="other"),r){let Y=O?vr(O):L.artifactType==="markdown"?"MD":L.component??"Component",Q=(L.title||"Document").trim(),G=O?mo(O.path):Q.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";me.textContent=`${G} \xB7 ${Y}`}else T.textContent=O?mo(O.path):s;wt?(wt.el.parentElement!==ve&&ve.replaceChildren(wt.el),wt.update(L)):(wt=Fc(L,{config:e,resolveViewMode:vo}),ve.replaceChildren(wt.el)),ve.classList.toggle("persona-artifact-content-flush",!!ve.querySelector(".persona-code-pre"))},te=()=>{let S=Ae.length>0;if(b.classList.toggle("persona-hidden",!S),y){let O=((typeof b.closest=="function"?b.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;S&&O&&at?(y.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},w=()=>{Vn=!1,F(),te()};return{element:b,backdrop:y,update(S){let I=S.selectedId??S.artifacts[S.artifacts.length-1]?.id??null,L=I!==Fe;Ae=S.artifacts,Fe=I,Ae.length>0&&(at=!0),Vn=!0,Ut&&w(),L&&Ne()},setMobileOpen(S){at=S,!S&&y?(y.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):te()},setExpanded(S){S!==Gt&&(Gt=S,ft());let I=de(S?"minimize":"maximize",16,"currentColor",2);I&&xe.replaceChildren(I);let L=S?"Collapse artifacts panel":"Expand artifacts panel";xe.setAttribute("aria-label",L),xe.title=L},setExpandToggleVisible(S){xe.classList.toggle("persona-hidden",!S)},setCopyButtonVisible(S){r||Z.classList.toggle("persona-hidden",!S)},setRefreshButtonVisible(S){X.classList.toggle("persona-hidden",!S)},setCustomActions(S){ye=S,vs()},setTabFade(S){let I=u(S);I.start===p&&I.end===g||(p=I.start,g=I.end,Oe(Se))},setRenderTabBar(S){S!==Le&&(Le=S,nt="",F())},setVisible(S){S!==Ut&&(Ut=S,S&&Vn&&w())},destroy(){wt?.destroy(),wt=null}}}function gn(e){return e?.features?.artifacts?.enabled===!0}function gv(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"),!gn(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function hE(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 fv=["panel","seamless","detached"];function lg(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&fv.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function cg(e){return!e||!gn(e)?!1:lg(e)==="detached"}function za(e,t){if(!gn(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-drawer-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),hE(e),gv(e,t);return}let n=t.features?.artifacts?.layout,o=lg(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?e.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):e.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let i=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of i){let u=l?.trim();u?e.style.setProperty(d,u):e.style.removeProperty(d)}gv(e,t)}function Ua(e,t){for(let l of fv)e.classList.remove(`persona-artifact-appearance-${l}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!gn(t))return;let n=t.features?.artifacts?.layout,o=lg(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&e.style.setProperty("--persona-artifact-chat-shadow",i)}function mv(e,t){return!t||!gn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var yE=new Set(["__proto__","prototype","constructor"]),bE=new Set(["collapsed","card","panel","inline"]),hv=new Set(["markdown","component"]),vE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,hs=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cd=e=>!yE.has(e),dg=e=>typeof e=="string"&&bE.has(e),ys=e=>Object.keys(e).length>0;function yo(e,t,n,o){e.push({path:t,code:n,message:o})}var CE="Ignored because this key is not part of the persisted preference schema.",ld="Ignored an unsupported value.",wE="Expected collapsed, panel, or inline.",xE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',yv={kind:"mode",message:ld},vi={kind:"string",message:"Expected a CSS length string."},Uo={kind:"boolean"},SE={paneWidth:vi,paneMaxWidth:vi,paneMinWidth:vi,expandedPanelWidth:vi,resizableMinWidth:vi,resizableMaxWidth:vi,expandLauncherPanelWhenOpen:Uo,resizable:Uo},AE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Uo,showReasoning:Uo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:ld},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:ld},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:ld},expandable:Uo,grouped:Uo}},reasoningDisplay:{kind:"object",children:{expandable:Uo,activePreview:Uo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:yv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:yv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:hv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:hv}}},filePreview:{kind:"object",children:{enabled:Uo}},layout:{kind:"object",children:SE}}}}};function bv(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:yo(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:yo(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:yo(o,n,"invalid_value",t.message);case"mode":return dg(e)?Cn(e):yo(o,n,"invalid_value",t.message);case"modeMap":{if(!hs(e))return yo(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,s={};for(let[i,l]of Object.entries(e)){let d=r?i:ar(i);cd(i)&&(r?r.has(i):vE.test(d))?dg(l)?s[d]=Cn(l):yo(o,`${n}.${i}`,"invalid_value",wE):yo(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":xE)}return ys(s)?s:void 0}case"object":{if(t.bareMode&&dg(e))return Cn(e);if(!hs(e))return yo(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!cd(l)||!r.includes(l))&&yo(o,s(l),"unknown_key",CE);let i={};for(let l of r){let d=t.children[l],u=bv(e[l],d,s(l),o);if(d.deprecated&&e[l]!==void 0&&yo(o,s(l),"deprecated_key",d.deprecated),u===void 0)continue;let p=d.alias??l,g=i[p];i[p]=hs(g)&&hs(u)?{...g,...u}:u}return ys(i)?i:void 0}}}function pg(e){let t=[];return{preferences:(e===null?void 0:bv(e,AE,"",t))??{},issues:t}}function Ci(e){if(Array.isArray(e))return e.map(Ci);if(!hs(e))return e;let t={};for(let[n,o]of Object.entries(e))cd(n)&&o!==void 0&&(t[n]=Ci(o));return t}function vv(e,t){let n=Ci(e);for(let[o,r]of Object.entries(t)){if(!cd(o)||r===void 0)continue;let s=n[o];n[o]=hs(s)&&hs(r)?vv(s,r):Ci(r)}return n}function TE(e){let t={},n;for(let r of e){let s=pg(r).preferences;n=Cv(n,s.artifacts?.display),t=vv(t,s)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function EE(e,t){if(t===void 0)return e===void 0?void 0:Ci(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byMediaType,...t.byMediaType},s={...o?{default:o}:{},...ys(r)?{byMediaType:r}:{}};return ys(s)?s:void 0}function Cv(e,t){if(t===void 0)return e===void 0?void 0:Ci(e);if(typeof t=="string")return t;let n=typeof e=="string"?{default:e}:e??{},o=t.default??n.default,r={...n.byType,...n.byKind,...t.byType,...t.byKind},s=EE(n.files,t.files),i={...o?{default:o}:{},...ys(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return ys(i)?i:void 0}function ug(e={},t){let n=TE(t),o={...e};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...e.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...e.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=e.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=Cv(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function qa(e){let t=e.preferences;return!t||!ys(t)?e:{...e,features:ug(e.features??{},[t])}}function ME(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 kE(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 PE(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function LE(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function gg(e,t){let o=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function wv(e,t,n,o,r,s,i=200){let l=ME(r,200),d=LE(t,n,o,i);d=Math.max(l,d);let u=kE(s);return u!==null&&(d=Math.min(d,u)),PE(e,l,d)}var xv={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"}},fg=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=xv[i]??xv.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),u=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(u.textContent=l.title,d.appendChild(u),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,d.appendChild(b)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let x=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");x.htmlFor=`${t.id}-${i}-${b.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,x.appendChild(T);let H=b.type??"text",_;H==="textarea"?(_=document.createElement("textarea"),_.rows=3):(_=document.createElement("input"),_.type=H),_.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",_.id=`${t.id}-${i}-${b.name}`,_.name=b.name,_.placeholder=b.placeholder??"",b.required&&(_.required=!0),x.appendChild(_),p.appendChild(x)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=l.submitLabel??"Submit",g.appendChild(y),g.appendChild(m),p.appendChild(g),s.replaceChildren(d,p),p.addEventListener("submit",async b=>{b.preventDefault();let x=n.formEndpoint??"/form",T=new FormData(p),H={};T.forEach((_,P)=>{H[P]=_}),H.type=i,m.disabled=!0,y.textContent="Submitting\u2026";try{let _=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)});if(!_.ok)throw new Error(`Form submission failed (${_.status})`);let P=await _.json();y.textContent=P.message??"Thanks! We'll be in touch soon.",P.success&&P.nextPrompt&&await o.sendMessage(String(P.nextPrompt))}catch(_){y.textContent=_ instanceof Error?_.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mg=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Va=new mg;var Sv=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),HE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),Av=(e,t,n)=>{if(!Sv(e)||!Sv(t)||HE.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Av(e[r],t[r],s)}return o};function dd(e,t){let n=Av(e,t,"");return ii(n)}var Tv=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var IE=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},RE=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Ka=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=IE(e),n=RE(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},hg=e=>typeof e=="string"?e:e==null?"":String(e),bs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:hg(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=hg(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:hg(n.text)}}},Ev=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ga=e=>{let t=new Set(Ev(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ev(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?e.parsers.reduce((u,p)=>u||p?.({text:i,message:s.message})||null,null):null;if(!l)return null;t.add(s.message.id),o();let d={action:l,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let p=()=>{e.emit("action:resubmit",d)},g=u(l,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!g)continue;if(g.handled){let y=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:y,resubmit:g.resubmit}}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var WE=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}},BE=e=>e.map(t=>({...t,streaming:!1})),OE=e=>e.map(t=>({...t,status:"complete"})),pd=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?WE(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?BE(n.messages):void 0,artifacts:n.artifacts?OE(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var DE=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")},Mv=async e=>{let t=globalThis.crypto?.subtle;if(t)try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return DE(e)},_E=async(e,t)=>{let n=await Mv(e);return{storageKey:`${t}visitor:${n}`,leaseKey:`${t}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await Mv(`${e}\0${t}`)}`}};var kv=(e,t,n)=>{let o="",r="",s="",i=!1,l=!1,d=0,u=null,p=null,g=new Set,y=()=>{if(n||i)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return i=!0,null}},m=()=>{let R=y();if(!R)return u;try{return R.getItem(o)}catch{return i=!0,u}},b=(R,W)=>{if(l||R===u)return;let U=u;u=R,d+=1;let V={previousToken:U,token:R,source:W,revision:d};for(let Z of g)Z(V)},x=R=>{l||R.key!==null&&R.key!==o||b(R.key===null?null:R.newValue??null,"external")},T=(async()=>{let R=await _E(e,t);o=R.storageKey,r=R.leaseKey,s=R.lockName,u=m(),!n&&typeof window<"u"&&window.addEventListener("storage",x)})(),H=R=>new Promise(W=>setTimeout(W,R)),_=()=>{let R=y();if(!R)return null;try{let W=R.getItem(r);if(!W)return null;let U=JSON.parse(W);return typeof U?.expiresAt=="number"&&typeof U?.ownerNonce=="string"?U:null}catch{return null}},P=R=>{let W=y();if(W)try{_()?.ownerNonce===R&&W.removeItem(r)}catch{}},A=R=>new Promise(W=>{let U=setTimeout(V,R);function V(){clearTimeout(U),window.removeEventListener("storage",Z),W()}function Z(j){(j.key===null||j.key===r)&&V()}window.addEventListener("storage",Z)}),B=async R=>{let W=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U=Date.now()+15e3;for(;Date.now()<U;){let V=y();if(!V)break;let Z=Date.now(),j=_();if(j&&j.expiresAt>Z&&j.ownerNonce!==W){await A(Math.min(j.expiresAt-Z,500));continue}try{V.setItem(r,JSON.stringify({ownerNonce:W,expiresAt:Z+1e4}))}catch{i=!0;break}if(await H(20+Math.random()*40),_()?.ownerNonce!==W){await A(500);continue}p=W;try{return await R()}finally{p=null,P(W)}}return R()};return{ready:T,async get(){return await T,b(m(),"external"),u},async set(R){await T;let W=y();if(W)try{W.setItem(o,R)}catch{i=!0}b(R,"local")},async clear(){await T;let R=y();if(R)try{R.removeItem(o)}catch{i=!0}b(null,"local")},revision(){return d},subscribe(R){return g.add(R),()=>{g.delete(R)}},async withFirstInitLock(R){await T;let W=globalThis.navigator?.locks;return W?.request?W.request(s,()=>R()):y()?B(R):R()},matches(R,W,U){return R===e&&W===t&&U===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",x),p&&P(p)}}};var{setLoader:NI,load:NE}=lo({fallbackImport:()=>import("@runtypelabs/persona/history-view")});var yg=NE;var bg=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},qo=e=>Object.freeze({...e}),Pv=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),Lv=e=>e?qo(e):null;function Hv(e){let{plugins:t,config:n}=e,o=!1,r=!1,s=!1,i=!1,l=null,d=[],u=()=>{for(let A of d.splice(0))try{A()}catch(B){bg("renderHistoryView cleanup",B)}},p=(A,B)=>{for(let R of t){let W=R[A];if(W)try{let U=W(B);if(U)return U}catch(U){bg(A,U)}}return null},g=()=>({presentation:e.getPresentation(),config:n}),y={header:A=>i?p("renderHistoryHeader",Object.freeze({...g(),returnSurface:e.getReturnSurface(),identityStatus:qo(A.identityStatus),pendingAction:Lv(A.pendingAction),copy:qo(A.copy),actions:Object.freeze({close:x.close,startNewConversation:x.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>i?p("renderHistoryConversation",Object.freeze({...g(),conversation:Pv(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>i?p("renderHistoryState",Object.freeze({...g(),state:qo(A.state),identityStatus:qo(A.identityStatus),copy:qo(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},m=t.flatMap(A=>(A.railSections??[]).map(B=>({...B,placement:B.placement??"above-conversations",items:[],render:R=>B.render(Object.freeze({collapsed:R,presentation:e.getPresentation(),actions:x}))}))),b=e.createView({slots:y,renderDom:!1,onModelChange:()=>P(),railSections:m}),x=Object.freeze({...b.operations,close:e.close}),T=()=>(i=!0,b.setDomRenderEnabled(!0),b.element),H=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(Pv)),activeConversationId:A.activeConversationId,state:qo(A.state),pendingAction:Lv(A.pendingAction),identityStatus:qo(A.identityStatus),nextCursor:A.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:qo(b.copy),actions:x,defaultRenderer:T,requestRender:()=>P(),onCleanup:B=>{d.push(B)}}),_=()=>{i=!1;let A=null;for(let R of t)if(R.renderHistoryView){try{A=R.renderHistoryView(H(b.getModel()))}catch(W){bg("renderHistoryView",W),A=null}if(A)break}let B=!A||A.contains(b.element);return i=B,b.setDomRenderEnabled(B),A??b.element};function P(){if(!(!s||o||r)){r=!0;try{u();let A=_();if(A===l)return;let B=l;l=A,e.onElementChanged(A,B)}finally{r=!1}}}return s=!0,P(),{view:b,get element(){return l??b.element},requestRender:P,dispose:()=>{o=!0,u()}}}var FE=null;function Iv(){return FE}var $E=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),jE=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),vg=e=>jE.get(e)??"Conversation history is unavailable right now.";function zE(e){if(e instanceof Un)return e;if(e instanceof De){let t=$E.get(e.code)??"unavailable";return new Un(t,vg(t),{...e.retryAfterSeconds!==void 0?{retryAfterSeconds:e.retryAfterSeconds}:{}})}return new Un("unavailable",vg("unavailable"))}function Rv(e){let t=()=>e.getClient?.()??e.client,n=e.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new Un("unsupported_scope",vg("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(u){throw zE(u)}},i=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await e.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return t().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return t().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return t().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await t().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let u=await t().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),p=oy(u.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:u.summary,messages:va([],p),conversationRevision:u.conversationRevision??"",nextCursor:u.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>i(await t().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>i(await t().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>t().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>t().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await t().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}var UE=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],Wv={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."};function Cg(e){if(!e)return Wv;let t={...Wv};for(let n of UE){let o=e[n];typeof o=="string"&&o.length>0&&(t[n]=o)}return t}var qE="button:not([disabled])";function ud(e){let t=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=ge("button",{className:"persona-history-confirm__cancel",text:e.cancelLabel,attrs:{type:"button"}}),i=ge("button",{className:"persona-history-confirm__confirm",text:e.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=ge("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},ge("h2",{className:"persona-history-confirm__title",text:e.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),ge("p",{className:"persona-history-confirm__description",text:e.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),ge("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,i));for(let u of[s,i])u.style.minHeight="44px",u.style.minWidth="88px",u.style.padding="0 16px",u.style.borderRadius="var(--persona-radius-md, 0.5rem)",u.style.cursor="pointer",u.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",i.style.border="none",i.style.background="var(--persona-danger, #b42318)",i.style.color="var(--persona-danger-fg, #ffffff)";let d=ge("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(u=>{let p=!1,g=m=>{p||(p=!0,d.removeEventListener("keydown",y,!0),d.remove(),t?.focus(),u(m))};function y(m){if(m.key==="Escape"){m.preventDefault(),m.stopPropagation(),g(!1);return}if(m.key!=="Tab")return;let b=Array.from(l.querySelectorAll(qE));if(b.length===0)return;let x=b[0],T=b[b.length-1],H=document.activeElement;m.shiftKey&&(H===x||!l.contains(H))?(m.preventDefault(),T.focus()):!m.shiftKey&&H===T&&(m.preventDefault(),x.focus())}d.addEventListener("keydown",y,!0),d.addEventListener("pointerdown",m=>{m.target===d&&g(!1)}),s.addEventListener("click",()=>g(!1)),i.addEventListener("click",()=>g(!0)),e.host.appendChild(d),s.focus()})}var wi=require("partial-json");function VE(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function KE(e,t){if(!VE(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 gd(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=(0,wi.parse)(n,wi.STR|wi.OBJ),s=KE(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Bv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function fd(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=to.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(e.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function Ov(){let e=gd();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Dv(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 Ya(e){let t=Dv(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 md(e){let t=Dv(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 GE=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hd(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:u=GE}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let g=null,y=document.createElement("div");y.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=o,m.appendChild(b);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=r,m.appendChild(x),y.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let H=[];for(let R=1;R<=5;R++){let W=document.createElement("button");W.type="button",W.className="persona-feedback-rating-btn persona-feedback-star-btn",W.setAttribute("role","radio"),W.setAttribute("aria-checked","false"),W.setAttribute("aria-label",`${R} star${R>1?"s":""}: ${u[R-1]}`),W.title=u[R-1],W.dataset.rating=String(R),W.innerHTML=`
45
45
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
46
46
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
47
47
  </svg>
48
- `,$.addEventListener("click",()=>{g=N,k.forEach((z,q)=>{let X=q<N;z.classList.toggle("selected",X),z.setAttribute("aria-checked",q===N-1?"true":"false")})}),k.push($),S.appendChild($)}b.appendChild(S);let R=null;if(p){let N=document.createElement("div");N.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),N.appendChild(R),b.appendChild(N)}let E=document.createElement("div");E.className="persona-feedback-actions";let P=document.createElement("button");P.type="button",P.className="persona-feedback-btn persona-feedback-btn-skip",P.textContent=i,P.addEventListener("click",()=>{n?.(),c.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=a,B.addEventListener("click",async()=>{if(g===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let N=R?.value.trim()||void 0;await t(g,N),c.remove()}catch(N){B.disabled=!1,B.textContent=a,console.error("[CSAT Feedback] Failed to submit:",N)}}),E.appendChild(P),E.appendChild(B),b.appendChild(E),c.appendChild(b),c}function Il(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let b=null,f=document.createElement("div");f.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,x.appendChild(C);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=r,x.appendChild(S),f.appendChild(x);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-nps",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Likelihood rating from 0 to 10");let R=document.createElement("div");R.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=d;let P=document.createElement("span");P.className="persona-feedback-label-high",P.textContent=c,R.appendChild(E),R.appendChild(P);let B=document.createElement("div");B.className="persona-feedback-numbers";let N=[];for(let A=0;A<=10;A++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-number-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`Rating ${A} out of 10`),J.textContent=String(A),J.dataset.rating=String(A),A<=6?J.classList.add("persona-feedback-detractor"):A<=8?J.classList.add("persona-feedback-passive"):J.classList.add("persona-feedback-promoter"),J.addEventListener("click",()=>{b=A,N.forEach((Z,ce)=>{Z.classList.toggle("selected",ce===A),Z.setAttribute("aria-checked",ce===A?"true":"false")})}),N.push(J),B.appendChild(J)}k.appendChild(R),k.appendChild(B),f.appendChild(k);let $=null;if(p){let A=document.createElement("div");A.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),A.appendChild($),f.appendChild(A)}let z=document.createElement("div");z.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),g.remove()});let X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=a,X.addEventListener("click",async()=>{if(b===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let A=$?.value.trim()||void 0;await t(b,A),g.remove()}catch(A){X.disabled=!1,X.textContent=a,console.error("[NPS Feedback] Failed to submit:",A)}}),z.appendChild(q),z.appendChild(X),f.appendChild(z),g.appendChild(f),g}var Ts="persona-chat-history",fw=30*1e3,mw=641,hw={"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 yw(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=hw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function Wl(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 bw(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 vw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Zd=e=>!e||typeof e!="object"?{}:{...e},ih=e=>e.map(t=>({...t,streaming:!1})),lh=(e,t,n)=>{let o=e?.markdown?hr(e.markdown):null,r=es(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=no()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?gg(a):a,g=o(c);d=r&&p?r(g):g}else d=_n(a);return d}};function ch(e){let t=y("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=se(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=y("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var xw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Cw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:xw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Hl=(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=ds(t),r=o.features;o=Ra(o);let s=Ia.getForInstance(o.plugins),a=!1,i=km(()=>o),{plugin:p,teardown:d}=Nm();o.components&&Dn.registerAll(o.components);let c=nh(),b=o.persistState===!1?null:o.storageAdapter??Ml(),f={},x=null,C=!1,S=l=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:v}=u;return v&&(C=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(b?.load)try{let l=b.load();if(l&&typeof l.then=="function")x=l.then(u=>S(u??{messages:[],metadata:{}}));else{let m=S(l??{messages:[],metadata:{}});m.metadata&&(f=Zd(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=S({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let k=()=>f,R=l=>{f=l({...f})??{},ic()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Wa],P=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Hr.message,Hr.messageAndClick],B=Ha({parsers:E,handlers:P,getSessionMetadata:k,updateSessionMetadata:R,emit:c.emit,documentRef:typeof document<"u"?document:null});B.syncFromMetadata();let N=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,q=$,X=N,A=o.layout?.header?.layout,J=!1,Z=()=>Ko(o),ce=()=>N||Z(),Y=Z()?!1:N?$:!0,he=!1,te=null,be=()=>{he=!0,te&&clearTimeout(te),te=setTimeout(()=>{he&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),he=!1)},1e4)},ee=lh(o,B,be),ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,ve=o.features?.scrollToBottom??{},ye=o.features?.scrollBehavior??{},at=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,je=me?new Ma(at):null,Ke=o.features?.eventStream?.maxEvents??2e3,Pe=me?new Ea(Ke,je):null,$e=me?new ka:null,Ae=null,ie=!1,Ie=null,dt=0;je?.open().then(()=>Pe?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let tt={onCopy:l=>{c.emit("message:copy",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{c.emit("message:feedback",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(l)}},xt=o.statusIndicator??{},An=l=>l==="idle"?xt.idleText??Dt.idle:l==="connecting"?xt.connectingText??Dt.connecting:l==="connected"?xt.connectedText??Dt.connected:l==="error"?xt.errorText??Dt.error:l==="paused"?xt.pausedText??Dt.paused:l==="resuming"?xt.resumingText??Dt.resuming:Dt[l];function Sn(l,u,m,v){if(v==="idle"&&m.idleLink){l.textContent="";let w=document.createElement("a");w.href=m.idleLink,w.target="_blank",w.rel="noopener noreferrer",w.textContent=u,w.style.color="inherit",w.style.textDecoration="none",l.appendChild(w)}else l.textContent=u}let et=Mm({config:o,showClose:ce()}),{wrapper:Le,panel:xe,pillRoot:nt}=et.shell,Ee=et.panelElements,{container:we,body:ae,messagesWrapper:Se,starterSuggestions:Tn,transcriptSuggestions:oe,suggestions:M,textarea:W,sendButton:h,sendButtonWrapper:H,composerForm:I,statusText:D,welcomeHost:K,welcomeIconHolder:j,greetingHost:G,introTitle:pe,introSubtitle:ze,closeButton:ue,iconHolder:Re,headerTitle:qe,headerSubtitle:Ue,header:Be,footer:Te,actionsRow:ot,rightActions:Tt}=Ee,fn=Ee.leftActions,Na=Ee.setSendButtonMode,re=Ee.micButton,mn=Ee.micButtonWrapper,pt=Ee.attachmentButton,hn=Ee.attachmentButtonWrapper,Lt=Ee.attachmentInput,En=Ee.attachmentPreviewsContainer;we.classList.add("persona-relative"),ae.classList.add("persona-relative");let Qh=12,Es=()=>ve.label??"",Zh=()=>ve.iconName??"arrow-down",ey=()=>ve.enabled!==!1,sn=()=>ye.mode??"anchor-top",ho=()=>sn()==="follow"||sn()==="anchor-top"&&Ds,Ms=()=>ye.anchorTopOffset??16,ty=()=>ye.restorePosition??"bottom",yp=()=>ye.pauseOnInteraction===!0,bp=()=>ye.showActivityWhilePinned!==!1,vp=()=>ye.announce===!0,zl=()=>ye.scrollbar??"on-scroll",It=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");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let ks=y("span","persona-flex persona-items-center"),ql=y("span",""),Yo=y("span","");Yo.setAttribute("data-persona-scroll-to-bottom-count",""),Yo.style.display="none",It.append(ks,ql,Yo),we.appendChild(It);let yn=y("div","persona-stream-anchor-spacer");yn.setAttribute("aria-hidden","true"),yn.setAttribute("data-persona-anchor-spacer",""),yn.style.flexShrink="0",yn.style.pointerEvents="none",yn.style.height="0px",yn.style.display="none",ae.appendChild(yn);let Xo=y("div","persona-sr-only");Xo.setAttribute("aria-live","polite"),Xo.setAttribute("aria-atomic","true"),Xo.setAttribute("role","status"),Xo.setAttribute("data-persona-live-region",""),Object.assign(Xo.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"}),we.appendChild(Xo);let Ls=null,Fa=null,xp=l=>{!vp()||!l||(Fa=l,Ls===null&&(Ls=setTimeout(()=>{Ls=null,Fa&&vp()&&(Xo.textContent=Fa),Fa=null},400)))},Qo=()=>{let u=Te.style.display==="none"?0:Te.offsetHeight;It.style.bottom=`${u+Qh}px`};Qo();let Cp=()=>{let l=!!Es();It.setAttribute("aria-label",Es()||"Jump to latest"),It.title=Es(),It.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ks.innerHTML="";let u=se(Zh(),"14px","currentColor",2);u?(ks.appendChild(u),ks.style.display=""):ks.style.display="none",ql.textContent=Es(),ql.style.display=l?"":"none"};Cp();let Ct=null,Yt=null,wp=null,Ap=s.find(l=>l.renderHeader);if(Ap?.renderHeader){let l=Ap.renderHeader({config:o,defaultRenderer:()=>{let u=uo({config:o,showClose:ce()});return Er(we,u,o),u.header},onClose:()=>ut(!1,"user")});if(l){let u=we.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Be=l,et.header.element=l)}}let Vl=()=>{if(!Pe)return;if(ie=!0,!Ae&&Pe&&(Ae=jm({buffer:Pe,getFullHistory:()=>Pe.getAllFromStore(),onClose:()=>Ps(),config:o,plugins:s,getThroughput:()=>$e?.getMetric()??{status:"idle"}})),Ae&&(ae.style.display="none",Te.parentNode?.insertBefore(Ae.element,Te),Ae.update()),Qe){Qe.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&Qe.classList.add(m))}let l=()=>{if(!ie)return;let u=Date.now();u-dt>=200&&(Ae?.update(),dt=u),Ie=requestAnimationFrame(l)};dt=0,Ie=requestAnimationFrame(l),Ut(),c.emit("eventStream:opened",{timestamp:Date.now()})},Ps=()=>{if(ie){if(ie=!1,Ae&&Ae.element.remove(),ae.style.display="",Qe){Qe.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(u=>u&&Qe.classList.remove(u))}Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),Ut(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Qe=null;if(me){let l=o.features?.eventStream?.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");Qe=y("button",u),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Jt.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let m=se("activity","18px","currentColor",1.5);m&&Qe.appendChild(m);let v=Ee.clearChatButtonWrapper,w=Ee.closeButtonWrapper,L=v||w;L&&L.parentNode===Be?Be.insertBefore(Qe,L):Be.appendChild(Qe),Qe.addEventListener("click",()=>{ie?Ps():Vl()})}let Sp=l=>{let u=o.attachments;if(!u?.enabled)return;let m=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!m){m=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let w=l.querySelector("[data-persona-composer-form]");w?.parentNode?w.parentNode.insertBefore(m,w):l.insertBefore(m,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let w=y("input");w.type="file",w.setAttribute("data-persona-composer-attachment-input",""),w.accept=(u.allowedTypes??io).join(","),w.multiple=(u.maxFiles??4)>1,w.style.display="none",w.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),l.appendChild(w)}},Kl=s.find(l=>l.renderComposer),Gl=!1,Tp=l=>{if(!Kl?.renderComposer)return null;let u=o.composer,m=a?_.isStreaming():!1;return Kl.renderComposer({config:o,defaultRenderer:l,requestRender:()=>Qy(),storage:i(Kl.id),onSubmit:v=>{if(!_||_.isStreaming())return;let w=v.trim(),L=Ct?.hasAttachments()??!1;if(!w&&!L)return;Eu();let U;L&&(U=[],U.push(...Ct.getContentParts()),w&&U.push(Oo(w))),_.sendMessage(w,{contentParts:U}),L&&Ct.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{Lt?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:v=>{o.composer={...o.composer,selectedModelId:v},o.agent&&(o.agent={...o.agent,model:v})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{wp?.()}:void 0})},Ep=Tp(()=>Mr({config:o}).footer);Ep&&(et.replaceComposer(Ep),Te=et.composer.footer,Gl=!0);let Mp=l=>{let u=(...fe)=>{for(let de of fe){let Ce=l.querySelector(de);if(Ce)return Ce}return null},m=l.querySelector("[data-persona-composer-form]"),v=l.querySelector("[data-persona-composer-input]"),w=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");m&&(I=m),v&&(W=v),w&&(h=w),L&&(re=L,mn=L.parentElement),U&&(D=U);let F=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(M=F);let V=u("[data-persona-composer-attachment-button]",".persona-attachment-button");V&&(pt=V,hn=V.parentElement),Lt=u("[data-persona-composer-attachment-input]",'input[type="file"]'),En=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let Q=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");Q&&(ot=Q),fn=u(".persona-widget-composer__left-actions")};Sp(Te),Mp(Te);let Rs=$o(o,Z());Rs&&(Se.style.maxWidth=Rs,Se.style.marginLeft="auto",Se.style.marginRight="auto",Se.style.width="100%",G.style.maxWidth=Rs,G.style.marginLeft="auto",G.style.marginRight="auto",G.style.width="100%",Tn.style.maxWidth=Rs,oe.style.maxWidth=Rs,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%");let kp=()=>{let l=$o(o,Z());if(!(!l||Z()))for(let u of[I,M,En,D])u&&(u.style.maxWidth=l,u.style.marginLeft="auto",u.style.marginRight="auto")};kp();let Lp=()=>{!o.attachments?.enabled||!Lt||!En||(Ct?Ct.remountPreviews(En):(Ct=wr.fromConfig(o.attachments),Ct.setPreviewsContainer(En)),Lt.addEventListener("change",l=>{let u=l.target;Ct?.handleFileSelect(u.files),u.value=""}),we.querySelector(".persona-attachment-drop-overlay")||we.appendChild(ch(o.attachments.dropOverlay)))};Lp();let ny=()=>Yt?.prefetch(),Pp=()=>{if(!(!o.contextMentions?.enabled||!W)&&(Yt=xf({config:o,textarea:W,anchor:I??W,getMessages:()=>_.getMessages(),liveRegionHost:we}),Yt)){let l=W;l.parentElement?.insertBefore(Yt.contextRow,l);let u=Yt.affordanceButtons;for(let m=u.length-1;m>=0;m--){let v=u[m];fn?fn.insertBefore(v,fn.firstChild):I?.appendChild(v)}}};Pp(),(()=>{let l=o.layout?.slots??{},u=v=>{switch(v){case"body-top":return ae.querySelector("[data-persona-intro-card]");case"messages":return Se;case"footer-top":return M;case"composer":return I;case"footer-bottom":return D;default:return null}},m=(v,w)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")Be.insertBefore(w,Be.firstChild);else if(v==="header-right")Be.appendChild(w);else{let L=Be.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(w,L.nextSibling):Be.appendChild(w)}break;case"body-top":{let L=ae.querySelector("[data-persona-intro-card]");L?L.replaceWith(w):ae.insertBefore(w,ae.firstChild);break}case"body-bottom":ae.appendChild(w);break;case"footer-top":M.replaceWith(w);break;case"footer-bottom":D.replaceWith(w);break;default:break}};for(let[v,w]of Object.entries(l))if(w)try{let L=w({config:o,defaultContent:()=>u(v)});L&&m(v,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,L)}})();let Rp=l=>{let m=l.target.closest('button[data-expand-header="true"]');if(!m)return;let v=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;let L=m.getAttribute("data-bubble-type");if(L==="reasoning")vs.has(w)?vs.delete(w):vs.add(w),Lm(w,v);else if(L==="tool")xs.has(w)?xs.delete(w):xs.add(w),Pm(w,v,o);else if(L==="approval"){let F=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",V=Lr.get(w)??F;Lr.set(w,!V),Hm(w,v,o)}sr.delete(w)};Se.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rp(l))}),Se.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Rp(l))}),Se.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let m=Se.getRootNode(),v=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let w=v.toString(),L=qf(w);!L||L===w||(u.setData("text/plain",L),l.preventDefault())});let Jl=new Map,Ip=null,Wp="idle",oy={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},ry=(l,u)=>{let{icon:m,label:v}=oy[u];l.setAttribute("aria-label",v),l.title=v,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let w=se(m,14,"currentColor",2);w&&(l.innerHTML="",l.appendChild(w))},Hp=()=>{Se.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let v=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;ry(u,v&&v===Ip?Wp:"idle")})};Se.addEventListener("click",l=>{let m=l.target.closest(".persona-message-action-btn[data-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.closest("[data-actions-for]");if(!v)return;let w=v.getAttribute("data-actions-for");if(!w)return;let L=m.getAttribute("data-action");if(L==="copy"){let F=_.getMessages().find(V=>V.id===w);if(F&&tt.onCopy){let V=F.content||"";navigator.clipboard.writeText(V).then(()=>{m.classList.add("persona-message-action-success");let Q=se("check",14,"currentColor",2);Q&&(m.innerHTML="",m.appendChild(Q)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let fe=se("copy",14,"currentColor",2);fe&&(m.innerHTML="",m.appendChild(fe))},2e3)}).catch(Q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",Q)}),tt.onCopy(F)}}else if(L==="read-aloud")_.toggleReadAloud(w);else if(L==="upvote"||L==="downvote"){let F=(Jl.get(w)??null)===L,V=L==="upvote"?"thumbs-up":"thumbs-down";if(F){Jl.delete(w),m.classList.remove("persona-message-action-active");let Q=se(V,14,"currentColor",2);Q&&(m.innerHTML="",m.appendChild(Q))}else{let Q=L==="upvote"?"downvote":"upvote",fe=v.querySelector(`[data-action="${Q}"]`);if(fe){fe.classList.remove("persona-message-action-active");let gt=se(Q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);gt&&(fe.innerHTML="",fe.appendChild(gt))}Jl.set(w,L),m.classList.add("persona-message-action-active");let de=se(V,14,"currentColor",2);de&&(de.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(de)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Je=_.getMessages().find(bt=>bt.id===w);Je&&tt.onFeedback&&tt.onFeedback({type:L,messageId:Je.id,message:Je})}}}),Se.addEventListener("click",l=>{let m=l.target.closest("button[data-approval-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.closest(".persona-approval-bubble");if(!v)return;let w=v.getAttribute("data-message-id");if(!w)return;let L=m.getAttribute("data-approval-action");if(!L)return;let U=L==="approve"?"approved":"denied",V=_.getMessages().find(fe=>fe.id===w);if(!V?.approval)return;let Q=v.querySelector("[data-approval-buttons]");Q&&Q.querySelectorAll("button").forEach(de=>{de.disabled=!0,de.style.opacity="0.5",de.style.cursor="not-allowed"}),V.approval.toolType==="webmcp"?_.resolveWebMcpApproval(w,U):_.resolveApproval(V.approval,U)});let Ye=null,Is=null,Zo=()=>{},Ws="none",_a=null,Mn={artifacts:[],selectedId:null},Vn=!1,kn=!1,Hs=!1,Br=!1,Bp=()=>Br||Mn.artifacts.some(l=>$n(o.features?.artifacts,l)==="panel"),$a=()=>Mn.artifacts.length>0&&!Vn&&Bp(),lt={current:null},Yl=(l,u)=>{let m=_.getArtifactById(u),v=m?.markdown,w=m?.title||"artifact",L=m?.file,U=m?.artifactType??"markdown";if(!v){let Q=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(Q){let de=_.getMessages().find(Ce=>Ce.id===Q);if(de?.rawContent)try{let Ce=JSON.parse(de.rawContent);v=Ce?.props?.markdown,w=Ce?.props?.title||w,Ce?.props?.file&&typeof Ce.props.file=="object"&&(L=Ce.props.file),!m&&typeof Ce?.props?.artifactType=="string"&&(U=Ce.props.artifactType)}catch{}}}return{markdown:v,title:w,file:L,artifactType:U}};Se.addEventListener("click",l=>{let m=l.target.closest("[data-download-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:L,title:U,file:F}=Yl(m,v);if(!L)return;let{filename:V,mime:Q,content:fe}=Mf({title:U,markdown:L,file:F}),de=new Blob([fe],{type:Q}),Ce=URL.createObjectURL(de),Je=document.createElement("a");Je.href=Ce,Je.download=V,Je.click(),URL.revokeObjectURL(Ce)}),Se.addEventListener("click",l=>{let m=l.target.closest("[data-artifact-custom-action]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-artifact-custom-action");if(!v)return;let w=m.closest("[data-artifact-inline]"),L=w?null:m.closest("[data-open-artifact]"),U=w?w.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,V=(w?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(bt=>bt.id===v);if(!V)return;let{markdown:Q,title:fe,file:de,artifactType:Ce}=Yl(m,U??""),Je={artifactId:U,title:fe,artifactType:Ce,markdown:Q,file:de};try{Promise.resolve(V.onClick(Je)).catch(()=>{})}catch{}}),Se.addEventListener("click",l=>{let m=l.target.closest("[data-copy-artifact]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-copy-artifact");if(!v)return;let w=_.getArtifactById(v),L="";if(w)L=ya(w);else{let{markdown:U,file:F,artifactType:V}=Yl(m,v);V==="markdown"&&(L=ya({id:v,artifactType:"markdown",status:"complete",markdown:U??"",...F?{file:F}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let U=se("check",16,"currentColor",2);U&&(m.replaceChildren(U),setTimeout(()=>{let F=se("copy",16,"currentColor",2);F&&m.replaceChildren(F)},1500))}).catch(()=>{})}),Se.addEventListener("click",l=>{let m=l.target.closest("[data-expand-artifact-inline]");if(!m)return;l.preventDefault(),l.stopPropagation();let v=m.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Vn=!1,Br=!0,kn=!0,Hs=!0,_.selectArtifact(v),Kn())}),Se.addEventListener("click",l=>{let u=l.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let v=m.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(l.preventDefault(),l.stopPropagation(),Vn=!1,Br=!0,_.selectArtifact(v),Kn())}),Se.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),u.click())});let Dr=Ee.composerOverlay,Or=(l,u,m)=>{let v=u.trim();if(!v||!lt.current)return;let w=l.getAttribute("data-tool-call-id")??"",L=m.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:w,answer:v,answers:m.structured,values:m.values??(m.source==="multi"?v.split(", "):[v]),isFreeText:L,source:m.source},bubbles:!0,composed:!0})),Io(Dr,w);let U=lt.current.getMessages().find(F=>F.toolCall?.id===w);U?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(U,m.structured??v):lt.current.sendMessage(v)},er=l=>{let u=lt.current;if(!u)return;let m=l.getAttribute("data-tool-call-id")??"",v=u.getMessages().find(w=>w.toolCall?.id===m);v&&u.persistAskUserQuestionProgress(v,{answers:vi(l,v),currentIndex:Cn(l)})},Dp=l=>Object.entries(l).map(([u,m])=>`${u}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),Xl=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=Cn(l),m=os(l);if(u>=m-1)return;let v=lt.current?.getMessages().find(w=>w.toolCall?.id===l.getAttribute("data-tool-call-id"));v&&(xi(l,v,o,u+1),er(l))};Dr.addEventListener("click",l=>{let m=l.target.closest("[data-ask-user-action]");if(!m)return;let v=m.closest("[data-persona-ask-sheet-for]");if(!v)return;let w=m.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),w==="dismiss"){let L=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Io(Dr,L);let U=lt.current?.getMessages().find(F=>F.toolCall?.id===L);U?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(U),lt.current?.resolveAskUserQuestion(U,"(dismissed)"));return}if(w==="pick"){let L=m.getAttribute("data-option-label");if(!L)return;let U=v.getAttribute("data-multi-select")==="true",F=Ro(v);if(F&&U){let V=yr(v)[Cn(v)],Q=new Set(Array.isArray(V)?V:[]);Q.has(L)?Q.delete(L):Q.add(L),Wo(v,Array.from(Q)),er(v);return}if(F){Wo(v,L),er(v),Xl(v);return}if(U){let V=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",V?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!V);let Q=v.querySelector('[data-ask-user-action="submit-multi"]');Q&&(Q.disabled=qc(v).length===0);return}Or(v,L,{source:"pick",values:[L]});return}if(w==="submit-multi"){let L=qc(v);if(L.length===0)return;Or(v,L.join(", "),{source:"multi",values:L});return}if(w==="open-free-text"){let L=v.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(w==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(w==="submit-free-text"){let U=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!U.trim())return;if(Ro(v)){Wo(v,U.trim()),er(v),Xl(v);return}Or(v,U,{source:"free-text"});return}if(w==="next"||w==="back"){if(!lt.current)return;let L=v.getAttribute("data-tool-call-id")??"",U=lt.current.getMessages().find(de=>de.toolCall?.id===L);if(!U)return;let V=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(V){let de=yr(v)[Cn(v)];(typeof de!="string"||de!==V)&&Wo(v,V)}let Q=w==="next"?1:-1,fe=Cn(v)+Q;xi(v,U,o,fe),er(v);return}if(w==="submit-all"){if(!lt.current)return;let L=v.getAttribute("data-tool-call-id")??"",U=lt.current.getMessages().find(de=>de.toolCall?.id===L);if(!U)return;let V=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";V&&Wo(v,V);let Q=vi(v,U);lt.current.persistAskUserQuestionProgress(U,{answers:Q,currentIndex:Cn(v)});let fe=Dp(Q);Or(v,fe||"(submitted)",{source:"submit-all",structured:Q});return}if(w==="skip"){if(!lt.current)return;let L=v.getAttribute("data-tool-call-id")??"",U=lt.current.getMessages().find(Ce=>Ce.toolCall?.id===L);if(!U)return;let F=Ro(v),V=Cn(v),Q=os(v),fe=V>=Q-1;if(!F){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Io(Dr,L),U.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(U),lt.current.resolveAskUserQuestion(U,"(dismissed)"));return}Wo(v,"");let de=v.querySelector('[data-ask-free-text-input="true"]');if(de&&(de.value=""),fe){let Ce=vi(v,U),Je=Dp(Ce);Or(v,Je||"(skipped)",{source:"submit-all",structured:Ce});return}xi(v,U,o,V+1),er(v);return}}),Dr.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let m=l.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let v=m.closest("[data-persona-ask-sheet-for]");if(!v)return;l.preventDefault();let w=m.value;if(w.trim()){if(Ro(v)){Wo(v,w.trim()),er(v),Xl(v);return}Or(v,w,{source:"free-text"})}});let Op=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=Dr.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let v=Number(l.key),L=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];L&&(l.preventDefault(),L.click())};document.addEventListener("keydown",Op);let yo=null,wt=null,Bs=null,ja=null,Ql=()=>{},Np=!1,Ua="",za="";function Zl(){ja?.(),ja=null}let Fp=()=>{if(!yo||!wt)return;let l=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||m){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let v=yo.firstElementChild;if(!v||v===wt)return;let w=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${w}px`,wt.style.zIndex="5";let L=Jd(yo,u),U=v.offsetWidth+L/2-w/2;wt.style.left=`${Math.max(0,U)}px`},qa=()=>{},sy=()=>{let l=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||l.innerWidth>m?!1:N||Mt(o)},Va=()=>!Zt(o)||!$a()||e.classList.contains("persona-artifact-narrow-host")||sy()||(e.ownerDocument.defaultView??window).innerWidth<mw?"none":qd(o)?"detached":"welded",Kn=()=>{if(!Ye||!Zt(o))return;La(e,o),Pa(e,o),qa();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=xe.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l);let m=$a();Ye.setVisible(m),Ye.update(Mn),Vn?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),kn=!1,Hs=!1):Mn.artifacts.length>0&&Bp()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),kn=!1,Hs=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ye.setExpandToggleVisible(v),Ye.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ye.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ye.setTabFade(o.features?.artifacts?.layout?.tabFade),Ye.setRenderTabBar(o.features?.artifacts?.renderTabBar),!v&&!Hs&&(kn=!1),kn!==Np){let L=Ye.element;kn?(Ua=L.style.width,za=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(Ua&&(L.style.width=Ua),za&&(L.style.maxWidth=za),Ua="",za=""),Np=kn}e.classList.toggle("persona-artifact-expanded",kn),Ye.setExpanded(kn);let w=Va();w!==Ws&&(Ws=w,Zo()),Ql()};if(Zt(o)){xe.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(we),Ye=Um(o,{onSelect:m=>lt.current?.selectArtifact(m),onDismiss:()=>{Vn=!0,Kn()},onToggleExpand:()=>{let m=!kn,v=Mn.selectedId??Mn.artifacts[Mn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:m})!==!0&&(kn=m,m||(Hs=!1),Kn())}}),Ye.element.classList.add("persona-hidden"),yo=u,u.appendChild(l),u.appendChild(Ye.element),Ye.backdrop&&xe.appendChild(Ye.backdrop),xe.appendChild(u),Ql=()=>{if(!yo||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Bs?.(),Bs=null,Zl(),wt&&(wt.remove(),wt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!wt){let v=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let w=e.ownerDocument,L=w.defaultView??window,U=F=>{if(!Ye||F.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;F.preventDefault(),Zl();let V=F.clientX,Q=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,de=Je=>{let bt=yo.getBoundingClientRect().width,gt=e.classList.contains("persona-artifact-welded-split"),cn=Jd(yo,L),kt=gt?0:v.getBoundingClientRect().width||6,Ht=Q-(Je.clientX-V),O=Qm(Ht,bt,cn,kt,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${O}px`,Ye.element.style.maxWidth="none",Fp()},Ce=()=>{w.removeEventListener("pointermove",de),w.removeEventListener("pointerup",Ce),w.removeEventListener("pointercancel",Ce),ja=null;try{v.releasePointerCapture(F.pointerId)}catch{}};ja=Ce,w.addEventListener("pointermove",de),w.addEventListener("pointerup",Ce),w.addEventListener("pointercancel",Ce);try{v.setPointerCapture(F.pointerId)}catch{}};v.addEventListener("pointerdown",U),wt=v,yo.insertBefore(v,Ye.element),Bs=()=>{v.removeEventListener("pointerdown",U)}}if(wt){let v=$a();wt.classList.toggle("persona-hidden",!v),Fp()}},qa=()=>{if(!N||!Ye||(o.launcher?.sidebarMode??!1)||Mt(o)&&rn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=L||!Vm(o,N))return;let U=o.launcher?.width??o.launcherWidth??pn,F=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";$a()?(xe.style.width=F,xe.style.maxWidth=F):(xe.style.width=U,xe.style.maxWidth=U)},typeof ResizeObserver<"u"&&(Is=new ResizeObserver(()=>{Kn()}),Is.observe(xe))}else xe.appendChild(we);Z()&&nt&&(Ee.peekBanner&&nt.appendChild(Ee.peekBanner),nt.appendChild(Te)),e.appendChild(Le),nt&&e.appendChild(nt);let ec=()=>{if(Z()){xe.style.width="100%",xe.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},nn=Le.dataset.state==="expanded",di=Rt.expandedSize??"anchored";if(!(nn&&di!=="fullscreen")){we.style.background="",we.style.border="",we.style.borderRadius="",we.style.overflow="",we.style.boxShadow="";return}let Ys=o.theme?.components?.panel,pi=_o(o),Jr=(eo,mr)=>eo==null||eo===""?mr:Qt(pi,eo)??eo,ui="1px solid var(--persona-border)",Wc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",fr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";we.style.background="var(--persona-surface, #ffffff)",we.style.border=Jr(Ys?.border,ui),we.style.borderRadius=Jr(Ys?.borderRadius,fr),we.style.boxShadow=Jr(Ys?.shadow,Wc),we.style.overflow="hidden";return}let l=Mt(o),u=o.launcher?.sidebarMode??!1,m=l||u||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,w=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,U=_o(o),F=(Rt,nn)=>Rt==null||Rt===""?nn:Qt(U,Rt)??Rt,V=e.ownerDocument.defaultView??window,Q=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,de=V.innerWidth<=fe,Ce=Q&&de&&N,Je=l&&Q&&de,bt=o.launcher?.position??"bottom-left",gt=bt==="bottom-left"||bt==="top-left",cn=o.launcher?.zIndex??$t,kt="var(--persona-panel-border, 1px solid var(--persona-border))",Ht="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",O="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",We=w&&!Ce&&!Je;We?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=We?kt:u||Ce?"none":kt,Me=We?Ht:Ce?"none":u?gt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":v?"none":Ht;l&&!Ce&&!We&&(Me="none",Fe="none");let Et=We?O:u||Ce?"0":O,ft=F(L?.border,Fe),Ft=F(L?.shadow,Me),mt=F(L?.borderRadius,Et),tn=Va(),Bt=tn==="detached",He=tn==="welded";e.classList.toggle("persona-artifact-detached-split",Bt),e.classList.toggle("persona-artifact-welded-split",He);let _e="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"&&Zt(o)&&qd(o)&&v&&!l;e.classList.toggle("persona-artifact-chat-flush",St);let ct=Bt||St?"none":Ft,ht=Bt?kt:He?"none":ft,Xe=Bt?O:mt;St&&(ht="none",Xe="0");let Oe=L?.borderRadius!=null&&L.borderRadius!=="",vt=St&&!Oe?"0":mt,Vt=ae.scrollTop;e.style.cssText="",Le.style.cssText="",xe.style.cssText="",we.style.cssText="",ae.style.cssText="",Te.style.cssText="",ie&&(ae.style.display="none"),(m||v)&&(e.style.minWidth="0");let xn=()=>{if(Vt<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===Vt)return;let nn=ae.scrollHeight-ae.clientHeight;nn<=0||(ae.scrollTop=Math.min(Vt,nn))})};if(Ce){Le.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"),Le.style.cssText=`
48
+ `,W.addEventListener("click",()=>{g=R,H.forEach((U,V)=>{let Z=V<R;U.classList.toggle("selected",Z),U.setAttribute("aria-checked",V===R-1?"true":"false")})}),H.push(W),T.appendChild(W)}y.appendChild(T);let _=null;if(d){let R=document.createElement("div");R.className="persona-feedback-comment-container",_=document.createElement("textarea"),_.className="persona-feedback-comment",_.placeholder=s,_.rows=3,_.setAttribute("aria-label","Additional comments"),R.appendChild(_),y.appendChild(R)}let P=document.createElement("div");P.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),p.remove()});let B=document.createElement("button");return B.type="button",B.className="persona-feedback-btn persona-feedback-btn-submit",B.textContent=i,B.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}B.disabled=!0,B.textContent="Submitting...";try{let R=_?.value.trim()||void 0;await t(g,R),p.remove()}catch(R){B.disabled=!1,B.textContent=i,console.error("[CSAT Feedback] Failed to submit:",R)}}),P.appendChild(A),P.appendChild(B),y.appendChild(P),p.appendChild(y),p}function yd(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:p="Very likely"}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let y=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,b.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,b.appendChild(T),m.appendChild(b);let H=document.createElement("div");H.className="persona-feedback-rating persona-feedback-rating-nps",H.setAttribute("role","radiogroup"),H.setAttribute("aria-label","Likelihood rating from 0 to 10");let _=document.createElement("div");_.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=u;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=p,_.appendChild(P),_.appendChild(A);let B=document.createElement("div");B.className="persona-feedback-numbers";let R=[];for(let j=0;j<=10;j++){let X=document.createElement("button");X.type="button",X.className="persona-feedback-rating-btn persona-feedback-number-btn",X.setAttribute("role","radio"),X.setAttribute("aria-checked","false"),X.setAttribute("aria-label",`Rating ${j} out of 10`),X.textContent=String(j),X.dataset.rating=String(j),j<=6?X.classList.add("persona-feedback-detractor"):j<=8?X.classList.add("persona-feedback-passive"):X.classList.add("persona-feedback-promoter"),X.addEventListener("click",()=>{y=j,R.forEach((ue,xe)=>{ue.classList.toggle("selected",xe===j),ue.setAttribute("aria-checked",xe===j?"true":"false")})}),R.push(X),B.appendChild(X)}H.appendChild(_),H.appendChild(B),m.appendChild(H);let W=null;if(d){let j=document.createElement("div");j.className="persona-feedback-comment-container",W=document.createElement("textarea"),W.className="persona-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),j.appendChild(W),m.appendChild(j)}let U=document.createElement("div");U.className="persona-feedback-actions";let V=document.createElement("button");V.type="button",V.className="persona-feedback-btn persona-feedback-btn-skip",V.textContent=l,V.addEventListener("click",()=>{n?.(),g.remove()});let Z=document.createElement("button");return Z.type="button",Z.className="persona-feedback-btn persona-feedback-btn-submit",Z.textContent=i,Z.addEventListener("click",async()=>{if(y===null){B.classList.add("persona-feedback-shake"),setTimeout(()=>B.classList.remove("persona-feedback-shake"),500);return}Z.disabled=!0,Z.textContent="Submitting...";try{let j=W?.value.trim()||void 0;await t(y,j),g.remove()}catch(j){Z.disabled=!1,Z.textContent=i,console.error("[NPS Feedback] Failed to submit:",j)}}),U.appendChild(V),U.appendChild(Z),m.appendChild(U),g.appendChild(m),g}var xi="persona-chat-history",XE=30*1e3,QE=641,ZE={"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 eM(e){if(!e)return[];let t=[],n=Array.from(e.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){t.push(r);continue}let s=ZE[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function bd(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 tM(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 nM(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var wg=e=>!e||typeof e!="object"?{}:{...e},_v=e=>e.map(t=>({...t,streaming:!1})),Nv=(e,t,n)=>{let o=e?.markdown?Xr(e.markdown):null,r=Vs(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let i=s.text??"",l=s.message.rawContent??null;if(t){let p=t.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});p!==null&&(i=p.text,p.persist||(s.message.__skipPersist=!0),p.resubmit&&!s.streaming&&n&&n())}let d=Bo()!==null,u;if(e?.postprocessMessage){let p=e.postprocessMessage({...s,text:i,raw:l??s.text??""});u=r?r(p):p}else if(o){let p=s.streaming?yh(i):i,g=o(p);u=r&&d?r(g):g}else u=co(i);return u}};function Fv(e){let t=v("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,i=de(n,o,r,s);if(i&&t.appendChild(i),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var oM=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},rM=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:oM(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vd=(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=ii(t),r=()=>{Wy({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=qa(o);let i=Va.getForInstance(o.plugins),l=Vy(e),d=[],u=!1,p=Xb(()=>o),{plugin:g,teardown:y}=av();o.components&&to.registerAll(o.components);let m=Tv(),x=o.persistState===!1?null:o.storageAdapter??pd(),T={},H=null,_,P=new Promise(a=>{_=a}),A=!1,B=a=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(a);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:h}=c;return h&&(A=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return a};if(x?.load)try{let a=x.load();if(a&&typeof a.then=="function")H=a.then(c=>B(c??{messages:[],metadata:{}}));else{let f=B(a??{messages:[],metadata:{}});f.metadata&&(T=wg(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=B({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}H||_();let R=()=>T,W=a=>{T=a({...T})??{},Ud()},U=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ka],V=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick],Z=Ga({parsers:U,handlers:V,getSessionMetadata:R,updateSessionMetadata:W,emit:m.emit,documentRef:typeof document<"u"?document:null});Z.syncFromMetadata();let j=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,ue=o.autoFocusInput??!1,xe=X,Ce=j,ye=o.layout?.header?.layout,oe=!1,le=()=>Sr(o),ae=()=>j||le(),M=le()?!1:j?X:!0,ee=!1,pe=null,we=()=>{ee=!0,pe&&clearTimeout(pe),pe=setTimeout(()=>{ee&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ee=!1)},1e4)},me=Nv(o,Z,we),Se=o.features?.showReasoning??!0,Le=o.features?.showToolCalls??!0,He=o.features?.showEventStreamToggle??!1,Qe=o.features?.scrollToBottom??{},Oe=o.features?.scrollBehavior??{},We=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",ve=`${We()}event-stream`,Ne=He?new $a(ve):null,ft=o.features?.eventStream?.maxEvents??2e3,Ae=He?new Fa(ft,Ne):null,Fe=He?new ja:null,at=null,Gt=!1,Ut=null,Vn=0,et=!1,nt=null,wt=()=>{},Zt=()=>{},vo=()=>{},Rt=()=>{},Ko=()=>{},vs=()=>Gt||et&&nt==="panel";Ne?.open().then(()=>Ae?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let F={onCopy:a=>{m.emit("message:copy",a),D?.isClientTokenMode()&&D.submitMessageFeedback(a.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{m.emit("message:feedback",a),D?.isClientTokenMode()&&D.submitMessageFeedback(a.messageId,a.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(a)}},te=o.statusIndicator??{},w=a=>a==="idle"?te.idleText??Nt.idle:a==="connecting"?te.connectingText??Nt.connecting:a==="connected"?te.connectedText??Nt.connected:a==="error"?te.errorText??Nt.error:a==="paused"?te.pausedText??Nt.paused:a==="resuming"?te.resumingText??Nt.resuming:Nt[a];function S(a,c,f,h){if(h==="idle"&&f.idleLink){a.textContent="";let C=document.createElement("a");C.href=f.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=c,C.style.color="inherit",C.style.textDecoration="none",a.appendChild(C)}else a.textContent=c}let I=Jb({config:o,showClose:ae()}),{wrapper:L,panel:O,pillRoot:Y}=I.shell,Q=I.panelElements,{container:G,body:K,messagesWrapper:ce,starterSuggestions:dt,transcriptSuggestions:st,suggestions:xt,textarea:he,sendButton:be,sendButtonWrapper:en,composerForm:Ue,statusText:on,welcomeHost:fn,welcomeIconHolder:PC,greetingHost:xn,introTitle:LC,introSubtitle:HC,closeButton:Be,iconHolder:St,headerTitle:Go,headerSubtitle:Er,header:Ee,footer:$e,actionsRow:IC,rightActions:RC}=Q,Cs=Q.leftActions,Ng=Q.setSendButtonMode,re=Q.micButton,Co=Q.micButtonWrapper,mt=Q.attachmentButton,Wn=Q.attachmentButtonWrapper,kt=Q.attachmentInput,Kn=Q.attachmentPreviewsContainer;G.classList.add("persona-relative"),K.classList.add("persona-relative");let WC=12,Si=()=>Qe.label??"",BC=()=>Qe.iconName??"arrow-down",OC=()=>Qe.enabled!==!1,Sn=()=>Oe.mode??"anchor-top",Yo=()=>Sn()==="follow"||Sn()==="anchor-top"&&Ri,Ai=()=>Oe.anchorTopOffset??16,DC=()=>Oe.restorePosition??"bottom",Fg=()=>Oe.pauseOnInteraction===!0,$g=()=>Oe.showActivityWhilePinned!==!1,jg=()=>Oe.announce===!0,Pd=()=>Oe.scrollbar??"on-scroll",Wt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Ti=v("span","persona-flex persona-items-center"),Ld=v("span",""),Mr=v("span","");Mr.setAttribute("data-persona-scroll-to-bottom-count",""),Mr.style.display="none",Wt.append(Ti,Ld,Mr),G.appendChild(Wt);let Bn=v("div","persona-stream-anchor-spacer");Bn.setAttribute("aria-hidden","true"),Bn.setAttribute("data-persona-anchor-spacer",""),Bn.style.flexShrink="0",Bn.style.pointerEvents="none",Bn.style.height="0px",Bn.style.display="none",K.appendChild(Bn);let wo=v("div","persona-sr-only");wo.setAttribute("aria-live","polite"),wo.setAttribute("aria-atomic","true"),wo.setAttribute("role","status"),wo.setAttribute("data-persona-live-region",""),Object.assign(wo.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"}),G.appendChild(wo);let Ei=null,Qa=null,zg=a=>{!jg()||!a||(Qa=a,Ei===null&&(Ei=setTimeout(()=>{Ei=null,Qa&&jg()&&(wo.textContent=Qa),Qa=null},400)))},kr=()=>{let c=$e.style.display==="none"?0:$e.offsetHeight;Wt.style.bottom=`${c+WC}px`};kr();let Ug=()=>{let a=!!Si();Wt.setAttribute("aria-label",Si()||"Jump to latest"),Wt.title=Si(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Ti.innerHTML="";let c=de(BC(),"14px","currentColor",2);c?(Ti.appendChild(c),Ti.style.display=""):Ti.style.display="none",Ld.textContent=Si(),Ld.style.display=a?"":"none"};Ug();let ht=null,rn=null,qg=null,Vg=i.find(a=>a.renderHeader);if(Vg?.renderHeader){let a=Vg.renderHeader({config:o,defaultRenderer:()=>{let c=jo({config:o,showClose:ae()});return ds(G,c,o),c.header},onClose:()=>lt(!1,"user")});if(a){let c=Ee;c&&(c.replaceWith(a),Ee=a,I.header.element=a)}}let Kg=()=>{at&&(K.style.display="none",$e.parentNode?.insertBefore(at.element,$e),at.update())},Hd=()=>{if(!Ae)return;if(Gt=!0,at?Kg():pv().then(c=>{at||!Gt||!Ae||(at=c.createEventStreamView({buffer:Ae,getFullHistory:()=>Ae.getAllFromStore(),onClose:()=>ws(),config:o,plugins:i,getThroughput:()=>Fe?.getMetric()??{status:"idle"}}),Kg())}).catch(()=>{ws()}),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${un.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&Ye.classList.add(f))}let a=()=>{if(!Gt)return;let c=Date.now();c-Vn>=200&&(at?.update(),Vn=c),Ut=requestAnimationFrame(a)};Vn=0,Ut=requestAnimationFrame(a),$t(),m.emit("eventStream:opened",{timestamp:Date.now()})},ws=()=>{if(Gt){if(Gt=!1,at&&at.element.remove(),K.style.display="",Ye){Ye.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(c=>c&&Ye.classList.remove(c))}Ut!==null&&(cancelAnimationFrame(Ut),Ut=null),$t(),m.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(He){let a=o.features?.eventStream?.classNames,c="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(a?.toggleButton?" "+a.toggleButton:"");Ye=v("button",c),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=un.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let f=de("activity","18px","currentColor",1.5);f&&Ye.appendChild(f);let h=Q.clearChatButtonWrapper,C=Q.closeButtonWrapper,E=h||C;E&&E.parentNode===Ee?Ee.insertBefore(Ye,E):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{Gt?ws():Hd()})}let Gg=a=>{let c=o.attachments;if(!c?.enabled)return;let f=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let C=a.querySelector("[data-persona-composer-form]");C?.parentNode?C.parentNode.insertBefore(f,C):a.insertBefore(f,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let C=v("input");C.type="file",C.setAttribute("data-persona-composer-attachment-input",""),C.accept=(c.allowedTypes??No).join(","),C.multiple=(c.maxFiles??4)>1,C.style.display="none",C.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),a.appendChild(C)}},Id=i.find(a=>a.renderComposer),Mi=!1,Yg=a=>{if(!Id?.renderComposer)return null;let c=o.composer,f=u?D.isStreaming():!1;return Id.renderComposer({config:o,defaultRenderer:a,requestRender:()=>bx(),storage:p(Id.id),onSubmit:h=>{if(!D||D.isStreaming())return;let C=h.trim(),E=ht?.hasAttachments()??!1;if(!C&&!E)return;Lm();let z;E&&(z=[],z.push(...ht.getContentParts()),C&&z.push(go(C))),D.sendMessage(C,{contentParts:z}),E&&ht.clearAttachments()},streaming:f,disabled:f,openAttachmentPicker:()=>{kt?.click()},models:c?.models,selectedModelId:c?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{qg?.()}:void 0})},Jg=Yg(()=>ps({config:o}).footer);Jg&&(I.replaceComposer(Jg),$e=I.composer.footer,Mi=!0);let Xg=a=>{let c=(...ne)=>{for(let ie of ne){let fe=a.querySelector(ie);if(fe)return fe}return null},f=a.querySelector("[data-persona-composer-form]"),h=a.querySelector("[data-persona-composer-input]"),C=a.querySelector("[data-persona-composer-submit]"),E=a.querySelector("[data-persona-composer-mic]"),z=a.querySelector("[data-persona-composer-status]");f&&(Ue=f),h&&(he=h),C&&(be=C),E&&(re=E,Co=E.parentElement),z&&(on=z);let $=c("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(xt=$);let J=c("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(mt=J,Wn=J.parentElement),kt=c("[data-persona-composer-attachment-input]",'input[type="file"]'),Kn=c("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let q=c("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");q&&(IC=q),Cs=c(".persona-widget-composer__left-actions")};Gg($e),Xg($e);let ki=br(o,le());ki&&(ce.style.maxWidth=ki,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",xn.style.maxWidth=ki,xn.style.marginLeft="auto",xn.style.marginRight="auto",xn.style.width="100%",dt.style.maxWidth=ki,st.style.maxWidth=ki,st.style.marginLeft="auto",st.style.marginRight="auto",st.style.width="100%");let Qg=()=>{let a=br(o,le());if(!(!a||le()))for(let c of[Ue,xt,Kn,on])c&&(c.style.maxWidth=a,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};Qg();let Zg=()=>{!o.attachments?.enabled||!kt||!Kn||(ht?ht.remountPreviews(Kn):(ht=os.fromConfig(o.attachments),ht.setPreviewsContainer(Kn)),kt.addEventListener("change",a=>{let c=a.target;ht?.handleFileSelect(c.files),c.value=""}),G.querySelector(".persona-attachment-drop-overlay")||G.appendChild(Fv(o.attachments.dropOverlay)))};Zg();let _C=()=>rn?.prefetch(),ef=()=>{if(!(!o.contextMentions?.enabled||!he)&&(rn=_y({config:o,textarea:he,anchor:Ue??he,getMessages:()=>D.getMessages(),liveRegionHost:G}),rn)){let a=he;a.parentElement?.insertBefore(rn.contextRow,a);let c=rn.affordanceButtons;for(let f=c.length-1;f>=0;f--){let h=c[f];Cs?Cs.insertBefore(h,Cs.firstChild):Ue?.appendChild(h)}}};ef(),(()=>{let a=o.layout?.slots??{},c=h=>{switch(h){case"body-top":return K.querySelector("[data-persona-intro-card]");case"messages":return ce;case"footer-top":return xt;case"composer":return Ue;case"footer-bottom":return on;default:return null}},f=(h,C)=>{switch(h){case"header-left":case"header-center":case"header-right":if(h==="header-left")Ee.insertBefore(C,Ee.firstChild);else if(h==="header-right")Ee.appendChild(C);else{let E=Ee.querySelector(".persona-flex-col");E?E.parentNode?.insertBefore(C,E.nextSibling):Ee.appendChild(C)}break;case"body-top":{let E=K.querySelector("[data-persona-intro-card]");E?E.replaceWith(C):K.insertBefore(C,K.firstChild);break}case"body-bottom":K.appendChild(C);break;case"footer-top":xt.replaceWith(C);break;case"footer-bottom":on.replaceWith(C);break;default:break}};for(let[h,C]of Object.entries(a))if(C)try{let E=C({config:o,defaultContent:()=>c(h)});E&&f(h,E)}catch(E){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${h}":`,E)}})();let tf=a=>{let f=a.target.closest('button[data-expand-header="true"]');if(!f)return;let h=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-bubble-type");if(E==="reasoning")yi.has(C)?yi.delete(C):yi.add(C),Qb(C,h);else if(E==="tool")bi.has(C)?bi.delete(C):bi.add(C),Zb(C,h,o);else if(E==="approval"){let $=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=gs.get(C)??$;gs.set(C,!J),ov(C,h,o)}Tn.delete(C)};ce.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),tf(a))}),ce.addEventListener("keydown",a=>{let c=a.target;(a.key==="Enter"||a.key===" ")&&c.closest('button[data-expand-header="true"]')&&(a.preventDefault(),tf(a))}),ce.addEventListener("copy",a=>{let{clipboardData:c}=a;if(!c)return;let f=ce.getRootNode(),h=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!h||h.isCollapsed)return;let C=h.toString(),E=pb(C);!E||E===C||(c.setData("text/plain",E),a.preventDefault())});let Rd=new Map,nf=null,of="idle",NC={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},FC=(a,c)=>{let{icon:f,label:h}=NC[c];a.setAttribute("aria-label",h),a.title=h,a.setAttribute("aria-pressed",c==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",c!=="idle"),a.classList.toggle("persona-message-action-loading",c==="loading");let C=de(f,14,"currentColor",2);C&&(a.innerHTML="",a.appendChild(C))},rf=()=>{ce.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let h=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;FC(c,h&&h===nf?of:"idle")})};ce.addEventListener("click",a=>{let f=a.target.closest(".persona-message-action-btn[data-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.closest("[data-actions-for]");if(!h)return;let C=h.getAttribute("data-actions-for");if(!C)return;let E=f.getAttribute("data-action");if(E==="copy"){let $=D.getMessages().find(J=>J.id===C);if($&&F.onCopy){let J=$.content||"";navigator.clipboard.writeText(J).then(()=>{f.classList.add("persona-message-action-success");let q=de("check",14,"currentColor",2);q&&(f.innerHTML="",f.appendChild(q)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let ne=de("copy",14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne))},2e3)}).catch(q=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",q)}),F.onCopy($)}}else if(E==="read-aloud")D.toggleReadAloud(C);else if(E==="upvote"||E==="downvote"){let $=(Rd.get(C)??null)===E,J=E==="upvote"?"thumbs-up":"thumbs-down";if($){Rd.delete(C),f.classList.remove("persona-message-action-active");let q=de(J,14,"currentColor",2);q&&(f.innerHTML="",f.appendChild(q))}else{let q=E==="upvote"?"downvote":"upvote",ne=h.querySelector(`[data-action="${q}"]`);if(ne){ne.classList.remove("persona-message-action-active");let Vt=de(q==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Vt&&(ne.innerHTML="",ne.appendChild(Vt))}Rd.set(C,E),f.classList.add("persona-message-action-active");let ie=de(J,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(ie)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Je=D.getMessages().find(vt=>vt.id===C);Je&&F.onFeedback&&F.onFeedback({type:E,messageId:Je.id,message:Je})}}}),ce.addEventListener("click",a=>{let f=a.target.closest("button[data-approval-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.closest(".persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let E=f.getAttribute("data-approval-action");if(!E)return;let z=E==="approve"?"approved":"denied",J=D.getMessages().find(ne=>ne.id===C);if(!J?.approval)return;let q=h.querySelector("[data-approval-buttons]");q&&q.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?D.resolveWebMcpApproval(C,z):D.resolveApproval(J.approval,z)});let _e=null,Pi=null,Pr=()=>{},Li="none",Za=null,Gn={artifacts:[],selectedId:null},xo=!1,Yn=!1,Hi=!1,xs=!1,sf=()=>xs||Gn.artifacts.some(a=>po(o.features?.artifacts,a)==="panel"),el=()=>Gn.artifacts.length>0&&!xo&&sf(),it={current:null},Wd=(a,c)=>{let f=D.getArtifactById(c),h=f?.markdown,C=f?.title||"artifact",E=f?.file,z=f?.artifactType??"markdown";if(!h){let q=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(q){let ie=D.getMessages().find(fe=>fe.id===q);if(ie?.rawContent)try{let fe=JSON.parse(ie.rawContent);h=fe?.props?.markdown,C=fe?.props?.title||C,fe?.props?.file&&typeof fe.props.file=="object"&&(E=fe.props.file),!f&&typeof fe?.props?.artifactType=="string"&&(z=fe.props.artifactType)}catch{}}}return{markdown:h,title:C,file:E,artifactType:z}};ce.addEventListener("click",a=>{let f=a.target.closest("[data-download-artifact]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-download-artifact");if(!h||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:h})===!0)return;let{markdown:E,title:z,file:$}=Wd(f,h);E&&Rc(Ic({title:z,markdown:E,file:$}))}),ce.addEventListener("click",a=>{let f=a.target.closest("[data-artifact-custom-action]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-artifact-custom-action");if(!h)return;let C=f.closest("[data-artifact-inline]"),E=C?null:f.closest("[data-open-artifact]"),z=C?C.getAttribute("data-artifact-inline"):E?.getAttribute("data-open-artifact")??null,J=(C?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(vt=>vt.id===h);if(!J)return;let{markdown:q,title:ne,file:ie,artifactType:fe}=Wd(f,z??""),Je={artifactId:z,title:ne,artifactType:fe,markdown:q,file:ie};try{Promise.resolve(J.onClick(Je)).catch(()=>{})}catch{}}),ce.addEventListener("click",a=>{let f=a.target.closest("[data-copy-artifact]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-copy-artifact");if(!h)return;let C=D.getArtifactById(h),E="";if(C)E=Ha(C);else{let{markdown:z,file:$,artifactType:J}=Wd(f,h);J==="markdown"&&(E=Ha({id:h,artifactType:"markdown",status:"complete",markdown:z??"",...$?{file:$}:{}}))}E&&navigator.clipboard.writeText(E).then(()=>{let z=de("check",16,"currentColor",2);z&&(f.replaceChildren(z),setTimeout(()=>{let $=de("copy",16,"currentColor",2);$&&f.replaceChildren($)},1500))}).catch(()=>{})}),ce.addEventListener("click",a=>{let f=a.target.closest("[data-expand-artifact-inline]");if(!f)return;a.preventDefault(),a.stopPropagation();let h=f.getAttribute("data-expand-artifact-inline");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(xo=!1,xs=!0,Yn=!0,Hi=!0,D.selectArtifact(h),So())}),ce.addEventListener("click",a=>{let c=a.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let h=f.getAttribute("data-open-artifact");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(a.preventDefault(),a.stopPropagation(),xo=!1,xs=!0,D.selectArtifact(h),So())}),ce.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let c=a.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),c.click())});let Ss=Q.composerOverlay,As=(a,c,f)=>{let h=c.trim();if(!h||!it.current)return;let C=a.getAttribute("data-tool-call-id")??"",E=f.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:E,source:f.source},bubbles:!0,composed:!0})),dr(Ss,C);let z=it.current.getMessages().find($=>$.toolCall?.id===C);z?.agentMetadata?.awaitingLocalTool?it.current.resolveAskUserQuestion(z,f.structured??h):it.current.sendMessage(h)},Lr=a=>{let c=it.current;if(!c)return;let f=a.getAttribute("data-tool-call-id")??"",h=c.getMessages().find(C=>C.toolCall?.id===f);h&&c.persistAskUserQuestionProgress(h,{answers:tc(a,h),currentIndex:zn(a)})},af=a=>Object.entries(a).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),Bd=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=zn(a),f=Ys(a);if(c>=f-1)return;let h=it.current?.getMessages().find(C=>C.toolCall?.id===a.getAttribute("data-tool-call-id"));h&&(nc(a,h,o,c+1),Lr(a))};Ss.addEventListener("click",a=>{let f=a.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let C=f.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),C==="dismiss"){let E=h.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),dr(Ss,E);let z=it.current?.getMessages().find($=>$.toolCall?.id===E);z?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved(z),it.current?.resolveAskUserQuestion(z,"(dismissed)"));return}if(C==="pick"){let E=f.getAttribute("data-option-label");if(!E)return;let z=h.getAttribute("data-multi-select")==="true",$=cr(h);if($&&z){let J=Qr(h)[zn(h)],q=new Set(Array.isArray(J)?J:[]);q.has(E)?q.delete(E):q.add(E),pr(h,Array.from(q)),Lr(h);return}if($){pr(h,E),Lr(h),Bd(h);return}if(z){let J=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",J?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!J);let q=h.querySelector('[data-ask-user-action="submit-multi"]');q&&(q.disabled=ou(h).length===0);return}As(h,E,{source:"pick",values:[E]});return}if(C==="submit-multi"){let E=ou(h);if(E.length===0)return;As(h,E.join(", "),{source:"multi",values:E});return}if(C==="open-free-text"){let E=h.querySelector('[data-ask-free-text-row="true"]');E&&(E.classList.remove("persona-hidden"),E.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(C==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(C==="submit-free-text"){let z=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!z.trim())return;if(cr(h)){pr(h,z.trim()),Lr(h),Bd(h);return}As(h,z,{source:"free-text"});return}if(C==="next"||C==="back"){if(!it.current)return;let E=h.getAttribute("data-tool-call-id")??"",z=it.current.getMessages().find(ie=>ie.toolCall?.id===E);if(!z)return;let J=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ie=Qr(h)[zn(h)];(typeof ie!="string"||ie!==J)&&pr(h,J)}let q=C==="next"?1:-1,ne=zn(h)+q;nc(h,z,o,ne),Lr(h);return}if(C==="submit-all"){if(!it.current)return;let E=h.getAttribute("data-tool-call-id")??"",z=it.current.getMessages().find(ie=>ie.toolCall?.id===E);if(!z)return;let J=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&pr(h,J);let q=tc(h,z);it.current.persistAskUserQuestionProgress(z,{answers:q,currentIndex:zn(h)});let ne=af(q);As(h,ne||"(submitted)",{source:"submit-all",structured:q});return}if(C==="skip"){if(!it.current)return;let E=h.getAttribute("data-tool-call-id")??"",z=it.current.getMessages().find(fe=>fe.toolCall?.id===E);if(!z)return;let $=cr(h),J=zn(h),q=Ys(h),ne=J>=q-1;if(!$){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:E},bubbles:!0,composed:!0})),dr(Ss,E),z.agentMetadata?.awaitingLocalTool&&(it.current.markAskUserQuestionResolved(z),it.current.resolveAskUserQuestion(z,"(dismissed)"));return}pr(h,"");let ie=h.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),ne){let fe=tc(h,z),Je=af(fe);As(h,Je||"(skipped)",{source:"submit-all",structured:fe});return}nc(h,z,o,J+1),Lr(h);return}}),Ss.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let f=a.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;a.preventDefault();let C=f.value;if(C.trim()){if(cr(h)){pr(h,C.trim()),Lr(h),Bd(h);return}As(h,C,{source:"free-text"})}});let lf=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let c=a.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=Ss.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let h=Number(a.key),E=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[h-1];E&&(a.preventDefault(),E.click())};document.addEventListener("keydown",lf);let no=null,yt=null,Ii=null,tl=null,Od=()=>{},cf=!1,nl="",ol="";function Dd(){tl?.(),tl=null}let $C=()=>{let a=qi&&Bs?.isConnected?Bs:null,c=a?a.getBoundingClientRect().width:0;return c<=0?200:c+360},df=()=>{if(!no||!yt)return;let a=e.classList.contains("persona-artifact-welded-split"),c=e.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!a||e.classList.contains("persona-artifact-narrow-host")||f){yt.style.removeProperty("position"),yt.style.removeProperty("left"),yt.style.removeProperty("top"),yt.style.removeProperty("bottom"),yt.style.removeProperty("width"),yt.style.removeProperty("z-index");return}let h=no.firstElementChild;if(!h||h===yt)return;let C=10;yt.style.position="absolute",yt.style.top="0",yt.style.bottom="0",yt.style.width=`${C}px`,yt.style.zIndex="5";let E=gg(no,c),z=h.offsetWidth+E/2-C/2;yt.style.left=`${Math.max(0,z)}px`},rl=()=>{},jC=()=>{let a=e.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||a.innerWidth>f?!1:j||Ct(o)},sl=()=>!gn(o)||!el()||e.classList.contains("persona-artifact-narrow-host")||jC()||(e.ownerDocument.defaultView??window).innerWidth<QE?"none":cg(o)?"detached":"welded",So=()=>{if(!_e||!gn(o))return;za(e,o),Ua(e,o),rl();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=O.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",c>0&&c<=a);let f=el();_e.setVisible(f),_e.update(Gn),xo?(_e.setMobileOpen(!1),_e.element.classList.add("persona-hidden"),_e.backdrop?.classList.add("persona-hidden"),Yn=!1,Hi=!1):Gn.artifacts.length>0&&sf()?(_e.element.classList.remove("persona-hidden"),_e.setMobileOpen(!0)):(_e.setMobileOpen(!1),_e.element.classList.add("persona-hidden"),_e.backdrop?.classList.add("persona-hidden"),Yn=!1,Hi=!1);let h=o.features?.artifacts?.layout?.showExpandToggle===!0;if(_e.setExpandToggleVisible(h),_e.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),_e.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),_e.setCustomActions(o.features?.artifacts?.toolbarActions??[]),_e.setTabFade(o.features?.artifacts?.layout?.tabFade),_e.setRenderTabBar(o.features?.artifacts?.renderTabBar),!h&&!Hi&&(Yn=!1),Yn!==cf){let E=_e.element;Yn?(nl=E.style.width,ol=E.style.maxWidth,E.style.removeProperty("width"),E.style.removeProperty("max-width")):(nl&&(E.style.width=nl),ol&&(E.style.maxWidth=ol),nl="",ol=""),cf=Yn}e.classList.toggle("persona-artifact-expanded",Yn),_e.setExpanded(Yn);let C=sl();C!==Li&&(Li=C,Pr()),Od()};if(gn(o)){O.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(G),_e=uv(o,{onSelect:f=>it.current?.selectArtifact(f),onDismiss:()=>{xo=!0,So()},onToggleExpand:()=>{let f=!Yn,h=Gn.selectedId??Gn.artifacts[Gn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:h,expanded:f})!==!0&&(Yn=f,f||(Hi=!1),So())}}),_e.element.classList.add("persona-hidden"),no=c,c.appendChild(a),c.appendChild(_e.element),_e.backdrop&&O.appendChild(_e.backdrop),O.appendChild(c),Od=()=>{if(!no||!_e)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Ii?.(),Ii=null,Dd(),yt&&(yt.remove(),yt=null),_e.element.style.removeProperty("width"),_e.element.style.removeProperty("maxWidth");return}if(!yt){let h=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");h.setAttribute("role","separator"),h.setAttribute("aria-orientation","vertical"),h.setAttribute("aria-label","Resize artifacts panel"),h.tabIndex=0;let C=e.ownerDocument,E=C.defaultView??window,z=$=>{if(!_e||$.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||E.innerWidth<=640)return;$.preventDefault(),Dd();let J=$.clientX,q=_e.element.getBoundingClientRect().width,ne=o.features?.artifacts?.layout,ie=Je=>{let vt=no.getBoundingClientRect().width,Vt=e.classList.contains("persona-artifact-welded-split"),bn=gg(no,E),Et=Vt?0:h.getBoundingClientRect().width||6,Pt=q-(Je.clientX-J),N=wv(Pt,vt,bn,Et,ne?.resizableMinWidth,ne?.resizableMaxWidth,$C());_e.element.style.width=`${N}px`,_e.element.style.maxWidth="none",df()},fe=()=>{C.removeEventListener("pointermove",ie),C.removeEventListener("pointerup",fe),C.removeEventListener("pointercancel",fe),tl=null;try{h.releasePointerCapture($.pointerId)}catch{}};tl=fe,C.addEventListener("pointermove",ie),C.addEventListener("pointerup",fe),C.addEventListener("pointercancel",fe);try{h.setPointerCapture($.pointerId)}catch{}};h.addEventListener("pointerdown",z),yt=h,no.insertBefore(h,_e.element),Ii=()=>{h.removeEventListener("pointerdown",z)}}if(yt){let h=el();yt.classList.toggle("persona-hidden",!h),df()}},rl=()=>{if(!j||!_e||(o.launcher?.sidebarMode??!1)||Ct(o)&&wn(o).reveal==="emerge")return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=E||!mv(o,j))return;let z=o.launcher?.width??o.launcherWidth??Hn,$=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";el()?(O.style.width=$,O.style.maxWidth=$):(O.style.width=z,O.style.maxWidth=z)},typeof ResizeObserver<"u"&&(Pi=new ResizeObserver(()=>{So()}),Pi.observe(O))}else O.appendChild(G);le()&&Y&&(Q.peekBanner&&Y.appendChild(Q.peekBanner),Y.appendChild($e)),e.appendChild(L),Y&&e.appendChild(Y);let _d=()=>{if(le()){O.style.width="100%",O.style.maxWidth="100%";let Ht=o.launcher?.composerBar??{},dn=L.dataset.state==="expanded",sa=Ht.expandedSize??"anchored";if(!(dn&&sa!=="fullscreen")){G.style.background="",G.style.border="",G.style.borderRadius="",G.style.overflow="",G.style.boxShadow="";return}let ia=o.theme?.components?.panel,Zm=yr(o),ql=(Yr,Kl)=>Yr==null||Yr===""?Kl:pn(Zm,Yr)??Yr,Dt="1px solid var(--persona-border)",qp="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Vl="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";G.style.background="var(--persona-surface, #ffffff)",G.style.border=ql(ia?.border,Dt),G.style.borderRadius=ql(ia?.borderRadius,Vl),G.style.boxShadow=ql(ia?.shadow,qp),G.style.overflow="hidden";return}let a=Ct(o),c=o.launcher?.sidebarMode??!1,f=a||c||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,C=o.launcher?.detachedPanel===!0,E=o.theme?.components?.panel,z=yr(o),$=(Ht,dn)=>Ht==null||Ht===""?dn:pn(z,Ht)??Ht,J=e.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,ne=o.launcher?.mobileBreakpoint??640,ie=J.innerWidth<=ne,fe=q&&ie&&j,Je=a&&q&&ie,vt=o.launcher?.position??"bottom-left",Vt=vt==="bottom-left"||vt==="top-left",bn=o.launcher?.zIndex??Xt,Et="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",N="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=C&&!fe&&!Je;Pe?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Ie=Pe?Et:c||fe?"none":Et,Te=Pe?Pt:fe?"none":c?Vt?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":h?"none":Pt;a&&!fe&&!Pe&&(Te="none",Ie="none");let Mt=Pe?N:c||fe?"0":N,pt=$(E?.border,Ie),Kt=$(E?.shadow,Te),ct=$(E?.borderRadius,Mt),ln=sl(),Yt=ln==="detached",jt=ln==="welded";e.classList.toggle("persona-artifact-detached-split",Yt),e.classList.toggle("persona-artifact-welded-split",jt);let Re="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)))))",Me=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&gn(o)&&cg(o)&&h&&!a;e.classList.toggle("persona-artifact-chat-flush",Me);let Bt=Yt||Me?"none":Kt,ut=Yt?Et:jt?"none":pt,Ve=Yt?N:ct;Me&&(ut="none",Ve="0");let Ot=E?.borderRadius!=null&&E.borderRadius!=="",Lt=Me&&!Ot?"0":ct,tn=K.scrollTop;e.style.cssText="",L.style.cssText="",O.style.cssText="",G.style.cssText="",K.style.cssText="",Mi||($e.style.cssText=""),Gt&&(K.style.display="none"),(f||h)&&(e.style.minWidth="0");let $n=()=>{if(tn<=0)return;(K.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(K.scrollTop===tn)return;let dn=K.scrollHeight-K.clientHeight;dn<=0||(K.scrollTop=Math.min(tn,dn))})};if(fe){L.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"),L.style.cssText=`
49
49
  position: fixed !important;
50
50
  inset: 0 !important;
51
51
  width: 100% !important;
@@ -55,9 +55,9 @@ _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]
55
55
  padding: 0 !important;
56
56
  display: flex !important;
57
57
  flex-direction: column !important;
58
- z-index: ${cn} !important;
58
+ z-index: ${bn} !important;
59
59
  background-color: var(--persona-surface, #ffffff) !important;
60
- `,xe.style.cssText=`
60
+ `,O.style.cssText=`
61
61
  position: relative !important;
62
62
  display: flex !important;
63
63
  flex-direction: column !important;
@@ -70,7 +70,7 @@ _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]
70
70
  padding: 0 !important;
71
71
  box-shadow: none !important;
72
72
  border-radius: 0 !important;
73
- `,we.style.cssText=`
73
+ `,G.style.cssText=`
74
74
  display: flex !important;
75
75
  flex-direction: column !important;
76
76
  flex: 1 1 0% !important;
@@ -81,33 +81,33 @@ _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]
81
81
  overflow: hidden !important;
82
82
  border-radius: 0 !important;
83
83
  border: none !important;
84
- `,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Te.style.flexShrink="0",J=!0,xn();return}let ci=o?.launcher?.width??o?.launcherWidth??pn;if(!u&&!l)v&&m?(xe.style.width="100%",xe.style.maxWidth="100%"):(xe.style.width=ci,xe.style.maxWidth=ci);else if(l)if(rn(o).reveal==="emerge"&&!w){let nn=rn(o).width;xe.style.width=nn,xe.style.maxWidth=nn}else xe.style.width="100%",xe.style.maxWidth="100%";if(qa(),xe.style.boxShadow=ct,xe.style.borderRadius=vt,Bt?xe.style.border="none":He&&(xe.style.border=ft),we.style.border=ht,we.style.borderRadius=Xe,we.style.boxShadow=Bt&&!St?_e:"",St&&(we.style.background="transparent",ae.style.background="transparent",Te.style.background="transparent",Te.style.borderTop="none"),He){let Rt=o.features?.artifacts?.layout;_a=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||mt}else _a=null;if(l&&!Ce&&!We&&!Bt&&!He&&L?.border===void 0&&(we.style.border="none",rn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&He&&L?.border===void 0&&(rn(o).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.style.borderRight="1px solid var(--persona-border)"),m&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),Le.style.display="flex",Le.style.flexDirection="column",Le.style.flex="1 1 0%",Le.style.minHeight="0",Le.style.maxHeight="100%",Le.style.height="100%",v&&(Le.style.overflow="hidden"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",Bt||(xe.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Te.style.flexShrink="0"),v&&(We||Bt||St)&&!l&&(St||(Le.style.padding="var(--persona-panel-inset)"),Le.style.background="var(--persona-panel-canvas-bg)"),Le.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"),!u&&!v&&!l&&(un[bt]??un["bottom-right"]).split(" ").forEach(nn=>Le.classList.add(nn)),u){let Rt=o.launcher?.sidebarWidth??"420px";w?Le.style.cssText=`
84
+ `,K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",$e.style.flexShrink="0",oe=!0,$n();return}let nn=o?.launcher?.width??o?.launcherWidth??Hn;if(!c&&!a)h&&f?(O.style.width="100%",O.style.maxWidth="100%"):(O.style.width=nn,O.style.maxWidth=nn);else if(a)if(wn(o).reveal==="emerge"&&!C){let dn=wn(o).width;O.style.width=dn,O.style.maxWidth=dn}else O.style.width="100%",O.style.maxWidth="100%";if(rl(),O.style.boxShadow=Bt,O.style.borderRadius=Lt,Yt?O.style.border="none":jt&&(O.style.border=pt),G.style.border=ut,G.style.borderRadius=Ve,G.style.boxShadow=Yt&&!Me?Re:"",Me&&(G.style.background="transparent",K.style.background="transparent",$e.style.background="transparent",$e.style.borderTop="none"),jt){let Ht=o.features?.artifacts?.layout;Za=Ht?.unifiedSplitOuterRadius?.trim()||Ht?.paneBorderRadius?.trim()||ct}else Za=null;if(a&&!fe&&!Pe&&!Yt&&!jt&&E?.border===void 0&&(G.style.border="none",wn(o).side==="right"?G.style.borderLeft="1px solid var(--persona-border)":G.style.borderRight="1px solid var(--persona-border)"),a&&!fe&&jt&&E?.border===void 0&&(wn(o).side==="right"?O.style.borderLeft="1px solid var(--persona-border)":O.style.borderRight="1px solid var(--persona-border)"),f&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",h&&(e.style.width="100%"),L.style.display="flex",L.style.flexDirection="column",L.style.flex="1 1 0%",L.style.minHeight="0",L.style.maxHeight="100%",L.style.height="100%",h&&(L.style.overflow="hidden"),O.style.display="flex",O.style.flexDirection="column",O.style.flex="1 1 0%",O.style.minHeight="0",O.style.maxHeight="100%",O.style.height="100%",Yt||(O.style.overflow="hidden"),G.style.display="flex",G.style.flexDirection="column",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.maxHeight="100%",G.style.overflow="hidden",K.style.flex="1 1 0%",K.style.minHeight="0",K.style.overflowY="auto",$e.style.flexShrink="0"),h&&(Pe||Yt||Me)&&!a&&(Me||(L.style.padding="var(--persona-panel-inset)"),L.style.background="var(--persona-panel-canvas-bg)"),L.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!c&&!h&&!a&&(In[vt]??In["bottom-right"]).split(" ").forEach(dn=>L.classList.add(dn)),c){let Ht=o.launcher?.sidebarWidth??"420px";C?L.style.cssText=`
85
85
  position: fixed !important;
86
86
  top: var(--persona-panel-inset) !important;
87
87
  bottom: var(--persona-panel-inset) !important;
88
- width: ${Rt} !important;
88
+ width: ${Ht} !important;
89
89
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
90
90
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
91
91
  margin: 0 !important;
92
92
  padding: 0 !important;
93
93
  display: flex !important;
94
94
  flex-direction: column !important;
95
- z-index: ${cn} !important;
96
- ${gt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
97
- `:Le.style.cssText=`
95
+ z-index: ${bn} !important;
96
+ ${Vt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
97
+ `:L.style.cssText=`
98
98
  position: fixed !important;
99
99
  top: 0 !important;
100
100
  bottom: 0 !important;
101
- width: ${Rt} !important;
101
+ width: ${Ht} !important;
102
102
  height: 100vh !important;
103
103
  max-height: 100vh !important;
104
104
  margin: 0 !important;
105
105
  padding: 0 !important;
106
106
  display: flex !important;
107
107
  flex-direction: column !important;
108
- z-index: ${cn} !important;
109
- ${gt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
110
- `,xe.style.cssText=`
108
+ z-index: ${bn} !important;
109
+ ${Vt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
110
+ `,O.style.cssText=`
111
111
  position: relative !important;
112
112
  display: flex !important;
113
113
  flex-direction: column !important;
@@ -118,10 +118,10 @@ _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]
118
118
  min-height: 0 !important;
119
119
  margin: 0 !important;
120
120
  padding: 0 !important;
121
- box-shadow: ${ct} !important;
122
- border-radius: ${vt} !important;
123
- ${Bt?"border: none !important;":He?`border: ${ft} !important;`:""}
124
- `,xe.style.setProperty("width","100%","important"),xe.style.setProperty("max-width","100%","important"),we.style.cssText=`
121
+ box-shadow: ${Bt} !important;
122
+ border-radius: ${Lt} !important;
123
+ ${Yt?"border: none !important;":jt?`border: ${pt} !important;`:""}
124
+ `,O.style.setProperty("width","100%","important"),O.style.setProperty("max-width","100%","important"),G.style.cssText=`
125
125
  display: flex !important;
126
126
  flex-direction: column !important;
127
127
  flex: 1 1 0% !important;
@@ -130,32 +130,32 @@ _Details: ${n.message}_`:o}var da=e=>({isError:!0,content:[{type:"text",text:e}]
130
130
  min-height: 0 !important;
131
131
  max-height: 100% !important;
132
132
  overflow: hidden !important;
133
- border-radius: ${Xe} !important;
134
- border: ${ht} !important;
135
- ${Bt&&!St?`box-shadow: ${_e} !important;`:""}
136
- ${St?"background: transparent !important;":""}
137
- `,Te.style.cssText=`
133
+ border-radius: ${Ve} !important;
134
+ border: ${ut} !important;
135
+ ${Yt&&!Me?`box-shadow: ${Re} !important;`:""}
136
+ ${Me?"background: transparent !important;":""}
137
+ `,Mi||($e.style.cssText=`
138
138
  flex-shrink: 0 !important;
139
139
  border-top: none !important;
140
140
  padding: 8px 16px 12px 16px !important;
141
- ${St?"background: transparent !important;":""}
142
- `}if(!v&&!l){let Rt="max-height: -moz-available !important; max-height: stretch !important;",nn=u?"":"padding-top: 1.25em !important;",di=u?"":`z-index: ${o.launcher?.zIndex??$t} !important;`;Le.style.cssText+=Rt+nn+di}xn()},tc=()=>{e.style.setProperty("--persona-content-max-width",$o(o,Z()))},_p=()=>{if(Z())return;let l=Mt(o),u=o.launcher?.sidebarMode??!1;if(l||u||(o.launcher?.fullHeight??!1)||!N)return;let v=e.ownerDocument.defaultView??window,w=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(w&&v.innerWidth<=L)return;let U=v.innerHeight,F=64,V=o.launcher?.heightOffset??0,Q=Math.max(200,U-F),fe=Math.min(640,Q);xe.style.height=`${Math.max(200,fe-V)}px`};ec(),Ar(e,o),La(e,o),Pa(e,o),tc(),Zo=()=>{ec(),_p(),Ar(e,o),La(e,o),Pa(e,o),tc(),_a?e.style.setProperty("--persona-artifact-welded-outer-radius",_a):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ne=[];Ne.push(()=>{document.removeEventListener("keydown",Op)}),Ne.push(()=>{Ls!==null&&clearTimeout(Ls)});let On=null,Nn=null;Ne.push(()=>{On?.(),On=null,Nn?.(),Nn=null}),Is&&Ne.push(()=>{Is?.disconnect(),Is=null}),Ne.push(()=>{Bs?.(),Bs=null,Zl(),wt&&(wt.remove(),wt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),me&&Ne.push(()=>{Ie!==null&&(cancelAnimationFrame(Ie),Ie=null),Ae?.destroy(),Ae=null,Pe?.destroy(),Pe=null,je=null});let tr=null,$p=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=ps(()=>{Ar(e,o)}))};$p(),Ne.push(()=>{tr&&(tr(),tr=null)}),Ne.push(d);let Ka=o.features?.streamAnimation;if(Ka?.type&&Ka.type!=="none"){let l=ms(Ka.type,Ka.plugins);l&&(al(l,e),Ne.push(()=>am(e)))}let Gn=Sa(M),jp=Sa(Tn),Up=Sa(oe),nr=[Gn,jp,Up];Ne.push(()=>{nr.forEach(l=>l.destroy())});let or=null,_,rr=null,zp=!1,qp=0,Vp=null,Kp=l=>l.reduce((u,m)=>m.role==="user"?u+1:u,0),Gp=l=>{for(let u=l.length-1;u>=0;u--)if(br(l[u]))return l[u].id??null;return null},Jp=!1,ay=()=>{Jp||o.debug!==!0||(Jp=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Yp=!1,Xp=!1,Qp=(l,u)=>{Yp||o.debug!==!0||!u.enabled||u.expose||zp||Xp&&(_.isStreaming()||l.some(br)||(Yp=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Nr=l=>{if(!_)return;let u=l??_.getMessages(),m=Q=>{Q.render([],_,W,u)},v=Q=>{nr.forEach(fe=>{fe!==Q&&m(fe)})};rr&&(Kp(u)>qp||Gp(u)!==Vp)&&(rr=null);let w=Ho(o);Qp(u,w);let L=w.enabled?wi(u):null,U=rr??L,F=rr?"host":"agent";if(U){let Q=o.suggestions?.followUps,fe=Q?.placement??(Q?"auto":"composer"),Ce=(fe==="auto"?Z()?"composer":"after-message":fe)==="after-message"?Up:Gn;v(Ce),Ce.render(U,_,W,u,o.suggestionChipsConfig,{source:F,surface:"followUp",variant:Q?.variant??"chip",behavior:Q?.behavior??"send",overflow:Q?.overflow??"wrap",maxItems:Q?.maxItems??4,config:o,plugins:s});return}if(u.some(Q=>Q.role==="user")){nr.forEach(m);return}let V=o.suggestions?.starters;if(V){let Q=Go(go(o),u),fe=V.placement??"auto",de=fe==="auto"?Q?"welcome":"composer":fe;if(de==="welcome"&&!Q){ay(),nr.forEach(m);return}let Ce=de==="welcome"?jp:Gn;v(Ce),Ce.render(V.items??o.suggestionChips,_,W,u,o.suggestionChipsConfig,{surface:"starter",variant:V.variant??"card",behavior:V.behavior??"send",overflow:V.overflow??"wrap",maxItems:V.maxItems??4,config:o,plugins:s});return}v(Gn),Gn.render(o.suggestionChips,_,W,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},Zp=()=>{rr&&(rr=null,Nr())},iy=l=>{let u=Array.isArray(l)?[...l]:[];if(!u.length){Zp();return}let m=_?_.getMessages():[];rr=u,zp=!0,qp=Kp(m),Vp=Gp(m),Nr(m)},Ln=!1,sr=Gf(),Fr=new Map,ar=new Map,bo=new Map,nc=0,ly=no()!==null,an=el(),ln=0,vo=null,en=!1,Ga=!1,xo=0,Ot=null,ir=null,oc=!1,Ja=!1,lr=null,Ds=!0,Ya=!1,_r=null,Xa=!1,cr=()=>{Xa=!0,uy()},rc=null,cy=4,Jn=24,dy=80,py=1e3,Yn=null,eu=()=>{e.setAttribute("data-persona-scrollbar",zl()),zl()!=="on-scroll"&&(Yn!==null&&clearTimeout(Yn),Yn=null,ae.removeAttribute("data-persona-scrollbar-visible"))},uy=()=>{zl()==="on-scroll"&&(ae.setAttribute("data-persona-scrollbar-visible",""),Yn!==null&&clearTimeout(Yn),Yn=setTimeout(()=>{Yn=null,po(ae,Jn)&&ae.removeAttribute("data-persona-scrollbar-visible")},py))};eu(),Ne.push(()=>{Yn!==null&&clearTimeout(Yn)});let sc=new Map,Ge={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},tu=o.voiceRecognition?.autoResume??!1,Xn=l=>{c.emit("voice:state",{active:Ge.active,source:l,timestamp:Date.now()})},Pn=()=>{R(l=>({...l,voiceState:{active:Ge.active,timestamp:Date.now(),manuallyDeactivated:Ge.manuallyDeactivated}}))},gy=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=Zd(f.voiceState),u=!!l.active,m=Number(l.timestamp??0);Ge.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-m<fw&&setTimeout(()=>{Ge.active||(Ge.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Xn("restore"),_.isVoiceActive()&&Vr()}):ai("restore"))},1e3)},fy=()=>_?ih(_.getMessages()).filter(l=>!l.__skipPersist):[],Qa=null,nu=(l,u)=>{typeof console<"u"&&console.error(l,u)},ac=(l,u)=>{let m=()=>{try{let U=l();return!U||typeof U.then!="function"?null:Promise.resolve(U).catch(F=>{nu(u,F)})}catch(U){return nu(u,U),null}},v=Qa,w=v?v.then(()=>m()??void 0):m();if(!w)return;let L=w.finally(()=>{Qa===L&&(Qa=null)});Qa=L};function ic(l){if(!b?.save)return;let m={messages:l?ih(l):_?fy():[],metadata:f,artifacts:Mn.artifacts,selectedArtifactId:Mn.selectedId};ac(()=>b.save(m),"[AgentWidget] Failed to persist state:")}let $r=null,ou=()=>Le.querySelector("#persona-scroll-container")||ae,jr=()=>{$r!==null&&(cancelAnimationFrame($r),$r=null),en=!1},ru=()=>{vo!==null&&(cancelAnimationFrame(vo),vo=null),Ga=!1,jr()},my=()=>Ln&&cc()&&(sn()!=="anchor-top"||bp()),lc=()=>{let l=Es()||"Jump to latest",u=my();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),xo>0?(Yo.textContent=String(xo),Yo.style.display="",It.setAttribute("aria-label",`${l} (${xo} new)`)):(Yo.textContent="",Yo.style.display="none",It.setAttribute("aria-label",u?`${l} (response streaming below)`:l))},su=()=>{xo!==0&&(xo=0,lc())},hy=()=>{let l=Ot?.spacerHeight??0;return l<=0?po(ae,Jn):ti(l)-ae.scrollTop-ae.clientHeight<=Jn},cc=()=>ho()?!an.isFollowing():!hy(),dc=()=>!!_&&_.getMessages().length>0,Ut=()=>{if(!ey()||ie){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==we&&we.appendChild(It),Qo();let u=Un(ae)>0&&cc()&&dc();u?lc():su(),It.style.display=u?"":"none"},Os=()=>{an.pause()&&(ru(),Ut())},Co=()=>{an.resume(),su(),Ut()},wo=(l=!1)=>{ho()&&dc()&&an.isFollowing()&&(!l&&!Ln||(vo!==null&&(cancelAnimationFrame(vo),vo=null),Ga=!0,vo=requestAnimationFrame(()=>{vo=null,Ga=!1,an.isFollowing()&&yy(ou(),l?220:140)})))},au=(l,u,m,v=()=>!0)=>{let w=l.scrollTop,L=u(),U=L-w;if(jr(),Math.abs(U)<1){en=!0,l.scrollTop=L,ln=l.scrollTop,en=!1;return}let F=performance.now();en=!0;let V=fe=>1-Math.pow(1-fe,3),Q=fe=>{if(!v()){jr();return}let de=u();de!==L&&(L=de,U=L-w);let Ce=fe-F,Je=Math.min(Ce/m,1),bt=V(Je),gt=w+U*bt;l.scrollTop=gt,ln=l.scrollTop,Je<1?$r=requestAnimationFrame(Q):(l.scrollTop=L,ln=l.scrollTop,$r=null,en=!1)};$r=requestAnimationFrame(Q)},yy=(l,u=500)=>{let m=Un(l)-l.scrollTop;if(Math.abs(m)<1){ln=l.scrollTop;return}if(Math.abs(m)>=dy){jr(),en=!0,l.scrollTop=Un(l),ln=l.scrollTop,en=!1;return}au(l,()=>Un(l),u,()=>an.isFollowing())},iu=()=>{if(!dc()){Ut();return}let l=ou();en=!0,l.scrollTop=Un(l),ln=l.scrollTop,en=!1,Ut()},dr=l=>{let u=0,m=l;for(;m&&m!==ae;)u+=m.offsetTop,m=m.offsetParent;return u},by=()=>{let l=ae.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??ae.ownerDocument.getSelection()},Za=()=>Zf(by(),ae),lu=()=>{if(ty()!=="last-user-turn")return!1;let l=_?.getMessages()??[];if(l.length<2)return!1;let u=[...l].reverse().find(L=>L.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ae.querySelector(`[data-message-id="${m}"]`);if(!v)return!1;let w=Math.min(Math.max(0,dr(v)-Ms()),Un(ae));return en=!0,ae.scrollTop=w,ln=ae.scrollTop,en=!1,sn()==="follow"&&!po(ae,Jn)&&an.pause(),Ut(),!0},ei=l=>{let u=Math.max(0,Math.round(l));yn.style.height=`${u}px`,yn.style.display=u>0?"":"none",Ot&&(Ot.spacerHeight=Math.max(0,l))},ti=l=>{let u=parseFloat(getComputedStyle(ae).paddingBottom)||0,m=0;for(let w of Array.from(ae.children)){if(w===yn||w.offsetHeight===0)continue;let L=dr(w)+w.offsetHeight;L>m&&(m=L)}let v=ae.scrollHeight-l;return m>0?Math.min(m+u,v):v},vy=()=>{if(!Ot||Ot.spacerHeight<=0)return;let l=ti(Ot.spacerHeight),u=Math.max(0,Math.round(ae.scrollTop)+ae.clientHeight-l+Jn);u<Ot.spacerHeight&&(ei(u),Ut())},Ns=()=>{ir!==null&&(cancelAnimationFrame(ir),ir=null),jr(),Ot=null,yn.style.height="0px",yn.style.display="none"},cu=l=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),pc=l=>ae.querySelector(`[data-message-id="${cu(l)}"]`),du=l=>{ir!==null&&cancelAnimationFrame(ir),ir=requestAnimationFrame(()=>{ir=null;let u=cu(l),m=ae.querySelector(`[data-message-id="${u}"]`);if(!m)return;let v=dr(m),w=Ot?.spacerHeight??0,L=ti(w),{targetScrollTop:U,spacerHeight:F}=bd({anchorOffsetTop:v,topOffset:Ms(),viewportHeight:ae.clientHeight,contentHeight:L,slack:Jn});Ot={initialSpacerHeight:F,contentHeightAtAnchor:L,spacerHeight:F},ei(F),au(ae,()=>m.isConnected?Math.max(0,dr(m)-Ms()):U,220)})},pu=()=>{if(sn()!=="anchor-top"||!Ot||!_r)return;let l=pc(_r);if(!l)return;jr();let u=Ot.spacerHeight,m=ti(u),{targetScrollTop:v,spacerHeight:w}=bd({anchorOffsetTop:dr(l),topOffset:Ms(),viewportHeight:ae.clientHeight,contentHeight:m,slack:Jn});Ot={initialSpacerHeight:w,contentHeightAtAnchor:m,spacerHeight:w},ei(w),en=!0,ae.scrollTop=v,ln=ae.scrollTop,en=!1,Ut()},xy=()=>{if(ho()){if(!an.isFollowing()||po(ae,1))return;wo(!Ln);return}if(Ot&&Ot.initialSpacerHeight>0){let l=ae.scrollHeight-Ot.spacerHeight,u=em({initialSpacerHeight:Ot.initialSpacerHeight,contentHeightAtAnchor:Ot.contentHeightAtAnchor,currentContentHeight:l});u!==Ot.spacerHeight&&ei(u)}Ut()},Cy=l=>{let u=sn();u==="follow"?(Co(),wo(!0)):u==="anchor-top"&&(Ds=!1,Ya=!0,Xa=!1,_r=l,du(l))},wy=()=>{if(sn()==="anchor-top"){if(Ya){Ds=!1;return}Ds=!0,Ns(),Co(),wo(!0)}},Ay=96,Sy=l=>{if(lr===null)return!0;let u=pc(lr),m=pc(l);if(!u||!m)return!0;let v=dr(m)-dr(u);return Ms()+v>ae.clientHeight-Ay},Ty=l=>{if(sn()!=="anchor-top"||!Ya||Xa||Za())return;let u=lr===null;for(let m of l){if(!u){m.id===lr&&(u=!0);continue}if(Qf(m)){if(m.id===_r||!Sy(m.id))return;_r=m.id,du(m.id);return}}},Ey=l=>{let u=new Map;l.forEach(m=>{let v=sc.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!v&&m.role==="assistant"&&(c.emit("assistant:message",m),!Ja&&(sn()!=="anchor-top"||bp())&&cc()&&(xo+=1,lc(),Ut(),xp(xo===1?"1 new message below.":`${xo} new messages below.`))),m.role==="assistant"&&v?.streaming&&m.streaming===!1&&c.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(v?m.approval.status!=="pending"&&c.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):c.emit("approval:requested",{approval:m.approval,message:m}))}),sc.clear(),u.forEach((m,v)=>{sc.set(v,m)})},ni=(l,u)=>{let m=u==="user"?"user":"assistant",v=o.layout?.messages?.[m],w=v?.width??"content",L=v?.maxWidth??(w==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${u}`,`persona-message-width-${w}`),l.classList.toggle("persona-justify-end",u==="user"),l.setAttribute("data-message-role",u),l.setAttribute("data-message-width",w),l.style.setProperty("--persona-message-row-max-width",L)},pr=(l,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${l}`,m.setAttribute("data-wrapper-id",l),ni(m,u),m},My=(l,u,m)=>{let v=document.createElement("div"),L=(()=>{let O=s.find(We=>We.renderLoadingIndicator);if(O?.renderLoadingIndicator)return O.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),U=(O,We)=>We==null?!1:typeof We=="string"?(O.textContent=We,!0):(O.appendChild(We),!0),F=new Set,V=new Map,Q=new Set,fe=s.some(O=>O.renderAskUserQuestion),de=[],Ce=[],Je=o.enableComponentStreaming!==!1,bt=o.approval!==!1,gt=[];if(u.forEach(O=>{F.add(O.id),V.set(O.id,O.role);let We=fe&&oo(O),Fe=bt&&O.variant==="approval"&&!!O.approval,Me=!We&&O.role==="assistant"&&!O.variant&&Je&&Ba(O);!Fe&&bo.has(O.id)&&(l.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(O.id)),!Me&&ar.has(O.id)&&(l.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),ar.delete(O.id));let Et=oo(O)?`:${O.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${O.agentMetadata?.askUserQuestionAnswers?Object.keys(O.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=Kf(O,nc)+Et,Ft=We||Fe||Me?null:Jf(sr,O.id,ft);if(Ft){v.appendChild(Ft.cloneNode(!0)),oo(O)&&O.toolCall?.id&&O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(Q.add(O.toolCall.id),rs(O,o,Ee.composerOverlay));return}let mt=null,tn=s.find(_e=>!!(O.variant==="reasoning"&&_e.renderReasoning||O.variant==="tool"&&_e.renderToolCall||!O.variant&&_e.renderMessage)),Bt=o.layout?.messages;if(oo(O)&&O.agentMetadata?.askUserQuestionAnswered===!0){Fr.delete(O.id),l.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime");return}if(br(O)&&Ho(o).enabled)return;if(oo(O)&&o.features?.askUserQuestion?.enabled!==!1){let _e=s.find(zt=>typeof zt.renderAskUserQuestion=="function");if(_e&&lt.current){let zt=Fr.get(O.id),qt=zt!==ft,St=null;if(qt){let{payload:Xe,complete:Oe}=ro(O),vt=O.id,Vt=()=>lt.current?.getMessages().find(xn=>xn.id===vt);St=_e.renderAskUserQuestion({message:O,payload:Xe,complete:Oe,resolve:xn=>{let Js=Vt();Js&&lt.current?.resolveAskUserQuestion(Js,xn)},dismiss:()=>{let xn=Vt();xn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(xn),lt.current?.resolveAskUserQuestion(xn,"(dismissed)"))},config:o})}let ct=zt!=null;if(qt&&St===null&&!ct){O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(Q.add(O.toolCall.id),rs(O,o,Ee.composerOverlay));return}let ht=pr(O.id,O.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),v.appendChild(ht),de.push({messageId:O.id,fingerprint:ft,bubble:St});return}else{O.agentMetadata?.awaitingLocalTool===!0&&!O.agentMetadata?.askUserQuestionAnswered&&(Q.add(O.toolCall.id),rs(O,o,Ee.composerOverlay));return}}else if(Fe){let _e=s.find(ct=>typeof ct.renderApproval=="function")??p,qt=bo.get(O.id)!==ft,St=null;if(qt&&_e?.renderApproval){let ct=O.id,ht=(Xe,Oe)=>{let vt=lt.current?.getMessages().find(Vt=>Vt.id===ct);vt?.approval&&(vt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(vt.id,Xe):lt.current?.resolveApproval(vt.approval,Xe,Oe))};St=_e.renderApproval({message:O,defaultRenderer:()=>Cl(O,o),config:o,approve:Xe=>ht("approved",Xe),deny:Xe=>ht("denied",Xe)})}if(qt&&St===null)l.querySelector(`#wrapper-${O.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(O.id),mt=Cl(O,o);else{let ct=pr(O.id,O.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),v.appendChild(ct),gt.push({messageId:O.id,fingerprint:ft,bubble:St});return}}else if(tn)if(O.variant==="reasoning"&&O.reasoning&&tn.renderReasoning){if(!ge)return;mt=tn.renderReasoning({message:O,defaultRenderer:()=>Nd(O,o),config:o})}else if(O.variant==="tool"&&O.toolCall&&tn.renderToolCall){if(!ne)return;mt=tn.renderToolCall({message:O,defaultRenderer:()=>_d(O,o),config:o})}else tn.renderMessage&&(mt=tn.renderMessage({message:O,defaultRenderer:()=>{let _e=ys(O,m,Bt,o.messageActions,tt,{loadingIndicatorRenderer:L,widgetConfig:o});return O.role!=="user"&&Yd(_e,O,o,_),_e},config:o}));if(!mt&&Me){let _e=Pl(O);if(_e){let zt=ar.get(O.id),qt=zt!==ft,St=o.wrapComponentDirectiveInBubble!==!1&&Dn.getOptions(_e.component)?.bubbleChrome!==!1,ct=null;if(qt){let ht=Ll(_e,{config:o,message:O,transform:m});if(ht&&_e.component==="PersonaArtifactInline"){let Xe=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),Oe=Xe?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Oe):Oe,Vt=Oe?l.querySelector(`#wrapper-${O.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;Xe&&Vt&&Vt!==Xe&&$f(Vt)&&(Xe===ht?ht=Vt:Xe.replaceWith(Vt))}if(ht)if(St){let Xe=document.createElement("div");if(Xe.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Xe.id=`bubble-${O.id}`,Xe.setAttribute("data-message-id",O.id),O.content&&O.content.trim()){let Oe=document.createElement("div");Oe.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Oe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Xe.appendChild(Oe)}Xe.appendChild(ht),ct=Xe}else{let Xe=document.createElement("div");if(Xe.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Xe.id=`bubble-${O.id}`,Xe.setAttribute("data-message-id",O.id),Xe.setAttribute("data-persona-component-directive","true"),O.content&&O.content.trim()){let Oe=document.createElement("div");Oe.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Oe.innerHTML=m({text:O.content,message:O,streaming:!!O.streaming,raw:O.rawContent}),Xe.appendChild(Oe)}Xe.appendChild(ht),ct=Xe}}if(ct||zt!=null){let ht=pr(O.id,O.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),v.appendChild(ht),Ce.push({messageId:O.id,fingerprint:ft,bubble:ct});return}}}if(!mt)if(O.variant==="reasoning"&&O.reasoning){if(!ge)return;mt=Nd(O,o)}else if(O.variant==="tool"&&O.toolCall){if(!ne)return;mt=_d(O,o)}else if(O.variant==="approval"&&O.approval){if(o.approval===!1)return;mt=Cl(O,o)}else{let _e=o.layout?.messages;_e?.renderUserMessage&&O.role==="user"?mt=_e.renderUserMessage({message:O,config:o,streaming:!!O.streaming}):_e?.renderAssistantMessage&&O.role==="assistant"?mt=_e.renderAssistantMessage({message:O,config:o,streaming:!!O.streaming}):mt=ys(O,m,_e,o.messageActions,tt,{loadingIndicatorRenderer:L,widgetConfig:o}),O.role!=="user"&&mt&&Yd(mt,O,o,_)}let He=pr(O.id,O.role);He.appendChild(mt),Yf(sr,O.id,ft,He),v.appendChild(He)}),Ee.composerOverlay&&Ee.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(We=>{let Fe=We.getAttribute("data-persona-ask-sheet-for");Fe&&!Q.has(Fe)&&Io(Ee.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let O=[],We=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Me=>{if(Me.variant==="tool"&&Me.toolCall&&ne){We.push(Me);return}Me.variant==="reasoning"&&!ge||((We.length>1||Fe&&We.length>0)&&O.push(We),We=[])}),(We.length>1||Fe&&We.length>0)&&O.push(We),O.forEach(Me=>{let Et=Me.map(_e=>Array.from(v.children).find(zt=>zt instanceof HTMLElement&&zt.getAttribute("data-wrapper-id")===_e.id)).filter(_e=>!!_e);if(Et.length<(Fe?1:2))return;let ft=pr(`tool-group-${Me[0].id}`,"assistant");ft.setAttribute("data-persona-tool-group-row","true");let Ft=document.createElement("div");Ft.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ft.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",mt.id=`tool-group-summary-${Me[0].id}`;let tn=`Called ${Me.length} ${Me.length===1?"tool":"tools"}`,Bt=o.toolCall?.renderGroupedSummary?.({messages:Me,toolCalls:Me.map(_e=>_e.toolCall).filter(_e=>!!_e),defaultSummary:tn,config:o});U(mt,Bt)||(mt.textContent=tn);let He=document.createElement("div");He.className="persona-tool-group-stack persona-flex persona-flex-col",He.id=`tool-group-stack-${Me[0].id}`,He.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(mt),Fe||Ft.appendChild(He),ft.appendChild(Ft),Et[0].before(ft),Et.forEach((_e,zt)=>{if(Fe){_e.remove();return}_e.style.setProperty("--persona-message-row-max-width","100%");let qt=document.createElement("div");qt.className="persona-tool-group-item persona-relative",qt.setAttribute("data-persona-tool-group-item","true"),zt<Et.length-1&&qt.setAttribute("data-persona-tool-group-connector","true"),qt.appendChild(_e),He.appendChild(qt)})})}Xf(sr,F);let cn=u.some(O=>O.role==="assistant"&&O.streaming),kt=u[u.length-1],Ht=kt?.role==="assistant"&&!kt.streaming&&kt.variant!=="approval";if(Ln&&u.some(O=>O.role==="user")&&!cn&&!Ht){let O={config:o,streaming:!0,location:"standalone",defaultRenderer:kr},We=s.find(Me=>Me.renderLoadingIndicator),Fe=null;if(We?.renderLoadingIndicator&&(Fe=We.renderLoadingIndicator(O)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(O)),Fe===null&&(Fe=kr()),Fe){let Me=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1,ft=o.layout?.messages?.layout??"bubble";Me.className=Et?Ta("assistant",ft).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Me.setAttribute("data-typing-indicator","true"),Et&&(Me.style.color="var(--persona-message-assistant-text, var(--persona-text))",ft!=="flat"&&(Me.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Me.appendChild(Fe);let Ft=pr("typing-indicator","assistant");Ft.appendChild(Me),v.appendChild(Ft)}}if(!Ln&&u.length>0){let O=u[u.length-1],We={config:o,lastMessage:O,messageCount:u.length},Fe=s.find(Et=>Et.renderIdleIndicator),Me=null;if(Fe?.renderIdleIndicator&&(Me=Fe.renderIdleIndicator(We)),Me===null&&o.loadingIndicator?.renderIdle&&(Me=o.loadingIndicator.renderIdle(We)),Me){let Et=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;Et.className=ft?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Me);let Ft=pr("idle-indicator","assistant");Ft.appendChild(Et),v.appendChild(Ft)}}if(yg(v),Zi(l,v),Nc(l),de.length>0)for(let{messageId:O,fingerprint:We,bubble:Fe}of de){let Me=l.querySelector(`#wrapper-${O}`);Me&&(ni(Me,V.get(O)??"assistant"),Fe!==null&&(Me.replaceChildren(Fe),Me.setAttribute("data-bubble-fp",We),Fr.set(O,We)))}if(Fr.size>0)for(let O of Fr.keys())F.has(O)||Fr.delete(O);if(Ce.length>0)for(let{messageId:O,fingerprint:We,bubble:Fe}of Ce){let Me=l.querySelector(`#wrapper-${O}`);Me&&(ni(Me,V.get(O)??"assistant"),Fe!==null&&(Me.replaceChildren(Fe),Me.setAttribute("data-bubble-fp",We),ar.set(O,We)))}if(ar.size>0)for(let O of ar.keys())F.has(O)||ar.delete(O);if(gt.length>0)for(let{messageId:O,fingerprint:We,bubble:Fe}of gt){let Me=l.querySelector(`#wrapper-${O}`);Me&&(ni(Me,V.get(O)??"assistant"),Fe!==null&&(Me.replaceChildren(Fe),Me.setAttribute("data-bubble-fp",We),bo.set(O,We)))}if(bo.size>0)for(let O of bo.keys())F.has(O)||bo.delete(O)},Fs=(l,u,m)=>{My(l,u,m),Hp()},_s=null,ky=()=>{if(_s)return;let l=m=>{let v=m.composedPath();v.includes(Le)||nt&&v.includes(nt)||ut(!1,"user")};_s=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},uu=()=>{if(!_s)return;(e.ownerDocument??document).removeEventListener("pointerdown",_s,!0),_s=null};Ne.push(()=>uu());let $s=null,Ly=()=>{if($s)return;let l=m=>{m.key==="Escape"&&(m.isComposing||ut(!1,"user"))};$s=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},gu=()=>{if(!$s)return;(e.ownerDocument??document).removeEventListener("keydown",$s,!0),$s=null};Ne.push(()=>gu());let js=!1,fu=new Set,Py=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},Ur=()=>{if(!Z())return;let l=Ee.peekBanner,u=Ee.peekTextNode;if(!l||!u)return;if(Y){l.classList.remove("persona-pill-peek--visible");return}let m=_?.getMessages()??[],v;for(let kt=m.length-1;kt>=0;kt--){let Ht=m[kt];if(Ht.role==="assistant"&&Ht.content){v=Ht;break}}if(!v){l.classList.remove("persona-pill-peek--visible");return}let w=v.content,L=!!v.streaming,U=Py(),F=ol(U),V=F.type!=="none"?ms(F.type,U?.plugins):null,Q=V?.isAnimating?.(v)===!0,fe=V!==null&&(L||Q);fe&&V&&!fu.has(V.name)&&(al(V,e),fu.add(V.name));let de=fe&&V?.containerClass?V.containerClass:null,Ce=u.dataset.personaPeekStreamClass??null;Ce&&Ce!==de&&(u.classList.remove(Ce),delete u.dataset.personaPeekStreamClass),de&&Ce!==de&&(u.classList.add(de),u.dataset.personaPeekStreamClass=de),fe?(u.style.setProperty("--persona-stream-step",`${F.speed}ms`),u.style.setProperty("--persona-stream-duration",`${F.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Je=fe?rl(w,F.buffer,V,v,L):w;if(fe&&F.placeholder==="skeleton"&&L&&(!Je||!Je.trim())){let kt=document.createElement("div"),Ht=Ca();Ht.classList.add("persona-pill-peek__skeleton"),kt.appendChild(Ht),Zi(u,kt)}else{let kt=Math.max(0,Je.length-100),Ht=Je.length>100?Je.slice(-100):Je,O=_n(Ht);if(!fe||!V){let We=Je.length>100?`\u2026${Ht}`:Ht;u.textContent!==We&&(u.textContent=We)}else{let We=O;(V.wrap==="char"||V.wrap==="word")&&(We=xa(O,V.wrap,`peek-${v.id}`,{skipTags:V.skipTags,startIndex:kt}));let Fe=document.createElement("div");if(Fe.innerHTML=We,V.useCaret&&Ht.length>0){let Me=sl(),Et=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ft=Et[Et.length-1];ft?.parentNode?ft.parentNode.insertBefore(Me,ft.nextSibling):Fe.appendChild(Me)}Zi(u,Fe),V.onAfterRender?.({container:u,bubble:l,messageId:v.id,message:v,speed:F.speed,duration:F.duration})}}let cn=Ln||js;l.classList.toggle("persona-pill-peek--visible",cn)};if(Z()){let l=Ee.peekBanner;if(l){let v=w=>{w.preventDefault(),w.stopPropagation(),ut(!0,"user")};l.addEventListener("pointerdown",v),Ne.push(()=>{l.removeEventListener("pointerdown",v)})}let u=()=>{js||(js=!0,Ur())},m=()=>{js&&(js=!1,Ur())};xe.addEventListener("pointerenter",u),xe.addEventListener("pointerleave",m),Ne.push(()=>{xe.removeEventListener("pointerenter",u),xe.removeEventListener("pointerleave",m)}),nt&&(nt.addEventListener("pointerenter",u),nt.addEventListener("pointerleave",m),Ne.push(()=>{nt.removeEventListener("pointerenter",u),nt.removeEventListener("pointerleave",m)}))}let Ry=l=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",v=u.bottomOffset??"16px",w=u.collapsedMaxWidth,L=u.expandedMaxWidth??"880px",U=u.expandedTopOffset??"5vh",F=u.modalMaxWidth??"880px",V=u.modalMaxHeight??"min(90vh, 800px)",Q="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",de=Le.style;if(de.left="",de.right="",de.top="",de.bottom="",de.transform="",de.width="",de.maxWidth="",de.height="",de.maxHeight="",nt){let Ce=nt.style;Ce.bottom=v,Ce.width=w??""}if(l&&m!=="fullscreen"){if(m==="modal"){de.top="50%",de.left="50%",de.transform="translate(-50%, -50%)",de.bottom="auto",de.right="auto",de.width=F,de.maxWidth=Q,de.maxHeight=V,de.height=V;return}de.left="50%",de.transform="translateX(-50%)",de.bottom=`calc(${v} + ${fe})`,de.top=U,de.width=L,de.maxWidth=Q}},Us=()=>{if(!ce())return;if(Z()){let Q=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Y?"expanded":"collapsed";Le.dataset.state=fe,Le.dataset.expandedSize=Q,nt&&(nt.dataset.state=fe,nt.dataset.expandedSize=Q),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ry(Y),we.style.display=Y?"flex":"none",Zo(),Y?(ky(),Ly()):(uu(),gu()),Ur();return}let l=Mt(o),u=e.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,w=u.innerWidth<=m,L=v&&w&&N,U=rn(o).reveal;Y?(Le.style.removeProperty("display"),Le.style.display=l?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0"),xe.classList.add("persona-scale-100","persona-opacity-100"),Pt?(Pt.setPanelOpen(!0),Pt.element.style.display="none"):Xt&&(Xt.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!L?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.setProperty("display","none","important"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Le.style.display="",Le.classList.add("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100"),xe.classList.add("persona-scale-95","persona-opacity-0")),Pt?(Pt.setPanelOpen(!1),Pt.element.style.display=l?"none":""):Xt&&(Xt.style.display=l?"none":""))},ut=(l,u="user")=>{if(!ce()||Y===l)return;let m=Y;Y=l,Us();let v=(()=>{let L=o.launcher?.sidebarMode??!1,U=e.ownerDocument.defaultView??window,F=o.launcher?.mobileFullscreen??!0,V=o.launcher?.mobileBreakpoint??640,Q=U.innerWidth<=V,fe=Mt(o)&&F&&Q,de=Z()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||F&&Q&&N||fe||de})();if(Y&&v){if(!On){let L=e.getRootNode(),U=L instanceof ShadowRoot?L.host:e.closest(".persona-host");U&&(On=Cd(U,o.launcher?.zIndex??$t))}Nn||(Nn=wd(e.ownerDocument))}else Y||(On?.(),On=null,Nn?.(),Nn=null);Y&&(Ks(),lu()||(sn()==="follow"?wo(!0):iu()));let w={open:Y,source:u,timestamp:Date.now()};Y&&!m?c.emit("widget:opened",w):!Y&&m&&c.emit("widget:closed",w),c.emit("widget:state",{open:Y,launcherEnabled:N,voiceActive:Ge.active,streaming:_.isStreaming()})},oi=l=>{Na(l?"stop":"send"),re&&(re.disabled=l),nr.forEach(u=>{u.elements.forEach(m=>{m.toggleAttribute("data-disabled",l),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",l?"true":"false")}),u.buttons.forEach(m=>{m.disabled=l})}),hc.forEach(u=>{u.toggleAttribute("data-disabled",l),u instanceof HTMLButtonElement?u.disabled=l:u.setAttribute("aria-disabled",l?"true":"false"),u.querySelectorAll("button").forEach(m=>{m.disabled=l})}),Te.dataset.personaComposerStreaming=l?"true":"false",Te.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},uc=()=>{Ge.active||W&&W.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>uc(),200)});let gc=!K.hidden,Ao=null,mu=!x,hu=null,yu,bu=null,zs=null,fc=l=>{let u=go(o),m=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(m!==hu||u.icon!==yu)&&(hu=m,yu=u.icon,bl({host:K,iconHolder:j,title:pe,subtitle:ze,starterSuggestions:Tn},u));let v=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;v!==bu&&(bu=v,vl(G,u.message,o));let w=l??(_?_.getMessages():o.initialMessages),L=Go(u,w),U=L!==gc;if(gc=L,zs){Ao?.cancel(),Ao=null,bs(ae,K,!0);return}if(U&&!L&&u.dismiss==="on-first-message"&&mu){Ao=vm(K,F=>{Ao===F&&(Ao=null),!gc&&!zs&&(bs(ae,K,!1),pu()),F?.cancel()});return}if(Ao){if(!L)return;Ao.cancel(),Ao=null}bs(ae,K,L),U&&!L&&pu()},mc=[],hc=[],yc=!1,vu=null,xu,Cu=()=>{hc.length=0;let l=mc.splice(0,mc.length);for(let u of l)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Ne.push(Cu);let Iy=(l,u)=>{let m=Sd(l,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),y("span");let v=o.suggestions?.starters,w=Td({item:{...m,behavior:m.behavior??v?.behavior??"send"},index:u,surface:"starter",source:"config",variant:v?.variant??"card",streaming:a?_.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:_,getTextarea:()=>W,eventTarget:K});return hc.push(w),w},bc=()=>{if(yc)return;yc=!0;let l=go(o);vu=`${l.variant}|${l.dismiss}|${l.title}|${l.subtitle}|${l.message??""}`,xu=l.icon;try{Cu(),ym(ae,K,zs),zs=null;let u=_?_.getMessages():o.initialMessages,m=Go(l,u),v=0,w=null;for(let L of s)if(L.renderWelcome&&(w=L.renderWelcome({config:l,variant:l.variant,visible:m,defaultRenderer:()=>K,sendMessage:U=>{if(!_||_.isStreaming())return;let F=U.trim();F&&_.sendMessage(F)},requestRender:()=>bc(),renderStarter:U=>Iy(U,v++),storage:i(L.id),onCleanup:U=>{mc.push(U)}}),w))break;w&&w!==K&&(zs=w,hm(ae,K,w))}finally{yc=!1}fc()},Wy=()=>{let l=go(o);`${l.variant}|${l.dismiss}|${l.title}|${l.subtitle}|${l.message??""}`===vu&&l.icon===xu||bc()},vc=()=>{fc(),Gl||(W.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),W.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',W.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=f.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{R(u=>({...u,sessionId:l}))}});let ur=null,Hy=()=>{ur==null&&(ur=setInterval(()=>{let l=Se.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(ur),ur=null;return}let u=Date.now();l.forEach(m=>{let v=Number(m.getAttribute("data-tool-elapsed"));v&&(m.textContent=Si(u-v))})},100))},xc=(l,u)=>{if(Object.is(l,u))return!0;if(l===null||u===null||typeof l!="object"||typeof u!="object")return!1;if(Array.isArray(l)||Array.isArray(u))return!Array.isArray(l)||!Array.isArray(u)||l.length!==u.length?!1:l.every((U,F)=>xc(U,u[F]));let m=l,v=u,w=Object.keys(m),L=Object.keys(v);return w.length===L.length&&w.every(U=>Object.prototype.hasOwnProperty.call(v,U)&&xc(m[U],v[U]))},wu=l=>{let{content:u,rawContent:m,llmContent:v,...w}=l;return w},Cc=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!Ba(l),By=(l,u,m)=>{if(l.length!==u.length)return!1;let v=l[m.index],w=u[m.index];return!v||!w||v.id!==m.id||w.id!==m.id?!1:(!Object.is(v.content,w.content)||!Object.is(v.rawContent,w.rawContent)||!Object.is(v.llmContent,w.llmContent))&&Cc(v)&&Cc(w)&&xc(wu(v),wu(w))},Au=null,zr=null,gr=null,Qn=null,ri=l=>{Au=l;let u,m;zr=null;for(let w=l.length-1;w>=0;w-=1){let L=l[w];if(!u&&L.role==="user"&&(u=L),!m&&L.role==="assistant"&&(m=L),!zr&&Cc(L)&&(zr={index:w,id:L.id}),u&&m&&zr)break}Fs(Se,l,ee),fd(Se,Mn.artifacts,{suppressTransition:Ln}),Hy(),fc(l),Nr(l),wo(!Ln),Ey(l),l.length===0&&(Ns(),Ds=!0,Ya=!1,_r=null,Xa=!1),!oc||Ja?(oc=!0,lr=u?.id??null,rc=m?.id??null):u&&u.id!==lr?(lr=u.id,Cy(u.id)):m&&m.id!==rc&&wy(),m&&(rc=m.id),Ty(l);let v=Ge.lastUserMessageId;u&&u.id!==v&&(Ge.lastUserMessageId=u.id,c.emit("user:message",u)),Ge.lastUserMessageWasVoice=!!u?.viaVoice,ic(l),Ur()},wc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null);let l=gr;gr=null,l&&ri(l)},Su=()=>{Qn!==null&&cancelAnimationFrame(Qn),Qn=null,gr=null},Dy=l=>{let u=gr??Au;if(Ln&&u&&zr&&By(u,l,zr)){gr=l,Qn===null&&(Qn=requestAnimationFrame(()=>{Qn=null;let m=gr;gr=null,m&&ri(m)}));return}if(l.length===0){Su(),ri(l);return}wc(),ri(l)};_=new cs(o,{onMessagesChanged(l){Dy(l)},onStatusChanged(l){let u=o.statusIndicator??{};Sn(D,(v=>v==="idle"?u.idleText??Dt.idle:v==="connecting"?u.connectingText??Dt.connecting:v==="connected"?u.connectedText??Dt.connected:v==="error"?u.errorText??Dt.error:v==="paused"?u.pausedText??Dt.paused:v==="resuming"?u.resumingText??Dt.resuming:Dt[v])(l),u,l)},onStreamingChanged(l){l||(_?.getMessages().length===0?Su():wc()),Ln=l,oi(l),_&&Fs(Se,_.getMessages(),ee),l||(wo(!0),vy(),Xp=!0,_&&Qp(_.getMessages(),Ho(o))),Ut(),xp(l?"Responding\u2026":"Response complete."),Ur()},onVoiceStatusChanged(l){if(c.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Zn(),Vr();break;case"processing":Zn(),Ky();break;case"speaking":Zn(),Gy();break;default:l==="idle"&&_.isBargeInActive()?(Zn(),Vr(),re?.setAttribute("aria-label","End voice session")):(Ge.active=!1,Zn(),Xn("system"),Pn());break}},onArtifactsState(l){Mn=l,l.artifacts.length===0&&(Br=!1),fd(Se,l.artifacts,{suppressTransition:Ln}),Kn(),ic()},onReconnect(l){let{executionId:u,lastEventId:m}=l.handle;l.phase==="paused"?c.emit("stream:paused",{executionId:u,after:m}):l.phase==="resuming"?c.emit("stream:resuming",{executionId:u,after:m,attempt:l.attempt??1}):c.emit("stream:resumed",{executionId:u,after:m})}}),lt.current=_,Ne.push(()=>_.cancel());let Ac=null;if(_.onReadAloudChange((l,u)=>{Ip=l,Wp=u,Hp();let m=l??Ac;l&&(Ac=l);let v=m?_.getMessages().find(w=>w.id===m)??null:null;c.emit("message:read-aloud",{messageId:m,message:v,state:u,timestamp:Date.now()}),u==="idle"&&(Ac=null)}),a=!0,oc=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(Pe||o.onSSEEvent)&&_.setSSEEventCallback((l,u)=>{o.onSSEEvent?.(l,u),$e?.processEvent(l,u),Pe?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})});let Tu=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};x?x.then(l=>{if(l){if(l.metadata&&(f=Zd(l.metadata),B.syncFromMetadata()),l.messages?.length){Ja=!0;try{_.hydrateMessages(l.messages)}finally{Ja=!1}}l.artifacts?.length&&_.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>{mu=!0,Tu()}):Tu();let Eu=()=>{!Z()||Y||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},Oy=(l,u)=>l?u?{refs:[...l.refs,...u.refs],finalize:async()=>{let[m,v]=await Promise.allSettled([l.finalize(),u.finalize()]),w=[];return m.status==="fulfilled"?w.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),v.status==="fulfilled"?w.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),Cw(w)}}:l:u,Ny=()=>{let u=W.getInlineMessageFields?.();return u&&u.contentSegments.some(v=>v.kind==="mention")?u.contentSegments:void 0},qs=!1,Fy=async l=>{let u=W.value.trim(),m=Ct?.hasAttachments()??!1,v=u?await(Yt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(v?.kind==="action"){W.value="",W.style.height="auto",Vs(),Yt?.clear();return}let w=Yt?.collectForSubmit()??null,L=v?.kind==="server"?v.mentions:null,U=Oy(w,L),F=v?.kind==="prompt"?v.sendText:u,V=!!w&&w.refs.length>0;if(!F&&!m&&!V&&!L)return;Eu();let Q;m&&(Q=[],Q.push(...Ct.getContentParts()),F&&Q.push(Oo(F)));let fe=v?.kind==="prompt"?void 0:Ny();W.value="",W.style.height="auto",Vs(),_.sendMessage(F,{contentParts:Q,mentions:U??void 0,contentSegments:fe,viaVoice:l?.viaVoice}),m&&Ct.clearAttachments(),w&&Yt?.clear()},Sc=async l=>{if(!qs){qs=!0;try{await Fy(l)}finally{qs=!1}}},si=l=>{if(l.preventDefault(),_.isStreaming()){_.cancel(),$e?.reset(),Ae?.update();return}qs||Sc()},_y=()=>o.features?.composerHistory!==!1,Tc={...yd},Ec=!1,Vs=()=>{Tc={...yd}},$y=()=>_.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),jy=l=>{if(!W)return;Ec=!0,W.value=l,W.dispatchEvent(new Event("input",{bubbles:!0})),Ec=!1;let u=W.value.length;W.setSelectionRange(u,u)},Uy=l=>{Ec||(l.isComposing||Yt?.handleInput(l.inputType??void 0),Vs())},zy=l=>{if(W&&!(!l.isComposing&&Yt?.handleKeydown(l))){if(_y()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=W.selectionStart===0&&W.selectionEnd===0,m=Vf({direction:l.key==="ArrowUp"?"up":"down",history:$y(),currentValue:W.value,atStart:u,state:Tc});if(Tc=m.state,m.handled){l.preventDefault(),m.value!==void 0&&jy(m.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}if(qs){l.preventDefault();return}Vs(),l.preventDefault(),h.click()}}},Mu=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(we)&&(_.cancel(),$e?.reset(),Ae?.update(),Vs(),l.preventDefault(),l.stopImmediatePropagation())},qy=async l=>{if(o.attachments?.enabled!==!0||!Ct)return;let u=yw(l.clipboardData);u.length!==0&&(l.preventDefault(),await Ct.handleFiles(u))},bn=null,Fn=!1,qr=null,At=null,ku=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ai=(l="user")=>{if(Fn||_.isStreaming())return;let u=ku();if(!u)return;bn=new u;let v=(o.voiceRecognition??{}).pauseDuration??2e3;bn.continuous=!0,bn.interimResults=!0,bn.lang="en-US";let w=W.value;bn.onresult=L=>{let U="",F="";for(let Q=0;Q<L.results.length;Q++){let fe=L.results[Q],de=fe[0].transcript;fe.isFinal?U+=de+" ":F=de}let V=w+U+F;W.value=V,qr&&clearTimeout(qr),(U||F)&&(qr=window.setTimeout(()=>{W.value.trim()&&bn&&Fn&&(So(),Sc({viaVoice:!0}))},v))},bn.onerror=L=>{L.error!=="no-speech"&&So()},bn.onend=()=>{if(Fn){let L=W.value.trim();L&&L!==w.trim()&&Sc({viaVoice:!0}),So()}};try{if(bn.start(),Fn=!0,Ge.active=!0,l!=="system"&&(Ge.manuallyDeactivated=!1),Xn(l),Pn(),re){let L=o.voiceRecognition??{};At={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let U=L.recordingBackgroundColor,F=L.recordingIconColor,V=L.recordingBorderColor;if(re.classList.add("persona-voice-recording"),re.style.backgroundColor=U??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=F??"var(--persona-voice-recording-indicator, #ffffff)",F){let Q=re.querySelector("svg");Q&&Q.setAttribute("stroke",F)}V&&(re.style.borderColor=V),re.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(l="user")=>{if(Fn){if(Fn=!1,qr&&(clearTimeout(qr),qr=null),bn){try{bn.stop()}catch{}bn=null}if(Ge.active=!1,Xn(l),Pn(),re){if(re.classList.remove("persona-voice-recording"),At){re.style.backgroundColor=At.backgroundColor,re.style.color=At.color,re.style.borderColor=At.borderColor;let u=re.querySelector("svg");u&&u.setAttribute("stroke",At.color||"currentColor"),At=null}re.setAttribute("aria-label","Start voice recognition")}}},Vy=(l,u)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=l?.provider?.type==="runtype",w=l?.provider?.type==="custom";if(!(m||v||w))return null;let U=y("div","persona-send-button-wrapper"),F=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button";let V=l?.tooltipText??"Start voice recognition";F.setAttribute("aria-label",V);let Q=l?.iconName??"mic",fe=u?.size??"40px",de=l?.iconSize??fe,Ce=parseFloat(de)||24,Je=l?.backgroundColor??u?.backgroundColor,bt=l?.iconColor??u?.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",bt?F.style.color=bt:F.style.color="var(--persona-text, #111827)";let cn=se(Q,Ce,bt||"currentColor",1.5);cn?F.appendChild(cn):F.textContent="\u{1F3A4}",Je?F.style.backgroundColor=Je: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),U.appendChild(F);let kt=l?.showTooltip??!1;return jt({anchor:F,trigger:U,text:()=>F.getAttribute("aria-label")??V,enabled:kt}),{micButton:F,micButtonWrapper:U}},Mc=()=>{if(!re||At)return;let l=o.voiceRecognition??{};At={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},kc=(l,u)=>{if(!re)return;let m=re.querySelector("svg");m&&m.remove();let v=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),w=se(l,v,u,1.5);w&&re.appendChild(w)},ii=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Vr=()=>{if(!re)return;Mc();let l=o.voiceRecognition??{},u=l.recordingBackgroundColor,m=l.recordingIconColor,v=l.recordingBorderColor;if(ii(),re.classList.add("persona-voice-recording"),re.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let w=re.querySelector("svg");w&&w.setAttribute("stroke",m)}v&&(re.style.borderColor=v),re.setAttribute("aria-label","Stop voice recognition")},Ky=()=>{if(!re)return;Mc();let l=o.voiceRecognition??{},u=_.getVoiceInterruptionMode(),m=l.processingIconName??"loader",v=l.processingIconColor??At?.color??"",w=l.processingBackgroundColor??At?.backgroundColor??"",L=l.processingBorderColor??At?.borderColor??"";ii(),re.classList.add("persona-voice-processing"),re.style.backgroundColor=w,re.style.borderColor=L;let U=v||"currentColor";re.style.color=U,kc(m,U),re.setAttribute("aria-label","Processing voice input"),u==="none"&&(re.style.cursor="default")},Gy=()=>{if(!re)return;Mc();let l=o.voiceRecognition??{},u=_.getVoiceInterruptionMode(),m=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",v=l.speakingIconName??m,w=l.speakingIconColor??(u==="barge-in"?l.recordingIconColor??At?.color??"":At?.color??""),L=l.speakingBackgroundColor??(u==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),U=l.speakingBorderColor??(u==="barge-in"?l.recordingBorderColor??"":At?.borderColor??"");ii(),re.classList.add("persona-voice-speaking"),re.style.backgroundColor=L,re.style.borderColor=U;let F=w||"currentColor";re.style.color=F,kc(v,F);let V=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",V),u==="none"&&(re.style.cursor="default"),u==="barge-in"&&re.classList.add("persona-voice-recording")},Zn=()=>{re&&(ii(),At&&(re.style.backgroundColor=At.backgroundColor??"",re.style.color=At.color??"",re.style.borderColor=At.borderColor??"",kc(At.iconName,At.color||"currentColor"),At=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},Kr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=_.getVoiceStatus(),u=_.getVoiceInterruptionMode();if(u==="none"&&(l==="processing"||l==="speaking"))return;if(u==="cancel"&&(l==="processing"||l==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,Pn(),Xn("user"),Zn()});return}_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Ge.manuallyDeactivated=!_.isVoiceActive(),Pn(),Xn("user"),_.isVoiceActive()?Vr():Zn()});return}if(Fn){let l=W.value.trim();Ge.manuallyDeactivated=!0,Pn(),So("user"),l&&(W.value="",W.style.height="auto",_.sendMessage(l))}else Ge.manuallyDeactivated=!1,Pn(),ai("user")};wp=Kr,re&&(re.addEventListener("click",Kr),Ne.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Zn()):So("system"),re&&re.removeEventListener("click",Kr)}));let Jy=c.on("assistant:complete",()=>{tu&&(Ge.active||Ge.manuallyDeactivated||tu==="assistant"&&!Ge.lastUserMessageWasVoice||setTimeout(()=>{!Ge.active&&!Ge.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Xn("auto"),_.isVoiceActive()&&Vr()}):ai("auto"))},600))});Ne.push(Jy);let Yy=c.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});Ne.push(Yy);let Lu=()=>{ut(!Y,"user")},Pt=null,Xt=null;if(N&&!Z()){let{instance:l,element:u}=Od({config:o,plugins:s,onToggle:Lu});Pt=l,l||(Xt=u)}Pt?e.appendChild(Pt.element):Xt&&e.appendChild(Xt),Us(),Nr(),vc(),bc(),oi(_.isStreaming()),lu()||(sn()==="follow"?wo(!0):iu()),gy(),z&&(!N||Z()?setTimeout(()=>uc(),0):Y&&setTimeout(()=>uc(),200));let Ks=()=>{if(Z()){Qo(),Us();return}let l=Mt(o),u=o.launcher?.sidebarMode??!1,m=e.ownerDocument.defaultView??window,v=o.launcher?.mobileFullscreen??!0,w=o.launcher?.mobileBreakpoint??640,L=m.innerWidth<=w,U=v&&L&&N;try{if(U){Zo(),Ws=Va();return}let F=!1;J&&(J=!1,Zo(),F=!0);let V=Va();if(!F&&V!==Ws&&(Zo(),F=!0),Ws=V,F&&Ql(),!N&&!l){xe.style.height="",xe.style.width="";return}if(!u&&!l){let fe=o?.launcher?.width??o?.launcherWidth??pn;xe.style.width=fe,xe.style.maxWidth=fe}qa(),_p()}finally{if(Qo(),Us(),Y&&N){let V=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Q=o.launcher?.sidebarMode??!1,fe=o.launcher?.mobileFullscreen??!0,de=Mt(o)&&fe&&V,Ce=Q||fe&&V&&N||de;if(Ce&&!Nn){let Je=e.getRootNode(),bt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");bt&&!On&&(On=Cd(bt,o.launcher?.zIndex??$t)),Nn=wd(e.ownerDocument)}else Ce||(On?.(),On=null,Nn?.(),Nn=null)}}};Ks();let Pu=e.ownerDocument.defaultView??window;if(Pu.addEventListener("resize",Ks),Ne.push(()=>Pu.removeEventListener("resize",Ks)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Qo()});l.observe(Te),Ne.push(()=>l.disconnect())}ln=ae.scrollTop;let Ru=Un(ae),Iu=()=>{let l=ae.scrollTop,u=Un(ae),m=u<Ru;if(Ru=u,!ho()){ln=l,Ut();return}let{action:v,nextLastScrollTop:w}=tl({following:an.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:po(ae,Jn),userScrollThreshold:cy,isAutoScrolling:en||Ga||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=w,v==="resume"){Za()||Co();return}v==="pause"&&Os()};if(ae.addEventListener("scroll",Iu,{passive:!0}),Ne.push(()=>ae.removeEventListener("scroll",Iu)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{xy(),Nc(Se)});l.observe(Se),l.observe(ae),Ne.push(()=>l.disconnect())}let Wu=()=>{ho()&&an.isFollowing()&&Za()&&Os()},Hu=ae.ownerDocument;Hu.addEventListener("selectionchange",Wu),Ne.push(()=>{Hu.removeEventListener("selectionchange",Wu)});let Xy=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Bu=l=>{Xy.has(l.key)&&(cr(),yp()&&ho()&&an.isFollowing()&&Os())},Du=l=>{l.target?.closest("a, button, [tabindex], input, textarea, select")&&(cr(),yp()&&ho()&&an.isFollowing()&&Os())};ae.addEventListener("keydown",Bu),ae.addEventListener("focusin",Du),Ne.push(()=>{ae.removeEventListener("keydown",Bu),ae.removeEventListener("focusin",Du)});let Ou=l=>{if(l.deltaY!==0&&cr(),!ho())return;let u=nl({following:an.isFollowing(),deltaY:l.deltaY,nearBottom:po(ae,Jn),resumeWhenNearBottom:!0});u==="pause"?Os():u==="resume"&&!Za()&&Co()};ae.addEventListener("wheel",Ou,{passive:!0}),ae.addEventListener("touchmove",cr,{passive:!0}),ae.addEventListener("pointerdown",cr,{passive:!0}),Ne.push(()=>{ae.removeEventListener("touchmove",cr),ae.removeEventListener("pointerdown",cr)}),Ne.push(()=>ae.removeEventListener("wheel",Ou)),It.addEventListener("click",()=>{Ns(),ae.scrollTop=ae.scrollHeight,ln=ae.scrollTop,Co(),wo(!0),Ut()}),Ne.push(()=>It.remove()),Ne.push(()=>{ru(),Ns()});let Nu=()=>{ue&&(or&&(ue.removeEventListener("click",or),or=null),ce()?(ue.style.display="",or=()=>{ut(!1,"user")},ue.addEventListener("click",or)):ue.style.display="none")};Nu(),(()=>{let{clearChatButton:l}=Ee;l&&l.addEventListener("click",()=>{_.clearMessages(),sr.clear(),Co(),Io(Ee.composerOverlay);try{localStorage.removeItem(Ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),b?.clear&&ac(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},B.syncFromMetadata(),Pe?.clear(),$e?.reset(),Ae?.update()})})(),I&&I.addEventListener("submit",si);let Fu=[["keydown",zy],["input",Uy],["paste",qy],["focus",ny]],Lc=l=>{if(l)for(let[u,m]of Fu)l.addEventListener(u,m)},Pc=l=>{if(l)for(let[u,m]of Fu)l.removeEventListener(u,m)};Lc(W);let _u=()=>{Yt?.onComposerSwap((l,u)=>{Pc(u),W=l,Lc(l)})};_u();let Rc=!1;function Qy(){if(!Rc){Rc=!0;try{let l=W?.value??"",u=Te.ownerDocument??document,m=W?u.activeElement===W:!1;Pc(W),I?.removeEventListener("submit",si),re?.removeEventListener("click",Kr),Yt?.destroy(),Yt=null;let v=null,w=()=>(v=Z()?hl({config:o}):Mr({config:o}),v.footer),L=Tp(w)??w();et.replaceComposer(L),Te=et.composer.footer;let U=v!==null&&L===v.footer;Gl=!U,Na=U?v.setSendButtonMode:()=>{},Sp(Te),Mp(Te),kp(),Lp(),Pp(),_u(),I&&I.addEventListener("submit",si),Lc(W),re?.addEventListener("click",Kr);let F=nr.indexOf(Gn);Gn.destroy(),Gn=Sa(M),F>=0&&(nr[F]=Gn),W&&(W.value=l),vc(),Nr(),oi(_.isStreaming()),Zo(),Qo(),m&&W?.focus()}finally{Rc=!1}}}let $u=e.ownerDocument??document;$u.addEventListener("keydown",Mu,!0);let ju="persona-attachment-drop-active",Gs=0,Ic=()=>{Gs=0,we.classList.remove(ju)},Gr=()=>o.attachments?.enabled===!0&&Ct!==null,Uu=l=>{!Wl(l.dataTransfer)||!Gr()||(Gs++,Gs===1&&we.classList.add(ju))},zu=l=>{!Wl(l.dataTransfer)||!Gr()||(Gs--,Gs<=0&&Ic())},qu=l=>{!Wl(l.dataTransfer)||!Gr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Vu=l=>{if(!Wl(l.dataTransfer)||!Gr())return;l.preventDefault(),l.stopPropagation(),Ic();let u=Array.from(l.dataTransfer.files??[]);u.length!==0&&Ct.handleFiles(u)},To=!0;we.addEventListener("dragenter",Uu,To),we.addEventListener("dragleave",zu,To),e.addEventListener("dragover",qu,To),e.addEventListener("drop",Vu,To);let li=e.ownerDocument,Ku=l=>{Gr()&&l.preventDefault()},Gu=l=>{Gr()&&l.preventDefault()};li.addEventListener("dragover",Ku),li.addEventListener("drop",Gu),Ne.push(()=>{I&&I.removeEventListener("submit",si),Pc(W),$u.removeEventListener("keydown",Mu,!0),Yt?.destroy()}),Ne.push(()=>{we.removeEventListener("dragenter",Uu,To),we.removeEventListener("dragleave",zu,To),e.removeEventListener("dragover",qu,To),e.removeEventListener("drop",Vu,To),li.removeEventListener("dragover",Ku),li.removeEventListener("drop",Gu),Ic()}),Ne.push(()=>{_.cancel()}),Pt?Ne.push(()=>{Pt?.destroy()}):Xt&&Ne.push(()=>{Xt?.remove()});let Wt={update(l){let u=o.toolCall,m=o.messageActions,v=o.layout?.messages,w=o.colorScheme,L=o.loadingIndicator,U=o.iterationDisplay,F=o.features?.showReasoning,V=o.features?.showToolCalls,Q=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,de=o.features?.streamAnimation?.type;o=El({...o,features:r},l),r=o.features,o=Ra(o),ec(),Ar(e,o),La(e,o),Pa(e,o),Kn(),o.colorScheme!==w&&$p();let Ce=Ia.getForInstance(o.plugins);s.length=0,s.push(...Ce),N=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,ve=o.features?.scrollToBottom??{};let Je=sn();ye=o.features?.scrollBehavior??{},Je!==sn()&&(Ns(),Co()),eu(),Cp(),Ut();let bt=me;if(me=o.features?.showEventStreamToggle??!1,me&&!bt){if(Pe||(je=new Ma(at),Pe=new Ea(Ke,je),$e=$e??new ka,je.open().then(()=>Pe?.restore()).catch(()=>{}),_.setSSEEventCallback((le,Ve)=>{o.onSSEEvent?.(le,Ve),$e?.processEvent(le,Ve),Pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:le,timestamp:Date.now(),payload:JSON.stringify(Ve)})})),!Qe&&Be){let le=o.features?.eventStream?.classNames,Ve="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"+(le?.toggleButton?" "+le.toggleButton:"");Qe=y("button",Ve),Qe.style.width="28px",Qe.style.height="28px",Qe.style.color=Jt.actionIconColor,Qe.type="button",Qe.setAttribute("aria-label","Event Stream"),Qe.title="Event Stream";let yt=se("activity","18px","currentColor",1.5);yt&&Qe.appendChild(yt);let Ze=Ee.clearChatButtonWrapper,rt=Ee.closeButtonWrapper,Kt=Ze||rt;Kt&&Kt.parentNode===Be?Be.insertBefore(Qe,Kt):Be.appendChild(Qe),Qe.addEventListener("click",()=>{ie?Ps():Vl()})}}else!me&&bt&&(Ps(),Qe&&(Qe.remove(),Qe=null),Pe?.clear(),je?.destroy(),Pe=null,je=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Pt&&(Pt.destroy(),Pt=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Pt&&!Xt){let{instance:le,element:Ve}=Od({config:o,plugins:s,onToggle:Lu});Pt=le,le||(Xt=Ve),e.appendChild(Ve)}Pt&&Pt.update(o),qe&&o.launcher?.title!==void 0&&(qe.textContent=o.launcher.title),Ue&&o.launcher?.subtitle!==void 0&&(Ue.textContent=o.launcher.subtitle);let gt=o.layout?.header;if(gt?.layout!==A&&Be){let le=gt?hs(o,gt,{showClose:ce(),onClose:()=>ut(!1,"user")}):uo({config:o,showClose:ce(),onClose:()=>ut(!1,"user")});et.replaceHeader(le),Be=et.header.element,Re=et.header.iconHolder,qe=et.header.headerTitle,Ue=et.header.headerSubtitle,ue=et.header.closeButton,A=gt?.layout}else if(gt){if(Re&&(Re.style.display=gt.showIcon===!1?"none":""),qe&&(qe.style.display=gt.showTitle===!1?"none":""),Ue&&(Ue.style.display=gt.showSubtitle===!1?"none":""),ue){let le=ce()&&gt.showCloseButton!==!1;ue.style.display=le?"":"none"}if(Ee.clearChatButtonWrapper){let le=gt.showClearChat;if(le!==void 0){Ee.clearChatButtonWrapper.style.display=le?"":"none";let{closeButtonWrapper:Ve}=Ee;Ve&&!Ve.classList.contains("persona-absolute")&&(le?Ve.classList.remove("persona-ml-auto"):Ve.classList.add("persona-ml-auto"))}}}let kt=o.layout?.showHeader!==!1;Be&&(Be.style.display=kt?"":"none");let Ht=o.layout?.showFooter!==!1;Te&&(Te.style.display=Ht?"":"none"),Qo(),Ut(),N!==X?N?ut($,"auto"):(Y=!0,Us()):$!==q&&ut($,"auto"),q=$,X=N,Ks(),Nu();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(u),Me=JSON.stringify(o.messageActions)!==JSON.stringify(m),Et=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ft=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,Ft=o.iterationDisplay!==U,mt=(o.features?.showReasoning??!0)!==(F??!0)||(o.features?.showToolCalls??!0)!==(V??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(Fe||Me||Et||ft||Ft||mt)&&_&&(nc++,Fs(Se,_.getMessages(),ee));let Bt=o.features?.streamAnimation?.type;if(Bt!==de&&Bt&&Bt!=="none"){let le=ms(Bt,o.features?.streamAnimation?.plugins);le&&al(le,e)}let He=o.launcher??{},_e=He.headerIconHidden??!1,zt=o.layout?.header?.showIcon,qt=_e||zt===!1,St=He.headerIconName,ct=He.headerIconSize??"48px";if(Re){let le=we.querySelector(".persona-border-b-persona-divider"),Ve=le?.querySelector(".persona-flex-col");if(qt)Re.style.display="none",le&&Ve&&!le.contains(Ve)&&le.insertBefore(Ve,le.firstChild);else{if(Re.style.display="",Re.style.height=ct,Re.style.width=ct,le&&Ve&&(le.contains(Re)?Re.nextSibling!==Ve&&(Re.remove(),le.insertBefore(Re,Ve)):le.insertBefore(Re,Ve)),St){let Ze=parseFloat(ct)||24,rt=se(St,Ze*.6,"currentColor",1);rt?Re.replaceChildren(rt):Re.textContent=He.agentIconText??"\u{1F4AC}"}else if(He.iconUrl){let Ze=Re.querySelector("img");if(Ze)Ze.src=He.iconUrl,Ze.style.height=ct,Ze.style.width=ct;else{let rt=document.createElement("img");rt.src=He.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=ct,rt.style.width=ct,Re.replaceChildren(rt)}}else{let Ze=Re.querySelector("svg"),rt=Re.querySelector("img");(Ze||rt)&&Re.replaceChildren(),Re.textContent=He.agentIconText??"\u{1F4AC}"}let yt=Re.querySelector("img");yt&&(yt.style.height=ct,yt.style.width=ct)}}let ht=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(qe&&(qe.style.display=ht===!1?"none":""),Ue&&(Ue.style.display=Xe===!1?"none":""),ue){let le=ce()&&o.layout?.header?.showCloseButton!==!1;ue.style.display=le?"":"none";let Ve=He.closeButtonSize??"32px",yt=He.closeButtonPlacement??"inline";ue.style.height=Ve,ue.style.width=Ve;let{closeButtonWrapper:Ze}=Ee,rt=yt==="top-right",Kt=Ze?.classList.contains("persona-absolute");if(Ze&&rt!==Kt)if(Ze.remove(),rt)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",we.style.position="relative",we.appendChild(Ze);else{let Mo=He.clearChat?.placement??"inline",Xs=He.clearChat?.enabled??!0;Ze.className=Xs&&Mo==="inline"?"":"persona-ml-auto";let Ju=we.querySelector(".persona-border-b-persona-divider");Ju&&Ju.appendChild(Ze)}if(ue.style.color=He.closeButtonColor||Jt.actionIconColor,He.closeButtonBackgroundColor?(ue.style.backgroundColor=He.closeButtonBackgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),He.closeButtonBorderWidth||He.closeButtonBorderColor){let Mo=He.closeButtonBorderWidth||"0px",Xs=He.closeButtonBorderColor||"transparent";ue.style.border=`${Mo} solid ${Xs}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");He.closeButtonBorderRadius?(ue.style.borderRadius=He.closeButtonBorderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),He.closeButtonPaddingX?(ue.style.paddingLeft=He.closeButtonPaddingX,ue.style.paddingRight=He.closeButtonPaddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),He.closeButtonPaddingY?(ue.style.paddingTop=He.closeButtonPaddingY,ue.style.paddingBottom=He.closeButtonPaddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let dn=He.closeButtonIconName??"x",Rn=He.closeButtonIconText??"\xD7";ue.innerHTML="";let _t=se(dn,"28px","currentColor",1);_t?(_t.style.display="block",ue.appendChild(_t)):ue.textContent=Rn;let Gt=He.closeButtonTooltipText??"Close chat",to=He.closeButtonShowTooltip??!0;ue.setAttribute("aria-label",Gt),Ze&&jt({anchor:ue,trigger:Ze,text:()=>ue?.getAttribute("aria-label")??Gt,enabled:to})}let{clearChatButton:Oe,clearChatButtonWrapper:vt}=Ee;if(Oe){let le=He.clearChat??{},Ve=le.enabled??!0,yt=o.layout?.header?.showClearChat,Ze=yt!==void 0?yt:Ve,rt=le.placement??"inline";if(vt){vt.style.display=Ze?"":"none";let{closeButtonWrapper:Kt}=Ee;!Z()&&Kt&&!Kt.classList.contains("persona-absolute")&&(Ze?Kt.classList.remove("persona-ml-auto"):Kt.classList.add("persona-ml-auto"));let dn=rt==="top-right",Rn=vt.classList.contains("persona-absolute");if(!Z()&&dn!==Rn&&Ze){if(vt.remove(),dn)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",we.style.position="relative",we.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Gt=we.querySelector(".persona-border-b-persona-divider"),to=Ee.closeButtonWrapper;Gt&&to&&to.parentElement===Gt?Gt.insertBefore(vt,to):Gt&&Gt.appendChild(vt)}let _t=Ee.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(dn?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(Ze){if(!Z()){let Mo=le.size??"32px";Oe.style.height=Mo,Oe.style.width=Mo}let Kt=le.iconName??"refresh-cw",dn=le.iconColor??"";Oe.style.color=dn||Jt.actionIconColor,Oe.innerHTML="";let Rn=Z()?"14px":"20px",_t=se(Kt,Rn,"currentColor",1);if(_t&&(_t.style.display="block",Oe.appendChild(_t)),le.backgroundColor?(Oe.style.backgroundColor=le.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),le.borderWidth||le.borderColor){let Mo=le.borderWidth||"0px",Xs=le.borderColor||"transparent";Oe.style.border=`${Mo} solid ${Xs}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");le.borderRadius?(Oe.style.borderRadius=le.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),le.paddingX?(Oe.style.paddingLeft=le.paddingX,Oe.style.paddingRight=le.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),le.paddingY?(Oe.style.paddingTop=le.paddingY,Oe.style.paddingBottom=le.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let Gt=le.tooltipText??"Clear chat",to=le.showTooltip??!0;Oe.setAttribute("aria-label",Gt),vt&&jt({anchor:Oe,trigger:vt,text:()=>Oe?.getAttribute("aria-label")??Gt,enabled:to})}}let Vt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Wa],xn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Hr.message,Hr.messageAndClick];B=Ha({parsers:Vt,handlers:xn,getSessionMetadata:k,updateSessionMetadata:R,emit:c.emit,documentRef:typeof document<"u"?document:null}),ee=lh(o,B,be),_.updateConfig(o),Fs(Se,_.getMessages(),ee),Nr(),vc(),Wy(),oi(_.isStreaming());let Js=o.voiceRecognition?.enabled===!0,ci=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(Js&&(ci||Rt))if(!re||!mn){let le=Vy(o.voiceRecognition,o.sendButton);le&&(re=le.micButton,mn=le.micButtonWrapper,Tt.insertBefore(mn,H),re.addEventListener("click",Kr),re.disabled=_.isStreaming())}else{let le=o.voiceRecognition??{},Ve=o.sendButton??{},yt=le.iconName??"mic",Ze=Ve.size??"40px",rt=le.iconSize??Ze,Kt=parseFloat(rt)||24;re.style.width=rt,re.style.height=rt,re.style.minWidth=rt,re.style.minHeight=rt;let dn=le.iconColor??Ve.textColor;re.innerHTML="";let Rn=se(yt,Kt,dn||"currentColor",1.5);Rn?re.appendChild(Rn):re.textContent="\u{1F3A4}";let _t=le.backgroundColor??Ve.backgroundColor;_t?re.style.backgroundColor=_t:re.style.backgroundColor="",dn?re.style.color=dn:re.style.color="var(--persona-text, #111827)",le.borderWidth?(re.style.borderWidth=le.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),le.borderColor?re.style.borderColor=le.borderColor:re.style.borderColor="",le.paddingX?(re.style.paddingLeft=le.paddingX,re.style.paddingRight=le.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),le.paddingY?(re.style.paddingTop=le.paddingY,re.style.paddingBottom=le.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Gt=le.tooltipText??"Start voice recognition",to=le.showTooltip??!1;re.setAttribute("aria-label",Gt),mn&&jt({anchor:re,trigger:mn,text:()=>re?.getAttribute("aria-label")??Gt,enabled:to}),mn.style.display="",re.disabled=_.isStreaming()}else re&&mn&&(mn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Fn&&So());if(o.attachments?.enabled===!0){if(!hn||!pt){let le=o.attachments??{},yt=(o.sendButton??{}).size??"40px";En||(En=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),En.style.display="none",I.insertBefore(En,W)),Lt||(Lt=document.createElement("input"),Lt.type="file",Lt.accept=(le.allowedTypes??io).join(","),Lt.multiple=(le.maxFiles??4)>1,Lt.style.display="none",Lt.setAttribute("aria-label","Attach files"),I.insertBefore(Lt,W)),hn=y("div","persona-send-button-wrapper"),pt=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),pt.type="button",pt.setAttribute("aria-label",le.buttonTooltipText??"Attach file");let Ze=le.buttonIconName??"paperclip",rt=yt,Kt=parseFloat(rt)||40,dn=Math.round(Kt*.6);pt.style.width=rt,pt.style.height=rt,pt.style.minWidth=rt,pt.style.minHeight=rt,pt.style.fontSize="18px",pt.style.lineHeight="1";let Rn=se(Ze,dn,"currentColor",1.5);Rn?pt.appendChild(Rn):pt.textContent="\u{1F4CE}",pt.addEventListener("click",Gt=>{Gt.preventDefault(),Lt?.click()}),hn.appendChild(pt);let _t=le.buttonTooltipText??"Attach file";jt({anchor:pt,trigger:hn,text:()=>pt?.getAttribute("aria-label")??_t}),fn?fn.append(hn):I.appendChild(hn),!Ct&&Lt&&En&&(Ct=wr.fromConfig(le),Ct.setPreviewsContainer(En),Lt.addEventListener("change",async()=>{Ct&&Lt?.files&&(await Ct.handleFileSelect(Lt.files),Lt.value="")}))}else{hn.style.display="";let le=o.attachments??{};Lt&&(Lt.accept=(le.allowedTypes??io).join(","),Lt.multiple=(le.maxFiles??4)>1),Ct&&Ct.updateConfig({allowedTypes:le.allowedTypes,maxFileSize:le.maxFileSize,maxFiles:le.maxFiles})}if(we.querySelector(".persona-attachment-drop-overlay")?.remove(),we.appendChild(ch(o.attachments?.dropOverlay)),pt){let le=o.attachments??{},Ve=le.buttonTooltipText??"Attach file";pt.setAttribute("aria-label",Ve),pt.textContent="";let yt=parseFloat(o.sendButton?.size??"40px")||40,Ze=se(le.buttonIconName??"paperclip",Math.round(yt*.6),"currentColor",1.5);Ze?pt.appendChild(Ze):pt.textContent="\u{1F4CE}",hn&&jt({anchor:pt,trigger:hn,text:()=>pt?.getAttribute("aria-label")??Ve})}}else hn&&(hn.style.display="none"),Ct&&Ct.clearAttachments(),we.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},Ys=Nt.useIcon??!1,pi=Nt.iconText??"\u2191",Jr=Nt.iconName,ui=Nt.tooltipText??"Send message",Wc=Nt.showTooltip??!1,fr=Nt.size??"40px",eo=Nt.backgroundColor,mr=Nt.textColor;if(Ys){if(h.style.width=fr,h.style.height=fr,h.style.minWidth=fr,h.style.minHeight=fr,h.style.fontSize="18px",h.style.lineHeight="1",mr?h.style.color=mr:h.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(h.innerHTML="",Jr){let le=parseFloat(fr)||24,Ve=mr?.trim()||"currentColor",yt=se(Jr,le,Ve,2);yt?h.appendChild(yt):h.textContent=pi}else h.textContent=pi;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",eo?(h.style.backgroundColor=eo,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",eo?(h.style.backgroundColor=eo,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),mr?h.style.color=mr:h.classList.add("persona-text-white");Nt.borderWidth?(h.style.borderWidth=Nt.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),Nt.borderColor?h.style.borderColor=Nt.borderColor:h.style.borderColor="",Nt.paddingX?(h.style.paddingLeft=Nt.paddingX,h.style.paddingRight=Nt.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),Nt.paddingY?(h.style.paddingTop=Nt.paddingY,h.style.paddingBottom=Nt.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),_.isStreaming()||h.setAttribute("aria-label",ui),H&&jt({anchor:h,trigger:H,text:()=>h.getAttribute("aria-label")??ui,enabled:Wc});let Yr=$o(o,Z());tc(),Yr?(Se.style.maxWidth=Yr,Se.style.marginLeft="auto",Se.style.marginRight="auto",Se.style.width="100%",G.style.maxWidth=Yr,G.style.marginLeft="auto",G.style.marginRight="auto",G.style.width="100%",I&&(I.style.maxWidth=Yr,I.style.marginLeft="auto",I.style.marginRight="auto"),M&&(M.style.maxWidth=Yr,M.style.marginLeft="auto",M.style.marginRight="auto"),D.style.maxWidth=Yr,D.style.marginLeft="auto",D.style.marginRight="auto"):(Se.style.maxWidth="",Se.style.marginLeft="",Se.style.marginRight="",Se.style.width="",G.style.maxWidth="",G.style.marginLeft="",G.style.marginRight="",G.style.width="",I&&(I.style.maxWidth="",I.style.marginLeft="",I.style.marginRight=""),M&&(M.style.maxWidth="",M.style.marginLeft="",M.style.marginRight=""),D.style.maxWidth="",D.style.marginLeft="",D.style.marginRight="");let Eo=o.statusIndicator??{},Zy=Eo.visible??!0;if(D.style.display=Zy?"":"none",_){let le=_.getStatus();Sn(D,(yt=>yt==="idle"?Eo.idleText??Dt.idle:yt==="connecting"?Eo.connectingText??Dt.connecting:yt==="connected"?Eo.connectedText??Dt.connected:yt==="error"?Eo.errorText??Dt.error:Dt[yt])(le),Eo,le)}D.classList.remove("persona-text-left","persona-text-center","persona-text-right");let eb=Eo.align==="left"?"persona-text-left":Eo.align==="center"?"persona-text-center":"persona-text-right";D.classList.add(eb)},open(){ce()&&ut(!0,"api")},close(){ce()&&ut(!1,"api")},toggle(){ce()&&ut(!Y,"api")},reconnect(){_.reconnectNow()},clearChat(){Vn=!1,_.clearMessages(),sr.clear(),Co();try{localStorage.removeItem(Ts),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ts}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ts)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),b?.clear&&ac(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},B.syncFromMetadata(),Pe?.clear(),$e?.reset(),Ae?.update()},setMessage(l){return!W||_.isStreaming()?!1:(!Y&&ce()&&ut(!0,"system"),W.value=l,W.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let u=l?.trim()||W.value.trim();return u?(!Y&&ce()&&ut(!0,"system"),W.value="",W.style.height="auto",_.sendMessage(u),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!Y&&ce()&&ut(!0,"system"),Ge.manuallyDeactivated=!1,Pn(),_.toggleVoice().then(()=>{Ge.active=_.isVoiceActive(),Xn("user"),_.isVoiceActive()&&Vr()})),!0):Fn?!0:ku()?(!Y&&ce()&&ut(!0,"system"),Ge.manuallyDeactivated=!1,Pn(),ai("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Ge.active=!1,Ge.manuallyDeactivated=!0,Pn(),Xn("user"),Zn()}),!0):!1:Fn?(Ge.manuallyDeactivated=!0,Pn(),So("user"),!0):!1},injectMessage(l){return!Y&&ce()&&ut(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!Y&&ce()&&ut(!0,"system");let u=_.injectAssistantMessage(l);return he&&(he=!1,te&&(clearTimeout(te),te=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),u},injectUserMessage(l){return!Y&&ce()&&ut(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!Y&&ce()&&ut(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!Y&&ce()&&ut(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!Y&&ce()&&ut(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!Y&&ce()&&ut(!0,"system"),_.injectTestEvent(l)},async connectStream(l,u){return _.connectStream(l,u)},__pushEventStreamEvent(l){Pe&&($e?.processEvent(l.type,l.payload),Pe.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!me||!Pe||Vl()},hideEventStream(){ie&&Ps()},isEventStreamVisible(){return ie},showArtifacts(){Zt(o)&&(Vn=!1,Br=!0,Kn(),Ye?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(Vn=!0,Kn())},upsertArtifact(l){return Zt(o)?($n(o.features?.artifacts,{artifactType:l.artifactType,...l.artifactType==="markdown"&&l.file?{file:l.file}:{},...l.presentation?{presentation:l.presentation}:{}})==="panel"&&(Vn=!1,Br=!0),_.upsertArtifact(l)):null},selectArtifact(l){Zt(o)&&_.selectArtifact(l)},clearArtifacts(){Zt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return N&&!Y&&!Z()||!W?!1:(W.focus(),!0)},async resolveApproval(l,u,m){let w=_.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===l);if(!w?.approval)throw new Error(`Approval not found: ${l}`);if(w.approval.toolType==="webmcp"){_.resolveWebMcpApproval(w.id,u);return}return _.resolveApproval(w.approval,u,m)},setFollowUpSuggestions(l){iy(l)},clearFollowUpSuggestions(){Zp()},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...f}},updatePersistentMetadata(l){R(l)},on(l,u){return c.on(l,u)},off(l,u){c.off(l,u)},isOpen(){return ce()&&Y},isVoiceActive(){return Ge.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:ce()&&Y,launcherEnabled:N,voiceActive:Ge.active,streaming:_.isStreaming()}},showCSATFeedback(l){!Y&&ce()&&ut(!0,"system");let u=Se.querySelector(".persona-feedback-container");u&&u.remove();let m=Rl({onSubmit:async(v,w)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(v,w),l?.onSubmit?.(v,w)},onDismiss:l?.onDismiss,...l});Se.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!Y&&ce()&&ut(!0,"system");let u=Se.querySelector(".persona-feedback-container");u&&u.remove();let m=Il({onSubmit:async(v,w)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(v,w),l?.onSubmit?.(v,w)},onDismiss:l?.onDismiss,...l});Se.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return _.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return _.submitNPSFeedback(l,u)},destroy(){wc(),ur!=null&&(clearInterval(ur),ur=null),Ne.forEach(l=>l()),Le.remove(),nt?.remove(),Pt?.destroy(),Xt?.remove(),or&&ue.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,u={controller:Wt,getMessages:Wt.getMessages,getStatus:Wt.getStatus,getMetadata:Wt.getPersistentMetadata,updateMetadata:Wt.updatePersistentMetadata,clearHistory:()=>Wt.clearChat(),setVoiceActive:m=>m?Wt.startVoiceRecognition():Wt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ne.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=F=>{let V=F.detail;(!V?.instanceId||V.instanceId===l)&&Wt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ne.push(()=>{window.removeEventListener("persona:focusInput",u)}),me){let F=Q=>{let fe=Q.detail;(!fe?.instanceId||fe.instanceId===l)&&Wt.showEventStream()},V=Q=>{let fe=Q.detail;(!fe?.instanceId||fe.instanceId===l)&&Wt.hideEventStream()};window.addEventListener("persona:showEventStream",F),window.addEventListener("persona:hideEventStream",V),Ne.push(()=>{window.removeEventListener("persona:showEventStream",F),window.removeEventListener("persona:hideEventStream",V)})}let m=F=>{let V=F.detail;(!V?.instanceId||V.instanceId===l)&&Wt.showArtifacts()},v=F=>{let V=F.detail;(!V?.instanceId||V.instanceId===l)&&Wt.hideArtifacts()},w=F=>{let V=F.detail;V?.instanceId&&V.instanceId!==l||V?.artifact&&Wt.upsertArtifact(V.artifact)},L=F=>{let V=F.detail;V?.instanceId&&V.instanceId!==l||typeof V?.id=="string"&&Wt.selectArtifact(V.id)},U=F=>{let V=F.detail;(!V?.instanceId||V.instanceId===l)&&Wt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",w),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",U),Ne.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",w),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",U)})}let vn=bw(o.persistState);if(vn&&ce()){let l=vw(vn.storage),u=`${vn.keyPrefix}widget-open`,m=`${vn.keyPrefix}widget-voice`,v=`${vn.keyPrefix}widget-voice-mode`;if(l){let w=vn.persist?.openState&&l.getItem(u)==="true",L=vn.persist?.voiceState&&l.getItem(m)==="true",U=vn.persist?.voiceState&&l.getItem(v)==="true";if(w&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Wt.open(),setTimeout(()=>{if(L||U)Wt.startVoiceRecognition();else if(vn.persist?.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0)),vn.persist?.openState&&(c.on("widget:opened",()=>{l.setItem(u,"true")}),c.on("widget:closed",()=>{l.setItem(u,"false")})),vn.persist?.voiceState&&(c.on("voice:state",F=>{l.setItem(m,F.active?"true":"false")}),c.on("user:message",F=>{l.setItem(v,F.viaVoice?"true":"false")})),vn.clearOnChatClear){let F=()=>{l.removeItem(u),l.removeItem(m),l.removeItem(v)},V=()=>F();window.addEventListener("persona:clear-chat",V),Ne.push(()=>{window.removeEventListener("persona:clear-chat",V)})}}}if(C&&ce()&&(Pt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Wt.open()},0)),Ur(),!ly){let l=Zr(()=>{_&&(nc++,sr.clear(),Fs(Se,_.getMessages(),ee))});Ne.push(l)}return Wt};var dh=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},ww=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Aw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Sw=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},ph=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},op=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=""},uh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",op(e)},ep=e=>{e.style.transition=""},tp=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=""},np=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Bl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Tw=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},Ew=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},Mw=e=>{let t=_o(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(t,r)??r;return{inset:o(n?.inset,$i),canvasBackground:o(n?.canvasBackground,ji)}},gh=(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},kw=(e,t,n,o,r,s,a,i)=>{let p=rn(s),d=p.reveal==="push",c=i!=null,g=i?.inset??"",b=i?.canvasBackground??"";Tw(e,t,n,o,d),Ew(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=e.ownerDocument.defaultView,x=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,S=f!=null?f.innerWidth<=C:!1;if(x&&S&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),tp(t),ep(o),uh(o),np(n),Bl(r,o),gh(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??$t),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),uh(o),ww(o,p.maxHeight),gh(o,c&&a,g,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",tp(t),ep(o),np(n),Bl(r,o);let R=p.animate?"transform 180ms ease":"none",E=p.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":E;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=R,o.style.transform=P,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",ep(o),op(o),Bl(r,o);let R=dh(p.width,e.clientWidth),E=Math.max(0,e.clientWidth),P=p.animate?"margin-left 180ms ease":"none",B=p.side==="right"?a?-R:0:a?0:-R;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=`${E+R}px`,t.style.transition=P,t.style.marginLeft=`${B}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}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="",tp(t),op(o),np(n),Bl(r,o);let R=p.reveal==="emerge";R?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let E=a?p.width:"0px",P=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",B=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",Aw(o,p.maxHeight),o.style.overflow=R||B?"hidden":"visible",o.style.transition=P,R){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let N=c?`calc(${dh(p.width,e.clientWidth)}px - (2 * ${g}))`:p.width;r.style.width=N,r.style.minWidth=N,r.style.maxWidth=N,r.style.boxSizing="border-box"}}},Lw=(e,t)=>{let n=e.ownerDocument.createElement("div");return ph(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ph(n,o)},destroy(){n.remove()}}},Pw=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,f=()=>{b?.disconnect(),b=null},x=null,C=()=>{x=t?.launcher?.detachedPanel===!0?Mw(t):null};C();let S=()=>{kw(a,i,p,d,c,t,g,x)},k=null,R=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=ps(()=>{C(),S()}))},E=()=>{f(),rn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{S()}),b.observe(a)))},P=!1,B=()=>{S(),E(),g&&!P&&a.dataset.personaDockMobileFullscreen!=="true"&&(P=!0,Sw(a,rn(t)))},N=a.ownerDocument.defaultView,$=()=>{B()};return N?.addEventListener("resize",$),rn(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),B(),R(),{mode:"docked",host:c,shell:a,syncWidgetState(z){let q=z.launcherEnabled?z.open:!0;g!==q&&(g=q,B())},updateConfig(z){t=z,(t?.launcher?.enabled??!0)===!1&&(g=!0),C(),B(),R()},destroy(){N?.removeEventListener("resize",$),k?.(),k=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},Da=(e,t)=>Mt(t)?Pw(e,t):Lw(e,t);var Rw=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},fh=(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)},rp=e=>{let t=Rw(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Da(t,r),a,i=[],p=(S,k)=>{let E=!(k?.launcher?.enabled??!0)||Mt(k),P=o.createElement("div");if(P.setAttribute("data-persona-root","true"),E&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0",P.style.minWidth="0"),n){let B=S.attachShadow({mode:"open"});B.appendChild(P),fh(B,o)}else S.appendChild(P),fh(S,o);return t.id&&P.setAttribute("data-persona-instance",t.id),P},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},g=()=>{let S=p(s.host,r);a=Hl(S,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(S=>S()),i=[],a.destroy()};g(),e.onChatReady?.();let f=S=>{b(),s.destroy(),s=Da(t,S),r=S,g()},x={update(S){let k=El(r??{},S),R=Mt(r),E=Mt(k),P=Ko(r),B=Ko(k);if(R!==E||P!==B){f(k);return}r=k,s.updateConfig(r),a.update(S),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(x,{get(S,k,R){if(k==="host")return s.host;if(k in S)return Reflect.get(S,k,R);let E=a[k];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function Iw(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function Ww(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:Iw(o,n)?2:3}function mh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Dl(e,t){let n=t.trim();if(!n)return[...e].sort(mh);let o=[];for(let r of e){let s=Ww(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:mh(r.item,s.item)),o.map(r=>r.item)}function Hw(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function hh(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Dl(e.items,t),resolve:e.resolve}}function yh(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>Dl(t,Hw(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var wh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Bw=new Set(["button","a","input","select","textarea","details","summary"]),Dw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),sp=/\b(product|card|item|listing|result)\b/i,ip=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ow=3e3,Nw=100;function Ah(e){let t=typeof e.className=="string"?e.className:"";if(sp.test(t)||e.id&&sp.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&sp.test(o.value))return!0}return!1}function Sh(e){return ip.test((e.textContent??"").trim())}function Th(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 Fw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bh(e){let t=e.match(ip);return t?t[0]:null}function vh(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 _w(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var $w="commerce-card",jw="result-card";function xh(e){return!Ah(e)||!Sh(e)||!Th(e)&&!Fw(e)?0:5200}function Ch(e){return!Ah(e)||Sh(e)||!Th(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var lp=[{id:$w,scoreElement(e){return xh(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||ip.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(xh(e)===0)return null;let{title:n,href:o}=vh(e),r=bh((e.textContent??"").trim())??bh(t.text)??"",s=_w(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
- `)}},{id:jw,scoreElement(e){return Ch(e)},formatSummary(e,t){if(Ch(e)===0)return null;let{title:n,href:o}=vh(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
- `)}}];function Uw(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function zw(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??lp;return i==="simple"&&e.rules&&e.rules.length>0?(Uw(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function ap(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var qw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Vw(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"||Bw.has(t)||n&&Dw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Eh(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 Kw(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let 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 cp(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${ap(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of qw){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${ap(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>ap(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function Gw(e){return e==="static"?Nw:Ow}function Mh(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:cp(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:Vw(e),attributes:Kw(e)}}function Jw(e,t,n,o){let r=Gw(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function Yw(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 Xw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(wh.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Eh(d)){i=a.nextNode();continue}let g=Mh(d,e.maxTextLength),b=g.text.length>0,f=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(S=>S==="role");if(!b&&!f){i=a.nextNode();continue}if(o.has(g.selector)){i=a.nextNode();continue}o.add(g.selector);let{score:x,formattingRule:C}=Jw(d,g,e.rules,n);r.push({el:d,domIndex:s,enriched:g,score:x,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let g=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return g!==b?g-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;Yw(p,d)||p.push(d)}return p.sort((d,c)=>{let g=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return g!==b?g-b:g===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let g={...d.enriched};return c&&(g.formattedSummary=c),g})}function Qw(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if(wh.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Eh(p)){s=r.nextNode();continue}let c=Mh(p,e.maxTextLength),g=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(f=>f==="role");if(!g&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.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 kh(e={}){let t=zw(e),n=t.root??document.body;return n?t.mode==="simple"?Qw(t,n):Xw(t,n):[]}var Ol=100;function Lh(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
145
- ${s.map(a=>`- ${a.split(`
141
+ ${Me?"background: transparent !important;":""}
142
+ `)}if(!h&&!a){let Ht="max-height: -moz-available !important; max-height: stretch !important;",dn=c?"":"padding-top: 1.25em !important;",sa=c?"":`z-index: ${o.launcher?.zIndex??Xt} !important;`;L.style.cssText+=Ht+dn+sa}$n()},Nd=()=>{e.style.setProperty("--persona-content-max-width",br(o,le()))},pf=()=>{if(le())return;let a=Ct(o),c=o.launcher?.sidebarMode??!1;if(a||c||(o.launcher?.fullHeight??!1)||!j)return;let h=e.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,E=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=E)return;let z=h.innerHeight,$=64,J=o.launcher?.heightOffset??0,q=Math.max(200,z-$),ne=Math.min(640,q);O.style.height=`${Math.max(200,ne-J)}px`};_d(),rs(e,o),za(e,o),Ua(e,o),Nd(),Pr=()=>{_d(),pf(),rs(e,o),za(e,o),Ua(e,o),Nd(),Za?e.style.setProperty("--persona-artifact-welded-outer-radius",Za):e.style.removeProperty("--persona-artifact-welded-outer-radius"),Zt(),wt()};let ke=[];ke.push(()=>{d.forEach(a=>a()),l.destroy()}),ke.push(()=>{document.removeEventListener("keydown",lf)}),ke.push(()=>{Ei!==null&&clearTimeout(Ei)});let oo=null,ro=null;ke.push(()=>{oo?.(),oo=null,ro?.(),ro=null}),Pi&&ke.push(()=>{Pi?.disconnect(),Pi=null}),ke.push(()=>{Ii?.(),Ii=null,Dd(),yt&&(yt.remove(),yt=null),_e?.element.style.removeProperty("width"),_e?.element.style.removeProperty("maxWidth"),_e?.destroy()}),He&&ke.push(()=>{Ut!==null&&(cancelAnimationFrame(Ut),Ut=null),at?.destroy(),at=null,Ae?.destroy(),Ae=null,Ne=null});let Hr=null,uf=()=>{Hr&&(Hr(),Hr=null),o.colorScheme==="auto"&&(Hr=ai(()=>{rs(e,o)}))};uf(),ke.push(()=>{Hr&&(Hr(),Hr=null)}),ke.push(y);let il=o.features?.streamAnimation;if(il?.type&&il.type!=="none"){let a=pi(il.type,il.plugins);a&&(qc(a,e),ke.push(()=>Pb(e)))}let Ao=_a(xt),gf=_a(dt),ff=_a(st),Ir=[Ao,gf,ff];ke.push(()=>{Ir.forEach(a=>a.destroy())});let Rr=null,D,Wr=null,mf=!1,hf=0,yf=null,bf=a=>a.reduce((c,f)=>f.role==="user"?c+1:c,0),vf=a=>{for(let c=a.length-1;c>=0;c--)if(Zr(a[c]))return a[c].id??null;return null},Cf=!1,zC=()=>{Cf||o.debug!==!0||(Cf=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},wf=!1,xf=!1,Sf=(a,c)=>{wf||o.debug!==!0||!c.enabled||c.expose||mf||xf&&(D.isStreaming()||a.some(Zr)||(wf=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},Ts=a=>{if(!D)return;let c=a??D.getMessages(),f=q=>{q.render([],D,he,c)},h=q=>{Ir.forEach(ne=>{ne!==q&&f(ne)})};Wr&&(bf(c)>hf||vf(c)!==yf)&&(Wr=null);let C=ur(o);Sf(c,C);let E=C.enabled?rc(c):null,z=Wr??E,$=Wr?"host":"agent";if(z){let q=o.suggestions?.followUps,ne=q?.placement??(q?"auto":"composer"),fe=(ne==="auto"?le()?"composer":"after-message":ne)==="after-message"?ff:Ao;h(fe),fe.render(z,D,he,c,o.suggestionChipsConfig,{source:$,surface:"followUp",variant:q?.variant??"chip",behavior:q?.behavior??"send",overflow:q?.overflow??"wrap",maxItems:q?.maxItems??4,config:o,plugins:i});return}if(c.some(q=>q.role==="user")){Ir.forEach(f);return}let J=o.suggestions?.starters;if(J){let q=Ar(zo(o),c),ne=J.placement??"auto",ie=ne==="auto"?q?"welcome":"composer":ne;if(ie==="welcome"&&!q){zC(),Ir.forEach(f);return}let fe=ie==="welcome"?gf:Ao;h(fe),fe.render(J.items??o.suggestionChips,D,he,c,o.suggestionChipsConfig,{surface:"starter",variant:J.variant??"card",behavior:J.behavior??"send",overflow:J.overflow??"wrap",maxItems:J.maxItems??4,config:o,plugins:i});return}h(Ao),Ao.render(o.suggestionChips,D,he,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:i})},Af=()=>{Wr&&(Wr=null,Ts())},UC=a=>{let c=Array.isArray(a)?[...a]:[];if(!c.length){Af();return}let f=D?D.getMessages():[];Wr=c,mf=!0,hf=bf(f),yf=vf(f),Ts(f)},An=!1,Tn=fb(),Es=new Map,Br=new Map,Jo=new Map,Fd=0,qC=Bo()!==null,En=vb(),Mn=0,Xo=null,mn=!1,al=!1,Qo=0,Ft=null,Or=null,$d=!1,Ms=!1,Dr=null,Ri=!0,ll=!1,ks=null,cl=!1,_r=()=>{cl=!0,YC()},jd=null,VC=4,To=24,KC=80,GC=1e3,Eo=null,Tf=()=>{e.setAttribute("data-persona-scrollbar",Pd()),Pd()!=="on-scroll"&&(Eo!==null&&clearTimeout(Eo),Eo=null,K.removeAttribute("data-persona-scrollbar-visible"))},YC=()=>{Pd()==="on-scroll"&&(K.setAttribute("data-persona-scrollbar-visible",""),Eo!==null&&clearTimeout(Eo),Eo=setTimeout(()=>{Eo=null,ls(K,To)&&K.removeAttribute("data-persona-scrollbar-visible")},GC))};Tf(),ke.push(()=>{Eo!==null&&clearTimeout(Eo)});let zd=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ef=o.voiceRecognition?.autoResume??!1,Mo=a=>{m.emit("voice:state",{active:je.active,source:a,timestamp:Date.now()})},Jn=()=>{W(a=>({...a,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},JC=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=wg(T.voiceState),c=!!a.active,f=Number(a.timestamp??0);je.manuallyDeactivated=!!a.manuallyDeactivated,c&&Date.now()-f<XE&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?D.toggleVoice().then(()=>{je.active=D.isVoiceActive(),Mo("restore"),D.isVoiceActive()&&Fs()}):$l("restore"))},1e3)},XC=()=>D?_v(D.getMessages()).filter(a=>!a.__skipPersist):[],dl=null,Mf=(a,c)=>{typeof console<"u"&&console.error(a,c)},pl=(a,c)=>{let f=()=>{try{let z=a();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch($=>{Mf(c,$)})}catch(z){return Mf(c,z),null}},h=dl,C=h?h.then(()=>f()??void 0):f();if(!C)return;let E=C.finally(()=>{dl===E&&(dl=null)});dl=E};function Ud(a){if(!x?.save)return;let f={messages:a?_v(a):D?XC():[],metadata:T,artifacts:Gn.artifacts,selectedArtifactId:Gn.selectedId};pl(()=>x.save(f),"[AgentWidget] Failed to persist state:")}let Ps=null,kf=()=>L.querySelector("#persona-scroll-container")||K,Ls=()=>{Ps!==null&&(cancelAnimationFrame(Ps),Ps=null),mn=!1},Pf=()=>{Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),al=!1,Ls()},QC=()=>An&&Vd()&&(Sn()!=="anchor-top"||$g()),qd=()=>{let a=Si()||"Jump to latest",c=QC();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),Qo>0?(Mr.textContent=String(Qo),Mr.style.display="",Wt.setAttribute("aria-label",`${a} (${Qo} new)`)):(Mr.textContent="",Mr.style.display="none",Wt.setAttribute("aria-label",c?`${a} (response streaming below)`:a))},Lf=()=>{Qo!==0&&(Qo=0,qd())},ZC=()=>{let a=Ft?.spacerHeight??0;return a<=0?ls(K,To):ml(a)-K.scrollTop-K.clientHeight<=To},Vd=()=>Yo()?!En.isFollowing():!ZC(),Kd=()=>!!D&&D.getMessages().length>0,$t=()=>{if(!OC()||vs()){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==G&&G.appendChild(Wt),kr();let c=ho(K)>0&&Vd()&&Kd();c?qd():Lf(),Wt.style.display=c?"":"none"},Wi=()=>{En.pause()&&(Pf(),$t())},hn=()=>{En.resume(),Lf(),$t()},Zo=(a=!1)=>{Yo()&&Kd()&&En.isFollowing()&&(!a&&!An||(Xo!==null&&(cancelAnimationFrame(Xo),Xo=null),al=!0,Xo=requestAnimationFrame(()=>{Xo=null,al=!1,En.isFollowing()&&ew(kf(),a?220:140)})))},Hf=(a,c,f,h=()=>!0)=>{let C=a.scrollTop,E=c(),z=E-C;if(Ls(),Math.abs(z)<1){mn=!0,a.scrollTop=E,Mn=a.scrollTop,mn=!1;return}let $=performance.now();mn=!0;let J=ne=>1-Math.pow(1-ne,3),q=ne=>{if(!h()){Ls();return}let ie=c();ie!==E&&(E=ie,z=E-C);let fe=ne-$,Je=Math.min(fe/f,1),vt=J(Je),Vt=C+z*vt;a.scrollTop=Vt,Mn=a.scrollTop,Je<1?Ps=requestAnimationFrame(q):(a.scrollTop=E,Mn=a.scrollTop,Ps=null,mn=!1)};Ps=requestAnimationFrame(q)},ew=(a,c=500)=>{let f=ho(a)-a.scrollTop;if(Math.abs(f)<1){Mn=a.scrollTop;return}if(Math.abs(f)>=KC){Ls(),mn=!0,a.scrollTop=ho(a),Mn=a.scrollTop,mn=!1;return}Hf(a,()=>ho(a),c,()=>En.isFollowing())},ul=()=>{if(!Kd()){$t();return}let a=kf();mn=!0,a.scrollTop=ho(a),Mn=a.scrollTop,mn=!1,$t()},Nr=a=>{let c=0,f=a;for(;f&&f!==K;)c+=f.offsetTop,f=f.offsetParent;return c},tw=()=>{let a=K.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??K.ownerDocument.getSelection()},gl=()=>xb(tw(),K),Gd=()=>{if(DC()!=="last-user-turn")return!1;let a=D?.getMessages()??[];if(a.length<2)return!1;let c=[...a].reverse().find(E=>E.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=K.querySelector(`[data-message-id="${f}"]`);if(!h)return!1;let C=Math.min(Math.max(0,Nr(h)-Ai()),ho(K));return mn=!0,K.scrollTop=C,Mn=K.scrollTop,mn=!1,Sn()==="follow"&&!ls(K,To)&&En.pause(),$t(),!0},fl=a=>{let c=Math.max(0,Math.round(a));Bn.style.height=`${c}px`,Bn.style.display=c>0?"":"none",Ft&&(Ft.spacerHeight=Math.max(0,a))},ml=a=>{let c=parseFloat(getComputedStyle(K).paddingBottom)||0,f=0;for(let C of Array.from(K.children)){if(C===Bn||C.offsetHeight===0)continue;let E=Nr(C)+C.offsetHeight;E>f&&(f=E)}let h=K.scrollHeight-a;return f>0?Math.min(f+c,h):h},nw=()=>{if(!Ft||Ft.spacerHeight<=0)return;let a=ml(Ft.spacerHeight),c=Math.max(0,Math.round(K.scrollTop)+K.clientHeight-a+To);c<Ft.spacerHeight&&(fl(c),$t())},Xn=()=>{Or!==null&&(cancelAnimationFrame(Or),Or=null),Ls(),Ft=null,Bn.style.height="0px",Bn.style.display="none"},If=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yd=a=>K.querySelector(`[data-message-id="${If(a)}"]`),Rf=a=>{Or!==null&&cancelAnimationFrame(Or),Or=requestAnimationFrame(()=>{Or=null;let c=If(a),f=K.querySelector(`[data-message-id="${c}"]`);if(!f)return;let h=Nr(f),C=Ft?.spacerHeight??0,E=ml(C),{targetScrollTop:z,spacerHeight:$}=Ru({anchorOffsetTop:h,topOffset:Ai(),viewportHeight:K.clientHeight,contentHeight:E,slack:To});Ft={initialSpacerHeight:$,contentHeightAtAnchor:E,spacerHeight:$},fl($),Hf(K,()=>f.isConnected?Math.max(0,Nr(f)-Ai()):z,220)})},ko=()=>{if(Sn()!=="anchor-top"||!Ft||!ks)return;let a=Yd(ks);if(!a)return;Ls();let c=Ft.spacerHeight,f=ml(c),{targetScrollTop:h,spacerHeight:C}=Ru({anchorOffsetTop:Nr(a),topOffset:Ai(),viewportHeight:K.clientHeight,contentHeight:f,slack:To});Ft={initialSpacerHeight:C,contentHeightAtAnchor:f,spacerHeight:C},fl(C),mn=!0,K.scrollTop=h,Mn=K.scrollTop,mn=!1,$t()},ow=()=>{if(Yo()){if(!En.isFollowing()||ls(K,1))return;Zo(!An);return}if(Ft&&Ft.initialSpacerHeight>0){let a=K.scrollHeight-Ft.spacerHeight,c=Sb({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:a});c!==Ft.spacerHeight&&fl(c)}$t()},rw=a=>{let c=Sn();c==="follow"?(hn(),Zo(!0)):c==="anchor-top"&&(Ri=!1,ll=!0,cl=!1,ks=a,Rf(a))},sw=()=>{if(Sn()==="anchor-top"){if(ll){Ri=!1;return}Ri=!0,Xn(),hn(),Zo(!0)}},iw=96,aw=a=>{if(Dr===null)return!0;let c=Yd(Dr),f=Yd(a);if(!c||!f)return!0;let h=Nr(f)-Nr(c);return Ai()+h>K.clientHeight-iw},lw=a=>{if(Sn()!=="anchor-top"||!ll||cl||gl())return;let c=Dr===null;for(let f of a){if(!c){f.id===Dr&&(c=!0);continue}if(bb(f)){if(f.id===ks||!aw(f.id))return;ks=f.id,Rf(f.id);return}}},cw=a=>{let c=new Map;a.forEach(f=>{let h=zd.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!h&&f.role==="assistant"&&(m.emit("assistant:message",f),!Ms&&(Sn()!=="anchor-top"||$g())&&Vd()&&(Qo+=1,qd(),$t(),zg(Qo===1?"1 new message below.":`${Qo} new messages below.`))),f.role==="assistant"&&h?.streaming&&f.streaming===!1&&m.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(h?f.approval.status!=="pending"&&m.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):m.emit("approval:requested",{approval:f.approval,message:f}))}),zd.clear(),c.forEach((f,h)=>{zd.set(h,f)})},hl=(a,c)=>{let f=c==="user"?"user":"assistant",h=o.layout?.messages?.[f],C=h?.width??"content",E=h?.maxWidth??(C==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${c}`,`persona-message-width-${C}`),a.classList.toggle("persona-justify-end",c==="user"),a.setAttribute("data-message-role",c),a.setAttribute("data-message-width",C),a.style.setProperty("--persona-message-row-max-width",E)},Fr=(a,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${a}`,f.setAttribute("data-wrapper-id",a),hl(f,c),f},dw=(a,c,f)=>{let h=document.createElement("div"),E=(()=>{let N=i.find(Pe=>Pe.renderLoadingIndicator);if(N?.renderLoadingIndicator)return N.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),z=(N,Pe)=>Pe==null?!1:typeof Pe=="string"?(N.textContent=Pe,!0):(N.appendChild(Pe),!0),$=new Set,J=new Map,q=new Set,ne=i.some(N=>N.renderAskUserQuestion),ie=[],fe=[],Je=o.enableComponentStreaming!==!1,vt=o.approval!==!1,Vt=[];if(c.forEach(N=>{$.add(N.id),J.set(N.id,N.role);let Pe=ne&&Oo(N),Ie=vt&&N.variant==="approval"&&!!N.approval,Te=!Pe&&N.role==="assistant"&&!N.variant&&Je&&Ya(N);!Ie&&Jo.has(N.id)&&(a.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(N.id)),!Te&&Br.has(N.id)&&(a.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Br.delete(N.id));let Mt=Oo(N)?`:${N.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${N.agentMetadata?.askUserQuestionAnswers?Object.keys(N.agentMetadata.askUserQuestionAnswers).length:0}`:"",pt=gb(N,Fd)+Mt,Kt=Pe||Ie||Te?null:mb(Tn,N.id,pt);if(Kt){h.appendChild(Kt.cloneNode(!0)),Oo(N)&&N.toolCall?.id&&N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(q.add(N.toolCall.id),Js(N,o,Q.composerOverlay));return}let ct=null,ln=i.find(Re=>!!(N.variant==="reasoning"&&Re.renderReasoning||N.variant==="tool"&&Re.renderToolCall||!N.variant&&Re.renderMessage)),Yt=o.layout?.messages;if(Oo(N)&&N.agentMetadata?.askUserQuestionAnswered===!0){Es.delete(N.id),a.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime");return}if(Zr(N)&&ur(o).enabled)return;if(Oo(N)&&o.features?.askUserQuestion?.enabled!==!1){let Re=i.find(cn=>typeof cn.renderAskUserQuestion=="function");if(Re&&it.current){let cn=Es.get(N.id),zt=cn!==pt,Me=null;if(zt){let{payload:Ve,complete:Ot}=Do(N),Lt=N.id,tn=()=>it.current?.getMessages().find($n=>$n.id===Lt);Me=Re.renderAskUserQuestion({message:N,payload:Ve,complete:Ot,resolve:$n=>{let Ke=tn();Ke&&it.current?.resolveAskUserQuestion(Ke,$n)},dismiss:()=>{let $n=tn();$n?.agentMetadata?.awaitingLocalTool&&(it.current?.markAskUserQuestionResolved($n),it.current?.resolveAskUserQuestion($n,"(dismissed)"))},config:o})}let Bt=cn!=null;if(zt&&Me===null&&!Bt){N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(q.add(N.toolCall.id),Js(N,o,Q.composerOverlay));return}let ut=Fr(N.id,N.role);ut.setAttribute("data-ask-plugin-stub","true"),ut.setAttribute("data-preserve-runtime","true"),h.appendChild(ut),ie.push({messageId:N.id,fingerprint:pt,bubble:Me});return}else{N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(q.add(N.toolCall.id),Js(N,o,Q.composerOverlay));return}}else if(Ie){let Re=i.find(Bt=>typeof Bt.renderApproval=="function")??g,zt=Jo.get(N.id)!==pt,Me=null;if(zt&&Re?.renderApproval){let Bt=N.id,ut=(Ve,Ot)=>{let Lt=it.current?.getMessages().find(tn=>tn.id===Bt);Lt?.approval&&(Lt.approval.toolType==="webmcp"?it.current?.resolveWebMcpApproval(Lt.id,Ve):it.current?.resolveApproval(Lt.approval,Ve,Ot))};Me=Re.renderApproval({message:N,defaultRenderer:()=>sd(N,o),config:o,approve:Ve=>ut("approved",Ve),deny:Ve=>ut("denied",Ve)})}if(zt&&Me===null)a.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(N.id),ct=sd(N,o);else{let Bt=Fr(N.id,N.role);Bt.setAttribute("data-approval-plugin-stub","true"),Bt.setAttribute("data-preserve-runtime","true"),h.appendChild(Bt),Vt.push({messageId:N.id,fingerprint:pt,bubble:Me});return}}else if(ln)if(N.variant==="reasoning"&&N.reasoning&&ln.renderReasoning){if(!Se)return;ct=ln.renderReasoning({message:N,defaultRenderer:()=>og(N,o),config:o})}else if(N.variant==="tool"&&N.toolCall&&ln.renderToolCall){if(!Le)return;ct=ln.renderToolCall({message:N,defaultRenderer:()=>sg(N,o),config:o})}else ln.renderMessage&&(ct=ln.renderMessage({message:N,defaultRenderer:()=>{let Re=mi(N,f,Yt,o.messageActions,F,{loadingIndicatorRenderer:E,widgetConfig:o});return N.role!=="user"&&fg(Re,N,o,D),Re},config:o}));if(!ct&&Te){let Re=md(N);if(Re){let cn=Br.get(N.id),zt=cn!==pt,Me=o.wrapComponentDirectiveInBubble!==!1&&to.getOptions(Re.component)?.bubbleChrome!==!1,Bt=null;if(zt){let ut=fd(Re,{config:o,message:N,transform:f});if(ut&&Re.component==="PersonaArtifactInline"){let Ve=ut.hasAttribute("data-artifact-inline")?ut:ut.querySelector("[data-artifact-inline]"),Ot=Ve?.getAttribute("data-artifact-inline")??"",Lt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ot):Ot,tn=Ot?a.querySelector(`#wrapper-${N.id}`)?.querySelector(`[data-artifact-inline="${Lt}"]`)??null:null;Ve&&tn&&tn!==Ve&&ab(tn)&&(Ve===ut?ut=tn:Ve.replaceWith(tn))}if(ut)if(Me){let Ve=document.createElement("div");if(Ve.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ve.id=`bubble-${N.id}`,Ve.setAttribute("data-message-id",N.id),N.content&&N.content.trim()){let Ot=document.createElement("div");Ot.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ot.innerHTML=f({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ve.appendChild(Ot)}Ve.appendChild(ut),Bt=Ve}else{let Ve=document.createElement("div");if(Ve.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ve.id=`bubble-${N.id}`,Ve.setAttribute("data-message-id",N.id),Ve.setAttribute("data-persona-component-directive","true"),N.content&&N.content.trim()){let Ot=document.createElement("div");Ot.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ot.innerHTML=f({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ve.appendChild(Ot)}Ve.appendChild(ut),Bt=Ve}}if(Bt||cn!=null){let ut=Fr(N.id,N.role);ut.setAttribute("data-component-directive-stub","true"),ut.setAttribute("data-preserve-runtime","true"),h.appendChild(ut),fe.push({messageId:N.id,fingerprint:pt,bubble:Bt});return}}}if(!ct)if(N.variant==="reasoning"&&N.reasoning){if(!Se)return;ct=og(N,o)}else if(N.variant==="tool"&&N.toolCall){if(!Le)return;ct=sg(N,o)}else if(N.variant==="approval"&&N.approval){if(o.approval===!1)return;ct=sd(N,o)}else{let Re=o.layout?.messages;Re?.renderUserMessage&&N.role==="user"?ct=Re.renderUserMessage({message:N,config:o,streaming:!!N.streaming}):Re?.renderAssistantMessage&&N.role==="assistant"?ct=Re.renderAssistantMessage({message:N,config:o,streaming:!!N.streaming}):ct=mi(N,f,Re,o.messageActions,F,{loadingIndicatorRenderer:E,widgetConfig:o}),N.role!=="user"&&ct&&fg(ct,N,o,D)}let jt=Fr(N.id,N.role);jt.appendChild(ct),hb(Tn,N.id,pt,jt),h.appendChild(jt)}),Q.composerOverlay&&Q.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Pe=>{let Ie=Pe.getAttribute("data-persona-ask-sheet-for");Ie&&!q.has(Ie)&&dr(Q.composerOverlay,Ie)}),o.features?.toolCallDisplay?.grouped){let N=[],Pe=[],Ie=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Te=>{if(Te.variant==="tool"&&Te.toolCall&&Le){Pe.push(Te);return}Te.variant==="reasoning"&&!Se||((Pe.length>1||Ie&&Pe.length>0)&&N.push(Pe),Pe=[])}),(Pe.length>1||Ie&&Pe.length>0)&&N.push(Pe),N.forEach(Te=>{let Mt=Te.map(Re=>Array.from(h.children).find(cn=>cn instanceof HTMLElement&&cn.getAttribute("data-wrapper-id")===Re.id)).filter(Re=>!!Re);if(Mt.length<(Ie?1:2))return;let pt=Fr(`tool-group-${Te[0].id}`,"assistant");pt.setAttribute("data-persona-tool-group-row","true");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 ct=document.createElement("div");ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ct.id=`tool-group-summary-${Te[0].id}`;let ln=`Called ${Te.length} ${Te.length===1?"tool":"tools"}`,Yt=o.toolCall?.renderGroupedSummary?.({messages:Te,toolCalls:Te.map(Re=>Re.toolCall).filter(Re=>!!Re),defaultSummary:ln,config:o});z(ct,Yt)||(ct.textContent=ln);let jt=document.createElement("div");jt.className="persona-tool-group-stack persona-flex persona-flex-col",jt.id=`tool-group-stack-${Te[0].id}`,jt.setAttribute("data-persona-tool-group-stack","true"),Kt.appendChild(ct),Ie||Kt.appendChild(jt),pt.appendChild(Kt),Mt[0].before(pt),Mt.forEach((Re,cn)=>{if(Ie){Re.remove();return}Re.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),cn<Mt.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(Re),jt.appendChild(zt)})})}yb(Tn,$);let bn=c.some(N=>N.role==="assistant"&&N.streaming),Et=c[c.length-1],Pt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(An&&c.some(N=>N.role==="user")&&!bn&&!Pt){let N={config:o,streaming:!0,location:"standalone",defaultRenderer:us},Pe=i.find(Te=>Te.renderLoadingIndicator),Ie=null;if(Pe?.renderLoadingIndicator&&(Ie=Pe.renderLoadingIndicator(N)),Ie===null&&o.loadingIndicator?.render&&(Ie=o.loadingIndicator.render(N)),Ie===null&&(Ie=us()),Ie){let Te=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1,pt=o.layout?.messages?.layout??"bubble";Te.className=Mt?Na("assistant",pt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Te.setAttribute("data-typing-indicator","true"),Mt&&(Te.style.color="var(--persona-message-assistant-text, var(--persona-text))",pt!=="flat"&&(Te.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Te.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Te.appendChild(Ie);let Kt=Fr("typing-indicator","assistant");Kt.appendChild(Te),h.appendChild(Kt)}}if(!An&&c.length>0){let N=c[c.length-1],Pe={config:o,lastMessage:N,messageCount:c.length},Ie=i.find(Mt=>Mt.renderIdleIndicator),Te=null;if(Ie?.renderIdleIndicator&&(Te=Ie.renderIdleIndicator(Pe)),Te===null&&o.loadingIndicator?.renderIdle&&(Te=o.loadingIndicator.renderIdle(Pe)),Te){let Mt=document.createElement("div"),pt=o.loadingIndicator?.showBubble!==!1;Mt.className=pt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Mt.setAttribute("data-idle-indicator","true"),Mt.appendChild(Te);let Kt=Fr("idle-indicator","assistant");Kt.appendChild(Mt),h.appendChild(Kt)}}if(wh(h),$c(a,h),Jp(a),ie.length>0)for(let{messageId:N,fingerprint:Pe,bubble:Ie}of ie){let Te=a.querySelector(`#wrapper-${N}`);Te&&(hl(Te,J.get(N)??"assistant"),Ie!==null&&(Te.replaceChildren(Ie),Te.setAttribute("data-bubble-fp",Pe),Es.set(N,Pe)))}if(Es.size>0)for(let N of Es.keys())$.has(N)||Es.delete(N);if(fe.length>0)for(let{messageId:N,fingerprint:Pe,bubble:Ie}of fe){let Te=a.querySelector(`#wrapper-${N}`);Te&&(hl(Te,J.get(N)??"assistant"),Ie!==null&&(Te.replaceChildren(Ie),Te.setAttribute("data-bubble-fp",Pe),Br.set(N,Pe)))}if(Br.size>0)for(let N of Br.keys())$.has(N)||Br.delete(N);if(Vt.length>0)for(let{messageId:N,fingerprint:Pe,bubble:Ie}of Vt){let Te=a.querySelector(`#wrapper-${N}`);Te&&(hl(Te,J.get(N)??"assistant"),Ie!==null&&(Te.replaceChildren(Ie),Te.setAttribute("data-bubble-fp",Pe),Jo.set(N,Pe)))}if(Jo.size>0)for(let N of Jo.keys())$.has(N)||Jo.delete(N)},Bi=(a,c,f)=>{dw(a,c,f),rf()},Oi=null,pw=()=>{if(Oi)return;let a=f=>{let h=f.composedPath();h.includes(L)||Y&&h.includes(Y)||lt(!1,"user")};Oi=a,(e.ownerDocument??document).addEventListener("pointerdown",a,!0)},Wf=()=>{if(!Oi)return;(e.ownerDocument??document).removeEventListener("pointerdown",Oi,!0),Oi=null};ke.push(()=>Wf());let Di=null,uw=()=>{if(Di)return;let a=f=>{f.key==="Escape"&&(f.isComposing||lt(!1,"user"))};Di=a,(e.ownerDocument??document).addEventListener("keydown",a,!0)},Bf=()=>{if(!Di)return;(e.ownerDocument??document).removeEventListener("keydown",Di,!0),Di=null};ke.push(()=>Bf());let _i=!1,Of=new Set,gw=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Hs=()=>{if(!le())return;let a=Q.peekBanner,c=Q.peekTextNode;if(!a||!c)return;if(M){a.classList.remove("persona-pill-peek--visible");return}let f=D?.getMessages()??[],h;for(let Et=f.length-1;Et>=0;Et--){let Pt=f[Et];if(Pt.role==="assistant"&&Pt.content){h=Pt;break}}if(!h){a.classList.remove("persona-pill-peek--visible");return}let C=h.content,E=!!h.streaming,z=gw(),$=jc(z),J=$.type!=="none"?pi($.type,z?.plugins):null,q=J?.isAnimating?.(h)===!0,ne=J!==null&&(E||q);ne&&J&&!Of.has(J.name)&&(qc(J,e),Of.add(J.name));let ie=ne&&J?.containerClass?J.containerClass:null,fe=c.dataset.personaPeekStreamClass??null;fe&&fe!==ie&&(c.classList.remove(fe),delete c.dataset.personaPeekStreamClass),ie&&fe!==ie&&(c.classList.add(ie),c.dataset.personaPeekStreamClass=ie),ne?(c.style.setProperty("--persona-stream-step",`${$.speed}ms`),c.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let Je=ne?zc(C,$.buffer,J,h,E):C;if(ne&&$.placeholder==="skeleton"&&E&&(!Je||!Je.trim())){let Et=document.createElement("div"),Pt=Ba();Pt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Pt),$c(c,Et)}else{let Et=Math.max(0,Je.length-100),Pt=Je.length>100?Je.slice(-100):Je,N=co(Pt);if(!ne||!J){let Pe=Je.length>100?`\u2026${Pt}`:Pt;c.textContent!==Pe&&(c.textContent=Pe)}else{let Pe=N;(J.wrap==="char"||J.wrap==="word")&&(Pe=Wa(N,J.wrap,`peek-${h.id}`,{skipTags:J.skipTags,startIndex:Et}));let Ie=document.createElement("div");if(Ie.innerHTML=Pe,J.useCaret&&Pt.length>0){let Te=Uc(),Mt=Ie.querySelectorAll(".persona-stream-char, .persona-stream-word"),pt=Mt[Mt.length-1];pt?.parentNode?pt.parentNode.insertBefore(Te,pt.nextSibling):Ie.appendChild(Te)}$c(c,Ie),J.onAfterRender?.({container:c,bubble:a,messageId:h.id,message:h,speed:$.speed,duration:$.duration})}}let bn=An||_i;a.classList.toggle("persona-pill-peek--visible",bn)};if(le()){let a=Q.peekBanner;if(a){let h=C=>{C.preventDefault(),C.stopPropagation(),lt(!0,"user")};a.addEventListener("pointerdown",h),ke.push(()=>{a.removeEventListener("pointerdown",h)})}let c=()=>{_i||(_i=!0,Hs())},f=()=>{_i&&(_i=!1,Hs())};O.addEventListener("pointerenter",c),O.addEventListener("pointerleave",f),ke.push(()=>{O.removeEventListener("pointerenter",c),O.removeEventListener("pointerleave",f)}),Y&&(Y.addEventListener("pointerenter",c),Y.addEventListener("pointerleave",f),ke.push(()=>{Y.removeEventListener("pointerenter",c),Y.removeEventListener("pointerleave",f)}))}let fw=a=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",h=c.bottomOffset??"16px",C=c.collapsedMaxWidth,E=c.expandedMaxWidth??"880px",z=c.expandedTopOffset??"5vh",$=c.modalMaxWidth??"880px",J=c.modalMaxHeight??"min(90vh, 800px)",q="calc(100vw - 32px)",ne="var(--persona-pill-area-height, 80px)",ie=L.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",Y){let fe=Y.style;fe.bottom=h,fe.width=C??""}if(a&&f!=="fullscreen"){if(f==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=$,ie.maxWidth=q,ie.maxHeight=J,ie.height=J;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${h} + ${ne})`,ie.top=z,ie.width=E,ie.maxWidth=q}},Ni=()=>{if(!ae())return;if(le()){let q=(o.launcher?.composerBar??{}).expandedSize??"anchored",ne=M?"expanded":"collapsed";L.dataset.state=ne,L.dataset.expandedSize=q,Y&&(Y.dataset.state=ne,Y.dataset.expandedSize=q),L.style.removeProperty("display"),L.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),fw(M),G.style.display=M?"flex":"none",Pr(),M?(pw(),uw()):(Wf(),Bf()),Hs();return}let a=Ct(o),c=e.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,h=o.launcher?.mobileFullscreen??!0,C=c.innerWidth<=f,E=h&&C&&j,z=wn(o).reveal;M?(L.style.removeProperty("display"),L.style.display=a?"flex":"",L.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-95","persona-opacity-0"),O.classList.add("persona-scale-100","persona-opacity-100"),At?(At.setPanelOpen(!0),At.element.style.display="none"):an&&(an.style.display="none")):(a?a&&(z==="overlay"||z==="push")&&!E?(L.style.removeProperty("display"),L.style.display="flex",L.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(L.style.setProperty("display","none","important"),L.classList.remove("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(L.style.display="",L.classList.add("persona-pointer-events-none","persona-opacity-0"),O.classList.remove("persona-scale-100","persona-opacity-100"),O.classList.add("persona-scale-95","persona-opacity-0")),At?(At.setPanelOpen(!1),At.element.style.display=a?"none":""):an&&(an.style.display=a?"none":""))},lt=(a,c="user")=>{if(!ae()||M===a)return;let f=M;M=a,Ni();let h=(()=>{let E=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,$=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,q=z.innerWidth<=J,ne=Ct(o)&&$&&q,ie=le()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return E||$&&q&&j||ne||ie})();if(M&&h){if(!oo){let E=e.getRootNode(),z=E instanceof ShadowRoot?E.host:e.closest(".persona-host");z&&(oo=Ou(z,o.launcher?.zIndex??Xt))}ro||(ro=Du(e.ownerDocument))}else M||(oo?.(),oo=null,ro?.(),ro=null);M&&(oa(),Gd()||(Sn()==="follow"?Zo(!0):ul()));let C={open:M,source:c,timestamp:Date.now()};M&&!f?m.emit("widget:opened",C):!M&&f&&m.emit("widget:closed",C),m.emit("widget:state",{open:M,launcherEnabled:j,voiceActive:je.active,streaming:D.isStreaming()})},Fi=a=>{Ng(a?"stop":"send"),re&&(re.disabled=a),Ir.forEach(c=>{c.elements.forEach(f=>{f.toggleAttribute("data-disabled",a),f instanceof HTMLButtonElement||f.setAttribute("aria-disabled",a?"true":"false")}),c.buttons.forEach(f=>{f.disabled=a})}),Zd.forEach(c=>{c.toggleAttribute("data-disabled",a),c instanceof HTMLButtonElement?c.disabled=a:c.setAttribute("aria-disabled",a?"true":"false"),c.querySelectorAll("button").forEach(f=>{f.disabled=a})}),$e.dataset.personaComposerStreaming=a?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(c=>{(c instanceof HTMLButtonElement||c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)&&(c.disabled=a)})},$r=()=>{je.active||he&&he.focus()};m.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>$r(),200)});let jr=null,$i=!1,Jd=!fn.hidden,er=null,Df=!H,_f=null,Nf,Ff=null,Is=null,Xd=!1,ji=a=>{let c=zo(o),f=`${c.variant}|${c.dismiss}|${c.title}|${c.subtitle}`;(f!==_f||c.icon!==Nf)&&(_f=f,Nf=c.icon,nd({host:fn,iconHolder:PC,title:LC,subtitle:HC,starterSuggestions:dt},c));let h=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;h!==Ff&&(Ff=h,od(xn,c.message,o));let C=a??(D?D.getMessages():o.initialMessages),E=$i,z=!E&&Ar(c,C),$=z!==Jd;if(Jd=z,Is){er?.cancel(),er=null,E!==Xd&&(Xd=E,E?Xu(K,fn,null):Ju(K,fn,Is)),hi(K,fn,!E);return}if($&&!z&&!E&&c.dismiss==="on-first-message"&&Df){er=$b(fn,q=>{er===q&&(er=null),!Jd&&!Is&&(hi(K,fn,!1),ko()),q?.cancel()});return}if(er){if(!z&&!E)return;er.cancel(),er=null}let J=!fn.hidden;hi(K,fn,z),!z&&J&&ko()},Qd=[],Zd=[],ep=!1,$f=null,jf,zf=()=>{Zd.length=0;let a=Qd.splice(0,Qd.length);for(let c of a)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};ke.push(zf);let mw=(a,c)=>{let f=Nu(a,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let h=o.suggestions?.starters,C=Fu({item:{...f,behavior:f.behavior??h?.behavior??"send"},index:c,surface:"starter",source:"config",variant:h?.variant??"card",streaming:u?D.isStreaming():!1,config:o,plugins:i,chipsConfig:o.suggestionChipsConfig,session:D,getTextarea:()=>he,eventTarget:fn});return Zd.push(C),C},tp=()=>{if(ep)return;ep=!0;let a=zo(o);$f=`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,jf=a.icon;try{zf(),Xu(K,fn,Is),Is=null,Xd=!1;let c=D?D.getMessages():o.initialMessages,f=Ar(a,c),h=0,C=null;for(let E of i)if(E.renderWelcome&&(C=E.renderWelcome({config:a,variant:a.variant,visible:f,defaultRenderer:()=>fn,sendMessage:z=>{if(!D||D.isStreaming())return;let $=z.trim();$&&D.sendMessage($)},requestRender:()=>tp(),renderStarter:z=>mw(z,h++),storage:p(E.id),onCleanup:z=>{Qd.push(z)}}),C))break;C&&C!==fn&&(Is=C,Ju(K,fn,C))}finally{ep=!1}ji()},hw=()=>{let a=zo(o);`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===$f&&a.icon===jf||tp()},np=()=>{ji(),Mi||(he.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!D?.isStreaming()&&(be.textContent=o.copy?.sendButtonLabel??"Send")),he.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',he.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},yw=!!o.setStoredConversationId,zi=a=>W(c=>{let f={...c};return delete f[a],f}),yl=a=>{let c=T[a];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>yl("sessionId"),setStoredSessionId:a=>{W(c=>({...c,sessionId:a}))},clearStoredSessionId:o.clearStoredSessionId??(()=>zi("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>yl("conversationId")),setStoredConversationId:o.setStoredConversationId??(a=>{W(c=>({...c,conversationId:a}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>zi("conversationId"))});let Uf=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,qf=a=>kv(a,We(),o.persistState===!1),Vf=Uf(),Po=Vf?qf(Vf):null,zr={...Po?{visitorStore:Po}:{},historyBootstrapReady:P,getStoredMessageCursor:()=>yl("historyMessageCursor"),setStoredMessageCursor:a=>{if(a===null){zi("historyMessageCursor");return}W(c=>({...c,historyMessageCursor:a}))},getPendingDisplayProjections:()=>{let a=T.pendingDisplayProjections;if(!a||typeof a!="object")return null;let c=a;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:a=>{if(!a){zi("pendingDisplayProjections");return}W(c=>({...c,pendingDisplayProjections:a}))},...yw?{}:{getStoredConversationRevision:()=>yl("conversationRevision"),setStoredConversationRevision:a=>{if(a===null){zi("conversationRevision");return}W(c=>({...c,conversationRevision:a}))}}},bw=()=>{let a=Uf();if(a&&Po?.matches(a,We(),o.persistState===!1)||!a&&!Po)return;Po?.destroy(),Po=a?qf(a):null;let c={...zr};Po?c.visitorStore=Po:delete c.visitorStore,zr=c,D.setHistoryInternals(zr)},Ur=null,vw=()=>{Ur==null&&(Ur=setInterval(()=>{let a=ce.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Ur),Ur=null;return}let c=Date.now();a.forEach(f=>{let h=Number(f.getAttribute("data-tool-elapsed"));h&&(f.textContent=ic(c-h))})},100))},op=(a,c)=>{if(Object.is(a,c))return!0;if(a===null||c===null||typeof a!="object"||typeof c!="object")return!1;if(Array.isArray(a)||Array.isArray(c))return!Array.isArray(a)||!Array.isArray(c)||a.length!==c.length?!1:a.every((z,$)=>op(z,c[$]));let f=a,h=c,C=Object.keys(f),E=Object.keys(h);return C.length===E.length&&C.every(z=>Object.prototype.hasOwnProperty.call(h,z)&&op(f[z],h[z]))},Kf=a=>{let{content:c,rawContent:f,llmContent:h,...C}=a;return C},rp=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Ya(a),Cw=(a,c,f)=>{if(a.length!==c.length)return!1;let h=a[f.index],C=c[f.index];return!h||!C||h.id!==f.id||C.id!==f.id?!1:(!Object.is(h.content,C.content)||!Object.is(h.rawContent,C.rawContent)||!Object.is(h.llmContent,C.llmContent))&&rp(h)&&rp(C)&&op(Kf(h),Kf(C))},sp=null,Rs=null,qr=null,Lo=null,bl=a=>{sp=a;let c,f;Rs=null;for(let C=a.length-1;C>=0;C-=1){let E=a[C];if(!c&&E.role==="user"&&(c=E),!f&&E.role==="assistant"&&(f=E),!Rs&&rp(E)&&(Rs={index:C,id:E.id}),c&&f&&Rs)break}Bi(ce,a,me),Pu(ce,Gn.artifacts,{suppressTransition:An}),vw(),ji(a),Ts(a),Zo(!An),cw(a),a.length===0&&(Xn(),Ri=!0,ll=!1,ks=null,cl=!1),!$d||Ms?($d=!0,Dr=c?.id??null,jd=f?.id??null):c&&c.id!==Dr?(Dr=c.id,rw(c.id)):f&&f.id!==jd&&sw(),f&&(jd=f.id),lw(a);let h=je.lastUserMessageId;c&&c.id!==h&&(je.lastUserMessageId=c.id,m.emit("user:message",c)),je.lastUserMessageWasVoice=!!c?.viaVoice,Ud(a),Hs()},ip=()=>{Lo!==null&&(cancelAnimationFrame(Lo),Lo=null);let a=qr;qr=null,a&&bl(a)},Gf=()=>{Lo!==null&&cancelAnimationFrame(Lo),Lo=null,qr=null},ww=a=>{let c=qr??sp;if(An&&c&&Rs&&Cw(c,a,Rs)){qr=a,Lo===null&&(Lo=requestAnimationFrame(()=>{Lo=null;let f=qr;qr=null,f&&bl(f)}));return}if(a.length===0){Gf(),bl(a);return}ip(),bl(a)};D=new oi(o,{onMessagesChanged(a){ww(a)},onStatusChanged(a){let c=o.statusIndicator??{};S(on,(h=>h==="idle"?c.idleText??Nt.idle:h==="connecting"?c.connectingText??Nt.connecting:h==="connected"?c.connectedText??Nt.connected:h==="error"?c.errorText??Nt.error:h==="paused"?c.pausedText??Nt.paused:h==="resuming"?c.resumingText??Nt.resuming:Nt[h])(a),c,a),Ko()},onStreamingChanged(a){a||(D?.getMessages().length===0?Gf():ip()),An=a,Fi(a),Ko(),D&&Bi(ce,D.getMessages(),me),a||(Zo(!0),nw(),xf=!0,D&&Sf(D.getMessages(),ur(o))),$t(),zg(a?"Responding\u2026":"Response complete."),Hs()},onVoiceStatusChanged(a){if(m.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Wo(),Fs();break;case"processing":Wo(),gx();break;case"speaking":Wo(),fx();break;default:a==="idle"&&D.isBargeInActive()?(Wo(),Fs(),re?.setAttribute("aria-label","End voice session")):(je.active=!1,Wo(),Mo("system"),Jn());break}},onArtifactsState(a){Gn=a,a.artifacts.length===0&&(xs=!1),Pu(ce,a.artifacts,{suppressTransition:An}),So(),Ud()},onHistoryStateChanged(a){vo(a)},onHistoryNotice(a){Rt(a)},onReconnect(a){let{executionId:c,lastEventId:f}=a.handle;a.phase==="paused"?m.emit("stream:paused",{executionId:c,after:f}):a.phase==="resuming"?m.emit("stream:resuming",{executionId:c,after:f,attempt:a.attempt??1}):m.emit("stream:resumed",{executionId:c,after:f})}},zr),it.current=D,ke.push(()=>D.cancel()),ke.push(()=>{D.destroy(),Po?.destroy()});let ap=null;if(D.onReadAloudChange((a,c)=>{nf=a,of=c,rf();let f=a??ap;a&&(ap=a);let h=f?D.getMessages().find(C=>C.id===f)??null:null;m.emit("message:read-aloud",{messageId:f,message:h,state:c,timestamp:Date.now()}),c==="idle"&&(ap=null)}),u=!0,$d=!0,o.voiceRecognition?.provider?.type==="runtype")try{D.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}let xw=720,Sw=250,qe=Cg(o.features?.history?.copy),kn=null,lp=!1,Ze=null,vl=null,Cl="conversation",cp=null,sn=null,so=null,wl=D.getHistoryState(),dp=null,xl=0,pp=null,Sl=null,Al=null,up=`persona-history-${Math.random().toString(36).slice(2,8)}`,gp=()=>o.features?.history?.enabled===!0,io=()=>gp()&&!!kn&&!lp,Yf=()=>{let a=D.getStatus();return An||a==="paused"||a==="resuming"},fp=()=>{let a=o.features?.history?.scope;if(a)return a;let c=o.getIdentityProof?"verified-user":"browser",f=kn?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Ws=()=>vl?.scope??fp(),Jf=()=>D.getClientSession()?.targetId??null,Xf=a=>`${a.state}:${"reason"in a?a.reason:""}`,Aw=a=>{let c=Xf(a);c!==dp&&(dp=c,m.emit("history:identityStatusChanged",{status:a,timestamp:Date.now()}))},Tl=a=>{a&&(wo.textContent="",wo.textContent=a)},Qf=null,Zf=null,Tw=()=>{if(!gp())return null;let a=Iv();if(a)return a();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(Qf!==c&&(Qf=c,Zf=c()),Zf):D.isClientTokenMode()?Rv({client:D.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>D.bindActivatedSession(f),getClient:()=>D.getClient()}):null},em=()=>{Sl?.(),Sl=null,Al?.(),Al=null,lp=!1,kn=Tw();let a={...zr};kn?a.historyProvider=kn:delete a.historyProvider,zr=a,D.setHistoryInternals(zr),kn&&(Sl=kn.subscribeAvailability?.(c=>{lp=!c,c||yn({restoreFocus:!1}),nr()})??null,Al=kn.subscribeIdentityStatus(c=>Aw(c)),dp=Xf(kn.getIdentityStatus()))},mp=()=>{let a=o.features?.history?.presentation??"panel";if(a==="panel"||a==="auto"&&!(!j||Ct(o)))return"panel";let c=no??G;return(c.getBoundingClientRect().width||c.clientWidth)>=xw?"rail":"panel"},On=(a,c)=>{c?(a.setAttribute("aria-hidden","true"),a.setAttribute("inert","")):(a.removeAttribute("aria-hidden"),a.removeAttribute("inert"))},El="data-persona-history-suppressed",Pn=null,tr=null,Vr=null,Ui=null,hp=null,tm="",nm=()=>Ee===hp?tm:o.layout?.showHeader===!1?"none":"",Ew=()=>nt==="panel"&&!!Vr&&Ui===Vr.element&&o.layout?.showHeader!==!1&&nm()!=="none",Mw=()=>{for(let a of Array.from(Ee.children))a!==Pn&&a.setAttribute(El,"")},kw=()=>{for(let a of Array.from(G.querySelectorAll(`[${El}]`)))a.removeAttribute(El)},Pw=()=>{let a=Vr;if(!a)return;if(Array.from(Ee.children).some(h=>h!==Pn&&!h.hasAttribute(El))){tr&&tr!==Ee&&(tr.style.removeProperty("min-height"),tr=null);let h=Ee.offsetHeight;h>0&&(Ee.style.minHeight=`${h}px`,tr=Ee)}Pn||(Pn=v("div","persona-history-header-host")),a.setHeaderPlacement("external");let f=a.getHeaderElement();f.parentNode!==Pn&&Pn.replaceChildren(f),Pn.parentNode!==Ee&&Ee.appendChild(Pn),Mw()},om=()=>{tr&&(tr.style.removeProperty("min-height"),tr=null),Pn&&(Vr?.setHeaderPlacement("inline"),Pn.remove(),Pn=null,kw())},Ml=null,yp=()=>{if(Ml){if(K.style.display="none",On(K,!0),$e.hidden=!0,On($e,!0),Ew()){Pw(),Ee.style.display=nm(),On(Ee,!1);return}om(),Ee.style.display="none",On(Ee,!0)}};wt=yp;let Lw=a=>{let c=K.style.display,f=$e.hidden,h=$e,C=Ee,E=Ee.style.display;hp=C,tm=E,Ml=()=>{Ml=null,om(),hp=null,K.style.display=c,On(K,!1),h.hidden=f,On(h,!1),$e!==h&&($e.hidden=!1,On($e,!1)),C.style.display=E,On(C,!1),Ee!==C&&(Ee.style.display=o.layout?.showHeader===!1?"none":"",On(Ee,!1))},$e.parentNode?.insertBefore(a,$e),yp()},qi=null,Bs=null,Vi=null,rm=()=>[Ee,Q.closeButtonWrapper,Q.clearChatButtonWrapper,K,$e],Hw=52,kl=()=>o.features?.history?.rail?.collapsible!==!1,Os=()=>o.features?.history?.rail?.side==="right"?"right":"left",bp=200,vp=400,Cp=a=>Math.min(vp,Math.max(bp,Math.round(a))),Iw=()=>o.features?.history?.rail?.resizable===!0,Ki,Rw=()=>{if(Ki===void 0&&(Ki=null,o.persistState!==!1))try{let a=Number(window.localStorage.getItem(`${We()}rail-width`));a&&(Ki=a)}catch{}return Ki},Gi=()=>Cp(Rw()??o.features?.history?.rail?.width??260),Ww=a=>{if(Ki=a,o.persistState!==!1)try{window.localStorage.setItem(`${We()}rail-width`,String(a))}catch{}},Pl=()=>kl()&&o.features?.history?.rail?.collapsedBehavior==="overlay",qt=!1,sm=a=>{let c=v("img");return c.src=a,c.alt="",c.setAttribute("aria-hidden","true"),c},Bw=()=>{let a=o.features?.history?.rail?.brand;if(!a)return;let c=!1,f;return h=>{if(a.render)try{return a.render({collapsed:h})??null}catch(C){return c||(c=!0,console.warn("[persona] history rail brand threw",C)),null}return f===void 0&&(a.iconUrl?f=sm(a.iconUrl):f=a.icon?de(a.icon,20):null),f?f.cloneNode(!0):null}},Ow=()=>o.features?.history?.rail?.sections?.map(a=>{let c=!1,f=h=>{c||(c=!0,console.warn("[persona] history rail section threw",a.id,h))};return{id:a.id,title:a.title,placement:a.placement??"above-conversations",items:a.items.map(h=>{let C;return{id:h.id,label:h.label,badge:h.badge,iconNode:()=>{if(C!==void 0)return C;try{h.renderIcon?C=h.renderIcon()??null:h.iconUrl?C=sm(h.iconUrl):C=h.icon?de(h.icon,20):null}catch(E){f(E),C=null}return C},onSelect:()=>{try{h.onSelect()}catch(E){f(E)}}}})}})??[],Dw=a=>{let c=Ow();for(let f of a)c.some(h=>h.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},Yi=null,im=()=>`${We()}rail-collapsed`,wp=()=>{if(Yi===null&&(Yi=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let a=window.localStorage.getItem(im());a&&(Yi=a==="1")}catch{}return Yi},xp=a=>{if(Yi=a,o.persistState!==!1)try{window.localStorage.setItem(im(),a?"1":"0")}catch{}},Ji=()=>nt==="rail"&&kl()&&!Pl()&&wp(),Sp=()=>{},am=()=>{if(Pl()){Sp();return}xp(!wp()),Ze?.view.setCollapsed(Ji()),Zt(),ko()},Ap=()=>{let a=o.features?.history?.rail?.collapseShortcut;return!a||!Pc(a)?null:{combo:a,hint:Lc(a),aria:ka(a)}},lm=()=>{d.forEach(c=>c()),d=[];let a=Ap();a&&d.push(l.register({id:"history-rail-collapse",combo:a.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>et&&nt==="rail"&&kl()||Xi(),run:()=>Pl()?Sp():am()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=e.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of i)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};lm();let _w=300,Ll="var(--persona-history-overlay-margin,8px)",Dn=null,Ho=null,Io=null,Ds=null,Kr=!1,Tp=0,cm=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,Xi=()=>io()&&Pl()&&(nt??mp())==="rail",Nw=()=>et&&!qt,Qi=()=>{Ds!==null&&clearTimeout(Ds),Ds=null},Fw=()=>{yg().catch(()=>{})},dm=()=>{Qi(),qt&&(Ds=setTimeout(()=>{Ds=null,!(Kr||!qt)&&(Io?.contains(document.activeElement)||yn({restoreFocus:!1}))},_w))},$w=(a,c)=>{let f=Io?.getBoundingClientRect();if(!f)return!1;let h=Dn?.getBoundingClientRect(),C=h?Math.min(h.top,f.top):f.top;return a>=f.left&&a<=f.right&&c>=C&&c<=f.bottom||!!h&&a>=h.left&&a<=h.right&&c>=h.top&&c<=h.bottom},Ep=a=>{qt&&(Kr=$w(a.clientX,a.clientY),Kr?Qi():Ds===null&&dm())},pm=a=>{et||!Xi()||(qt=!0,Zi({invoker:Dn,keyboard:a?.keyboard===!0}).then(()=>{et?!Kr&&document.activeElement!==Dn&&yn():qt=!1}))},um=()=>{let a=Ui?.querySelector('[data-persona-history-focus="collapse"]');a&&(a.setAttribute("aria-label",qt?qe.expandLabel:qe.collapseLabel),a.setAttribute("aria-expanded",qt?"false":"true"))},gm=()=>{xp(!1);let a=Ze;if(!qt||!a){Zi({invoker:Dn});return}let c=document.activeElement===Dn;qt=!1,Pp(),a.element.remove(),Lp(a.element),um(),c&&Il(),ko(),nr()},jw=()=>{xp(!0),yn()};Sp=()=>{!et||qt?gm():jw()};let zw=()=>{let a=Ap(),c=cs({ariaLabel:qe.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":up,...a?{"aria-keyshortcuts":a.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{Kr=!0,Qi(),!(cm()||Date.now()<Tp)&&pm()}),f.addEventListener("mouseleave",()=>{Kr=!1,Tp=0,dm()}),f.addEventListener("focus",()=>{et||Fw()}),f.addEventListener("click",h=>{io()&&(h.detail!==0&&cm()&&!et?pm():gm())}),Dn=f,Ho=c.wrapper},Mp=()=>{if(Ho&&!Ho.isConnected&&(Ho=null,Dn=null),!Xi()){Ho?.remove(),Ho=null,Dn=null;return}Dn||zw();let a=Ho,c=Dn;if(!a||!c)return;let f=Os()!=="right"?Ee.firstChild:null;(f??Ee.lastChild)!==a&&Ee.insertBefore(a,f),a.style.display=Nw()?"none":"",c.setAttribute("aria-label",qe.expandLabel),c.setAttribute("aria-expanded",et?"true":"false"),Io&&Zt()},fm=a=>{if(!qt)return;let c=a.target;c instanceof Node&&(Io?.contains(c)||Ho?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||yn({restoreFocus:!1}))};document.addEventListener("pointerdown",fm,!0),ke.push(()=>{document.removeEventListener("pointerdown",fm,!0),document.removeEventListener("pointermove",Ep),_s?.(),Qi()});let kp=null,_s=null,mm=16,hm=a=>{Ww(Cp(a)),Zt(),ko()},Uw=()=>{let a=v("div","persona-rail-resizer");return a.tabIndex=0,a.setAttribute("role","separator"),a.setAttribute("aria-orientation","vertical"),a.setAttribute("aria-valuemin",String(bp)),a.setAttribute("aria-valuemax",String(vp)),a.addEventListener("pointerdown",c=>{let f=Bs;if(!f||c.button!==0)return;c.preventDefault(),_s?.();let h=c.clientX,C=f.getBoundingClientRect().width||Gi(),E=Os()==="right"?-1:1,z=C,$=e.ownerDocument;f.style.transition="none";let J=ne=>{z=Cp(C+E*(ne.clientX-h)),f.style.flex=`0 0 ${z}px`,a.setAttribute("aria-valuenow",String(z))},q=()=>{_s=null,$.removeEventListener("pointermove",J),$.removeEventListener("pointerup",q),$.removeEventListener("pointercancel",q),f.style.removeProperty("transition");try{a.releasePointerCapture(c.pointerId)}catch{}hm(z)};_s=q,$.addEventListener("pointermove",J),$.addEventListener("pointerup",q),$.addEventListener("pointercancel",q);try{a.setPointerCapture(c.pointerId)}catch{}}),a.addEventListener("keydown",c=>{let f=Os()==="right"?-mm:mm,h=Gi(),C=c.key==="ArrowRight"?h+f:c.key==="ArrowLeft"?h-f:c.key==="Home"?bp:c.key==="End"?vp:null;C!==null&&(c.preventDefault(),hm(C))}),a},qw=(a,c)=>{if(!Iw()||Ji()){_s?.(),kp?.remove();return}let f=kp??Uw();kp=f,f.setAttribute("aria-label",qe.resizeLabel),f.setAttribute("aria-valuenow",String(Gi())),f.nextElementSibling!==c&&a.insertBefore(f,c)};Zt=()=>{Ze?.view.setRailSide(Os());let a=Os()==="right",c=Io;if(c){let $=Dn?Dn.getBoundingClientRect().bottom-G.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round($))}px + ${Ll})`,c.style.width=`${Gi()}px`,c.style.left=a?"":Ll,c.style.right=a?Ll:""}let f=Bs,h=qi,C=Vi;if(!f||!h||!C)return;f.style.flex=`0 0 ${Ji()?Hw:Gi()}px`;let E="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=a?"":E,f.style.borderLeft=a?E:"";let z=a?C:f;h.firstElementChild!==z&&h.append(z,a?f:C),qw(h,a?f:C)};let Vw=a=>{let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let h=v("div","persona-history-rail-host");h.style.cssText="display:flex;min-height:0;overflow:hidden",G.insertBefore(c,Ee.parentNode===G?Ee:K);for(let C of rm())C?.parentNode===G&&f.appendChild(C);c.append(h,f),h.appendChild(a),qi=c,Bs=h,Vi=f,Zt()},Kw=a=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Ll};display:flex;overflow:hidden;z-index:${ri-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,G.style.position="relative",G.appendChild(c),c.appendChild(a),document.addEventListener("pointermove",Ep),Io=c,Zt(),um()},Pp=()=>{Ml?.(),Io&&(Kr&&(Tp=Date.now()+150),document.removeEventListener("pointermove",Ep),Io.remove(),Io=null);let a=qi;if(a){_s?.();for(let c of rm())c&&a.contains(c)&&G.insertBefore(c,a);a.remove(),qi=null,Bs=null,Vi=null}},ym=a=>{Ui=a,a.id=up,a.style.flex="1 1 auto",a.style.minHeight="0"},Lp=a=>{ym(a),nt!=="rail"?Lw(a):qt?Kw(a):Vw(a)},Hl=()=>{if(Mp(),km(),!et||!Ze)return;let a=mp();if(a===nt)return;let c=document.activeElement,f=c instanceof HTMLElement&&(Ze.element.contains(c)||Pn?.contains(c)===!0)?c:null;Pp(),Ze.element.remove(),Ze.view.setHeaderPlacement("inline"),nt=a,Ze.view.setPresentation(a),Ze.view.setCollapsed(Ji()),Ze.requestRender(),Ze.element.isConnected||Lp(Ze.element),f?.isConnected?f.focus():Il(),$t(),ko(),nr()},bm=(a,c)=>Pn?.querySelector(c)??a.querySelector(c),Il=()=>{let a=Ze?.element??Ui;if(!a)return;let c=bm(a,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=bm(a,".persona-history-title")??a;f.tabIndex=-1,f.focus()},Zi=async a=>{if(!io()||et)return;let c=kn;if(!c)return;if(!qt&&Xi()&&wp()){Mp();return}Rl();let f=++xl;Cl=a?.returnSurface??"conversation",cp=a?.invoker??sn;let h;try{h=await yg()}catch{Tl(qe.openHistoryLabel);return}if(f!==xl||et)return;vl={scope:fp()},nt=mp(),et=!0;let C=nt==="panel"&&o.layout?.showHeader!==!1&&Ee.style.display!=="none"?"external":"inline",E=o.features?.history?.rowAvatar,z=Ap(),$=z?{hint:z.hint,aria:z.aria}:null,J={provider:c,context:vl,targetId:Jf(),presentation:nt,collapsible:kl(),collapsed:Ji(),railSide:Os(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:Bw(),onToggleCollapse:am,...$?{collapseShortcut:$}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:E===!1?!1:typeof E=="string"?E:o.launcher?.iconUrl,activeConversationId:D.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:q=>Ip(q,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:q=>Gr(q),attachTooltip:Qt,onStartNew:()=>Rp({focusComposer:!0}),onClose:()=>yn(),onRequestDeleteConversation:q=>Mm(q),onRequestClearHistory:()=>Zw(),...c.resetDevice?{onRequestResetIdentity:()=>ex()}:{}};Ze=Hv({plugins:i,config:o,getPresentation:()=>nt??"panel",getReturnSurface:()=>Cl,close:()=>yn(),createView:({slots:q,renderDom:ne,onModelChange:ie,railSections:fe})=>(Vr=h.createHistoryView({...J,railSections:Dw(fe),slots:q,renderDom:ne,onModelChange:ie,onAnnounce:Tl}),Vr),onElementChanged:(q,ne)=>{if(!ne?.isConnected)return Lp(q);ym(q),ne.replaceWith(q),yp()}}),Ze.view.setNewConversationRequired(wl.recovery==="new_conversation_required"),a?.focus!==!1&&(nt!=="rail"||a?.keyboard===!0)&&Il(),$t(),ko(),nr(),m.emit("history:opened",{presentation:nt,returnSurface:Cl,timestamp:Date.now()})},Rl=()=>{},yn=a=>{if(!et)return;xl+=1;let c=Cl,f=cp,h=Ze,C=a?.restoreFocus!==!1;et=!1;let E=!1,z=null,$=()=>{if(!E){if(E=!0,Rl=()=>{},z!==null&&clearTimeout(z),qt=!1,Qi(),Pp(),h?.dispose(),h?.view.destroy(),h?.element.remove(),Ze===h&&(Ze=null,Vr=null,Ui=null,nt=null,vl=null,cp=null),$t(),ko(),nr(),C){let q=f??sn;q?.isConnected?q.focus():$r()}m.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},J=h&&h.element===h.view.element?h.view.playExit():null;if(!J){$();return}Rl=$,z=setTimeout($,Sw),J.then($)},vm=a=>{if(!(a.key!=="Escape"||!et||!Ze)){if(nt==="rail"){let c=a.target;if(!(c instanceof Node)||!(Ze.element.contains(c)||qt&&Ho?.contains(c)===!0))return}a.preventDefault(),a.stopPropagation(),yn()}};G.addEventListener("keydown",vm),ke.push(()=>G.removeEventListener("keydown",vm));let Wl=null,Cm=!1,ea=()=>{if(!Go)return;let a=o.layout?.header?.titleSource==="conversation",c=a&&Wl?.trim()||null;Go.textContent=c??o.launcher?.title??"Chat Assistant";let f=Go.closest(".persona-combo-btn");if(!f)return;let h=!a||D.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",h?"false":"true"),f.setAttribute("aria-haspopup",h?"true":"false"),h||f.setAttribute("aria-expanded","false"),f.style.cursor=h?"pointer":"default";let C=f.querySelector("svg");C&&(C.style.display=h?"":"none")},Gw=a=>{a!==Wl&&(Wl=a,ea())},Gr=a=>{Cm=a?.starred===!0,Gw(a&&a.title.trim()||null),ea()};ea(),G.addEventListener("persona:title-menu-builtin",a=>{let c=a.detail?.actionId,f=D.getActiveConversationId();f&&(c==="delete"?Mm(f):c==="star"&&D.canUpdateConversations()&&Wp(f,{starred:!Cm}).catch(()=>{}))});let Bl=0,Yw=250,Ol=null,Dl=()=>{Ol&&clearTimeout(Ol),Ol=null};ke.push(Dl);let wm=()=>{Dl();let a=jr;a&&($i=!0,a.hidden=!1,ce.style.display="none",ji())},_l=()=>{Bl+=1,Dl(),jr&&(jr.remove(),jr=null,$i=!1,ce.style.removeProperty("display"),On($e,!1),ji())},Jw=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ce.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Hp=(a,c)=>ge("div",{className:jn("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:a}}),xm=()=>ge("div",{className:"persona-conversation-loading-body"},Hp("58%",!1),Hp("72%",!0),Hp("44%",!1)),Sm=a=>{jr?.remove(),jr=a,a.hidden=!$i,K.insertBefore(a,ce),Dl(),$i||(Ol=setTimeout(wm,Yw)),On($e,!0)},Xw=()=>{let a={config:o,streaming:!1,location:"conversation-open",defaultRenderer:xm},c=null,f=i.find(h=>h.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(a)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(a)),Sm(ge("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":qe.openConversationLoadingLabel}},c??xm()))},Qw=a=>{let c=()=>{Ip(a,{focusComposer:!0}).catch(()=>{})},f=io()?()=>{_l(),Zi()}:void 0,h=($,J)=>{let q=ge("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:$});return q.addEventListener("click",J),q},C=()=>ge("div",{className:"persona-conversation-loading-error-body"},ge("p",{className:"persona-conversation-loading-error-title",text:qe.openConversationErrorTitle}),ge("div",{className:"persona-conversation-loading-error-actions"},h(qe.openConversationRetryLabel,c),f?h(qe.openConversationBackLabel,f):null)),E=Object.freeze({conversationId:a,config:o,copy:Object.freeze({title:qe.openConversationErrorTitle,retryLabel:qe.openConversationRetryLabel,backLabel:qe.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:C}),z=null;for(let $ of i)if($.renderHistoryOpenError){try{z=$.renderHistoryOpenError(E)}catch(J){console.warn("[persona] renderHistoryOpenError threw",J),z=null}if(z)break}Sm(ge("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},z??C())),wm()};m.on("history:closed",()=>{jr&&On($e,!0)});let Ip=async(a,{focusComposer:c=!1}={})=>{let f=Ws(),h=!!Ze;Ze?.view.setActiveConversationId(a),_l();let C=Bl;Xw(),et&&(nt==="panel"||qt)&&yn({restoreFocus:!1}),Ms=!0;try{await D.openConversation(a,{scope:f})}catch(E){throw C===Bl&&Qw(a),E}finally{Ms=!1}C===Bl&&(_l(),Tn.clear(),Xn(),hn(),Gd()||ul(),Jw(),Ro(),h||Gr(null),m.emit("history:conversationOpened",{conversationId:a,title:Wl,scope:f,timestamp:Date.now()}),c&&$r())},Rp=async({focusComposer:a=!1}={})=>{_l(),await D.startNewConversation({scope:Ws()}),Gr(null),Tn.clear(),Xn(),hn(),ul(),Ro();let c=D.getActiveConversationId();Ze?.view.setActiveConversationId(c),m.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),et&&(nt==="panel"||qt)&&yn({restoreFocus:!1}),a&&$r()},Wp=async(a,c)=>{let f=await D.updateConversation(a,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return Ze?.view.applyConversationSummary(f),!Ze&&a===D.getActiveConversationId()&&Gr(f),f},Am=async a=>{let c=Ws(),f=D.getActiveConversationId()===a;await D.deleteConversation(a,{scope:c}),Ze?.view.removeConversationSummary(a),f&&(Gr(null),Tn.clear(),Xn(),hn(),Ro()),m.emit("history:conversationDeleted",{conversationId:a,scope:c,wasActive:f,timestamp:Date.now()})},Tm=async a=>{let c=a?.scope??Ws(),f=a?.allTargets?null:a?.targetId??Jf(),h=await D.clearConversationHistory({...f?{targetId:f}:{},scope:c});return Gr(null),Tn.clear(),Xn(),hn(),Ro(),m.emit("history:cleared",{deleted:h.deleted,scope:c,targetId:f,timestamp:Date.now()}),h},Em=async()=>{if(!kn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let a=!1;try{a=(await D.resetHistoryDevice()).remoteRevocationConfirmed}finally{Gr(null),D.clearArtifacts(),Tn.clear(),sp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),T={},Z.syncFromMetadata(),x?.clear&&pl(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),Xn(),hn(),Ro(),yn({restoreFocus:!1}),$r(),M||At?.launcher.element.focus()}return Tl(a?qe.identityResetNotice:qe.identityResetUnconfirmedNotice),m.emit("history:identityReset",{remoteRevocationConfirmed:a,timestamp:Date.now()}),{remoteRevocationConfirmed:a}},Bp=()=>no?O:G,Mm=async a=>await ud({host:Bp(),title:qe.deleteConversationConfirmTitle,description:qe.deleteConversationConfirm,confirmLabel:qe.deleteConversationConfirmLabel,cancelLabel:qe.confirmCancelLabel})?(await Am(a),"deleted"):"cancelled",Zw=async()=>{let a=Ws()==="verified-user";return await ud({host:Bp(),title:qe.clearHistoryConfirmTitle,description:a?qe.clearHistoryVerifiedConfirm:qe.clearHistoryConfirm,confirmLabel:qe.clearHistoryConfirmLabel,cancelLabel:qe.confirmCancelLabel})?(await Tm(),"cleared"):"cancelled"},ex=async()=>{if(!await ud({host:Bp(),title:qe.resetIdentityConfirmTitle,description:qe.resetIdentityConfirm,confirmLabel:qe.resetIdentityConfirmLabel,cancelLabel:qe.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Em();return{outcome:"reset",remoteRevocationConfirmed:c}},_n=v("button","persona-history-earlier");_n.type="button",_n.textContent=qe.showEarlierMessagesLabel,_n.setAttribute("data-persona-history-earlier",""),Object.assign(_n.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Ro=()=>{if(!(io()&&!!wl.nextMessageCursor&&!!D.getActiveConversationId())){_n.remove();return}_n.textContent=qe.showEarlierMessagesLabel,_n.parentNode!==K&&K.insertBefore(_n,K.firstChild)};_n.addEventListener("click",()=>{let a=D.getActiveConversationId(),c=wl.nextMessageCursor;if(!a||!c||_n.disabled)return;_n.disabled=!0;let f=K.scrollHeight,h=K.scrollTop;D.loadOlderMessages(a,c,{scope:Ws()}).then(()=>{K.scrollTop=h+(K.scrollHeight-f),ko()}).catch(()=>{}).finally(()=>{_n.disabled=!1,Ro()})});let tx=()=>{let a=cs({ariaLabel:qe.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return a.button.addEventListener("click",c=>{if(!(!io()||Yf())){if(et){yn();return}Zi({invoker:a.button,keyboard:c.detail===0})}}),a},km=()=>{if(!io()){so?.remove(),sn=null,so=null;return}if(so&&!so.isConnected&&(sn=null,so=null),!sn&&Ee){let h=tx();sn=h.button,so=h.wrapper;let C=Q.clearChatButtonWrapper||Q.closeButtonWrapper;C?.parentNode&&Ee.contains(C)?C.parentNode.insertBefore(so,C):Ee.appendChild(so)}if(!sn||!so)return;let a=Xi()||et&&nt==="rail";if(so.style.display=a?"none":"",a){document.activeElement===sn&&Il();return}let c=Yf();sn.disabled=c,sn.setAttribute("aria-disabled",c?"true":"false");let f=c?qe.openHistoryBusyLabel:qe.openHistoryLabel;sn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(sn.removeAttribute("aria-expanded"),sn.removeAttribute("aria-controls")):(sn.setAttribute("aria-expanded",et?"true":"false"),sn.setAttribute("aria-controls",up))},Nl=!1,nx=()=>{let a=Q.clearChatButton;if(a){if(io()){Nl||(pp=a.getAttribute("aria-label")??"",Nl=!0),a.setAttribute("aria-label",qe.newConversationLabel),a.removeAttribute("title");return}Nl&&(Nl=!1,pp&&a.setAttribute("aria-label",pp))}},nr=()=>{qe=Cg(o.features?.history?.copy),km(),Mp(),nx(),Ro()};Ko=nr,vo=a=>{wl=a,Ze?.view.setNewConversationRequired(a.recovery==="new_conversation_required"),Fi(a.sendBlocked||An),Ro()},Rt=a=>{(a.code==="history_continuity_reset"||a.code==="conversation_deleted_recovered")&&(Tn.clear(),Xn(),hn()),Tl(a.message),Ze?.view.refresh()},em(),nr(),ke.push(()=>{Sl?.(),Al?.(),xl+=1,Rl(),Ze?.dispose(),Ze?.view.destroy(),Ze=null}),o.clientToken&&D.initClientSession().then(()=>{if(io())return D.reconcileBootConversation({scope:fp()})}).then(()=>{Ro()}).catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Ae||o.onSSEEvent)&&D.setSSEEventCallback((a,c)=>{o.onSSEEvent?.(a,c),Fe?.processEvent(a,c),Ae?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(c)})});let Pm=()=>{o.resume&&typeof o.reconnectStream=="function"&&D.resumeFromHandle(o.resume)};H?H.then(a=>{if(a){if(a.metadata&&(T=wg(a.metadata),Z.syncFromMetadata()),a.messages?.length){Ms=!0;try{D.hydrateMessages(a.messages)}finally{Ms=!1}}a.artifacts?.length&&D.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Df=!0,_(),Pm()}):Pm();let Lm=()=>{!le()||M||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},ox=(a,c)=>a?c?{refs:[...a.refs,...c.refs],finalize:async()=>{let[f,h]=await Promise.allSettled([a.finalize(),c.finalize()]),C=[];return f.status==="fulfilled"?C.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),h.status==="fulfilled"?C.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),rM(C)}}:a:c,rx=()=>{let c=he.getInlineMessageFields?.();return c&&c.contentSegments.some(h=>h.kind==="mention")?c.contentSegments:void 0},ta=!1,sx=async a=>{let c=he.value.trim(),f=ht?.hasAttachments()??!1,h=c?await(rn?.takeInlineCommand(c)??Promise.resolve(null)):null;if(h?.kind==="action"){he.value="",he.style.height="auto",na(),rn?.clear();return}let C=rn?.collectForSubmit()??null,E=h?.kind==="server"?h.mentions:null,z=ox(C,E),$=h?.kind==="prompt"?h.sendText:c,J=!!C&&C.refs.length>0;if(!$&&!f&&!J&&!E)return;Lm();let q;f&&(q=[],q.push(...ht.getContentParts()),$&&q.push(go($)));let ne=h?.kind==="prompt"?void 0:rx();he.value="",he.style.height="auto",na(),D.sendMessage($,{contentParts:q,mentions:z??void 0,contentSegments:ne,viaVoice:a?.viaVoice}),f&&ht.clearAttachments(),C&&rn?.clear()},Op=async a=>{if(!ta){ta=!0;try{await sx(a)}finally{ta=!1}}},Fl=a=>{if(a.preventDefault(),D.isStreaming()){D.cancel(),Fe?.reset(),at?.update();return}ta||Op()},ix=()=>o.features?.composerHistory!==!1,Dp={...Iu},_p=!1,na=()=>{Dp={...Iu}},ax=()=>D.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),lx=a=>{if(!he)return;_p=!0,he.value=a,he.dispatchEvent(new Event("input",{bubbles:!0})),_p=!1;let c=he.value.length;he.setSelectionRange(c,c)},cx=a=>{_p||(a.isComposing||rn?.handleInput(a.inputType??void 0),na())},dx=a=>{if(he&&!(!a.isComposing&&rn?.handleKeydown(a))){if(ix()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let c=he.selectionStart===0&&he.selectionEnd===0,f=ub({direction:a.key==="ArrowUp"?"up":"down",history:ax(),currentValue:he.value,atStart:c,state:Dp});if(Dp=f.state,f.handled){a.preventDefault(),f.value!==void 0&&lx(f.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(D.isStreaming()){a.preventDefault();return}if(ta){a.preventDefault();return}na(),a.preventDefault(),be.click()}}},Hm=a=>{a.key!=="Escape"||a.isComposing||D.isStreaming()&&a.composedPath().includes(G)&&(D.cancel(),Fe?.reset(),at?.update(),na(),a.preventDefault(),a.stopImmediatePropagation())},px=async a=>{if(o.attachments?.enabled!==!0||!ht)return;let c=eM(a.clipboardData);c.length!==0&&(a.preventDefault(),await ht.handleFiles(c))},Nn=null,ao=!1,Ns=null,bt=null,Im=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,$l=(a="user")=>{if(ao||D.isStreaming())return;let c=Im();if(!c)return;Nn=new c;let h=(o.voiceRecognition??{}).pauseDuration??2e3;Nn.continuous=!0,Nn.interimResults=!0,Nn.lang="en-US";let C=he.value;Nn.onresult=E=>{let z="",$="";for(let q=0;q<E.results.length;q++){let ne=E.results[q],ie=ne[0].transcript;ne.isFinal?z+=ie+" ":$=ie}let J=C+z+$;he.value=J,Ns&&clearTimeout(Ns),(z||$)&&(Ns=window.setTimeout(()=>{he.value.trim()&&Nn&&ao&&(or(),Op({viaVoice:!0}))},h))},Nn.onerror=E=>{E.error!=="no-speech"&&or()},Nn.onend=()=>{if(ao){let E=he.value.trim();E&&E!==C.trim()&&Op({viaVoice:!0}),or()}};try{if(Nn.start(),ao=!0,je.active=!0,a!=="system"&&(je.manuallyDeactivated=!1),Mo(a),Jn(),re){let E=o.voiceRecognition??{};bt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:E.iconName??"mic",iconSize:parseFloat(E.iconSize??o.sendButton?.size??"40")||24};let z=E.recordingBackgroundColor,$=E.recordingIconColor,J=E.recordingBorderColor;if(re.classList.add("persona-voice-recording"),re.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=$??"var(--persona-voice-recording-indicator, #ffffff)",$){let q=re.querySelector("svg");q&&q.setAttribute("stroke",$)}J&&(re.style.borderColor=J),re.setAttribute("aria-label","Stop voice recognition")}}catch{or("system")}},or=(a="user")=>{if(ao){if(ao=!1,Ns&&(clearTimeout(Ns),Ns=null),Nn){try{Nn.stop()}catch{}Nn=null}if(je.active=!1,Mo(a),Jn(),re){if(re.classList.remove("persona-voice-recording"),bt){re.style.backgroundColor=bt.backgroundColor,re.style.color=bt.color,re.style.borderColor=bt.borderColor;let c=re.querySelector("svg");c&&c.setAttribute("stroke",bt.color||"currentColor"),bt=null}re.setAttribute("aria-label","Start voice recognition")}}},ux=(a,c)=>{let f=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),h=a?.provider?.type==="runtype",C=a?.provider?.type==="custom";if(!(f||h||C))return null;let z=v("div","persona-send-button-wrapper"),$=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");$.type="button";let J=a?.tooltipText??"Start voice recognition";$.setAttribute("aria-label",J);let q=a?.iconName??"mic",ne=c?.size??"40px",ie=a?.iconSize??ne,fe=parseFloat(ie)||24,Je=a?.backgroundColor??c?.backgroundColor,vt=a?.iconColor??c?.textColor;$.style.width=ie,$.style.height=ie,$.style.minWidth=ie,$.style.minHeight=ie,$.style.fontSize="18px",$.style.lineHeight="1",vt?$.style.color=vt:$.style.color="var(--persona-text, #111827)";let bn=de(q,fe,vt||"currentColor",1.5);bn?$.appendChild(bn):$.textContent="\u{1F3A4}",Je?$.style.backgroundColor=Je:$.style.backgroundColor="",a?.borderWidth&&($.style.borderWidth=a.borderWidth,$.style.borderStyle="solid"),a?.borderColor&&($.style.borderColor=a.borderColor),a?.paddingX&&($.style.paddingLeft=a.paddingX,$.style.paddingRight=a.paddingX),a?.paddingY&&($.style.paddingTop=a.paddingY,$.style.paddingBottom=a.paddingY),z.appendChild($);let Et=a?.showTooltip??!1;return Qt({anchor:$,trigger:z,text:()=>$.getAttribute("aria-label")??J,enabled:Et}),{micButton:$,micButtonWrapper:z}},Np=()=>{if(!re||bt)return;let a=o.voiceRecognition??{};bt={backgroundColor:re.style.backgroundColor,color:re.style.color,borderColor:re.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Fp=(a,c)=>{if(!re)return;let f=re.querySelector("svg");f&&f.remove();let h=bt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),C=de(a,h,c,1.5);C&&re.appendChild(C)},jl=()=>{re&&re.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Fs=()=>{if(!re)return;Np();let a=o.voiceRecognition??{},c=a.recordingBackgroundColor,f=a.recordingIconColor,h=a.recordingBorderColor;if(jl(),re.classList.add("persona-voice-recording"),re.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",re.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let C=re.querySelector("svg");C&&C.setAttribute("stroke",f)}h&&(re.style.borderColor=h),re.setAttribute("aria-label","Stop voice recognition")},gx=()=>{if(!re)return;Np();let a=o.voiceRecognition??{},c=D.getVoiceInterruptionMode(),f=a.processingIconName??"loader",h=a.processingIconColor??bt?.color??"",C=a.processingBackgroundColor??bt?.backgroundColor??"",E=a.processingBorderColor??bt?.borderColor??"";jl(),re.classList.add("persona-voice-processing"),re.style.backgroundColor=C,re.style.borderColor=E;let z=h||"currentColor";re.style.color=z,Fp(f,z),re.setAttribute("aria-label","Processing voice input"),c==="none"&&(re.style.cursor="default")},fx=()=>{if(!re)return;Np();let a=o.voiceRecognition??{},c=D.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",h=a.speakingIconName??f,C=a.speakingIconColor??(c==="barge-in"?a.recordingIconColor??bt?.color??"":bt?.color??""),E=a.speakingBackgroundColor??(c==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":bt?.backgroundColor??""),z=a.speakingBorderColor??(c==="barge-in"?a.recordingBorderColor??"":bt?.borderColor??"");jl(),re.classList.add("persona-voice-speaking"),re.style.backgroundColor=E,re.style.borderColor=z;let $=C||"currentColor";re.style.color=$,Fp(h,$);let J=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";re.setAttribute("aria-label",J),c==="none"&&(re.style.cursor="default"),c==="barge-in"&&re.classList.add("persona-voice-recording")},Wo=()=>{re&&(jl(),bt&&(re.style.backgroundColor=bt.backgroundColor??"",re.style.color=bt.color??"",re.style.borderColor=bt.borderColor??"",Fp(bt.iconName,bt.color||"currentColor"),bt=null),re.style.cursor="",re.setAttribute("aria-label","Start voice recognition"))},$s=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=D.getVoiceStatus(),c=D.getVoiceInterruptionMode();if(c==="none"&&(a==="processing"||a==="speaking"))return;if(c==="cancel"&&(a==="processing"||a==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Jn(),Mo("user"),Wo()});return}D.toggleVoice().then(()=>{je.active=D.isVoiceActive(),je.manuallyDeactivated=!D.isVoiceActive(),Jn(),Mo("user"),D.isVoiceActive()?Fs():Wo()});return}if(ao){let a=he.value.trim();je.manuallyDeactivated=!0,Jn(),or("user"),a&&(he.value="",he.style.height="auto",D.sendMessage(a))}else je.manuallyDeactivated=!1,Jn(),$l("user")};qg=$s,re&&(re.addEventListener("click",$s),ke.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),Wo()):or("system"),re&&re.removeEventListener("click",$s)}));let mx=m.on("assistant:complete",()=>{Ef&&(je.active||je.manuallyDeactivated||Ef==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?D.toggleVoice().then(()=>{je.active=D.isVoiceActive(),Mo("auto"),D.isVoiceActive()&&Fs()}):$l("auto"))},600))});ke.push(mx);let hx=m.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});ke.push(hx);let Rm=()=>{lt(!M,"user")},At=null,an=null;if(j&&!le()){let{instance:a,element:c}=ng({config:o,plugins:i,onToggle:Rm});At=a,a||(an=c)}At?e.appendChild(At.element):an&&e.appendChild(an),Ni(),Ts(),np(),tp(),Fi(D.isStreaming()),Gd()||(Sn()==="follow"?Zo(!0):ul()),JC(),ue&&(!j||le()?setTimeout(()=>$r(),0):M&&setTimeout(()=>$r(),200));let oa=()=>{if(le()){kr(),Ni();return}let a=Ct(o),c=o.launcher?.sidebarMode??!1,f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640,E=f.innerWidth<=C,z=h&&E&&j;try{if(z){Pr(),Li=sl();return}let $=!1;oe&&(oe=!1,Pr(),$=!0);let J=sl();if(!$&&J!==Li&&(Pr(),$=!0),Li=J,$&&Od(),!j&&!a){O.style.height="",O.style.width="";return}if(!c&&!a){let ne=o?.launcher?.width??o?.launcherWidth??Hn;O.style.width=ne,O.style.maxWidth=ne}rl(),pf()}finally{if(kr(),Ni(),M&&j){let J=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),q=o.launcher?.sidebarMode??!1,ne=o.launcher?.mobileFullscreen??!0,ie=Ct(o)&&ne&&J,fe=q||ne&&J&&j||ie;if(fe&&!ro){let Je=e.getRootNode(),vt=Je instanceof ShadowRoot?Je.host:e.closest(".persona-host");vt&&!oo&&(oo=Ou(vt,o.launcher?.zIndex??Xt)),ro=Du(e.ownerDocument)}else fe||(oo?.(),oo=null,ro?.(),ro=null)}}};oa();let zl=e.ownerDocument.defaultView??window;if(zl.addEventListener("resize",oa),ke.push(()=>zl.removeEventListener("resize",oa)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{kr()});a.observe($e),ke.push(()=>a.disconnect());let c=new ResizeObserver(()=>{Hl()});c.observe(G),ke.push(()=>c.disconnect())}zl.addEventListener("resize",Hl),ke.push(()=>zl.removeEventListener("resize",Hl)),Mn=K.scrollTop;let Wm=ho(K),Bm=()=>{let a=K.scrollTop,c=ho(K),f=c<Wm;if(Wm=c,!Yo()){Mn=a,$t();return}let{action:h,nextLastScrollTop:C}=Cb({following:En.isFollowing(),currentScrollTop:a,lastScrollTop:Mn,nearBottom:ls(K,To),userScrollThreshold:VC,isAutoScrolling:mn||al||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Mn=C,h==="resume"){gl()||hn();return}h==="pause"&&Wi()};if(K.addEventListener("scroll",Bm,{passive:!0}),ke.push(()=>K.removeEventListener("scroll",Bm)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{ow(),Jp(ce)});a.observe(ce),a.observe(K),ke.push(()=>a.disconnect())}let Om=()=>{Yo()&&En.isFollowing()&&gl()&&Wi()},Dm=K.ownerDocument;Dm.addEventListener("selectionchange",Om),ke.push(()=>{Dm.removeEventListener("selectionchange",Om)});let yx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),_m=a=>{yx.has(a.key)&&(_r(),Fg()&&Yo()&&En.isFollowing()&&Wi())},Nm=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(_r(),Fg()&&Yo()&&En.isFollowing()&&Wi())};K.addEventListener("keydown",_m),K.addEventListener("focusin",Nm),ke.push(()=>{K.removeEventListener("keydown",_m),K.removeEventListener("focusin",Nm)});let Fm=a=>{if(a.deltaY!==0&&_r(),!Yo())return;let c=wb({following:En.isFollowing(),deltaY:a.deltaY,nearBottom:ls(K,To),resumeWhenNearBottom:!0});c==="pause"?Wi():c==="resume"&&!gl()&&hn()};K.addEventListener("wheel",Fm,{passive:!0}),K.addEventListener("touchmove",_r,{passive:!0}),K.addEventListener("pointerdown",_r,{passive:!0}),ke.push(()=>{K.removeEventListener("touchmove",_r),K.removeEventListener("pointerdown",_r)}),ke.push(()=>K.removeEventListener("wheel",Fm)),Wt.addEventListener("click",()=>{Xn(),K.scrollTop=K.scrollHeight,Mn=K.scrollTop,hn(),Zo(!0),$t()}),ke.push(()=>Wt.remove()),ke.push(()=>{Pf(),Xn()});let $m=()=>{Be&&(Rr&&(Be.removeEventListener("click",Rr),Rr=null),ae()?(Be.style.display="",Rr=()=>{lt(!1,"user")},Be.addEventListener("click",Rr)):Be.style.display="none")};$m(),(()=>{let{clearChatButton:a}=Q;a&&a.addEventListener("click",()=>{if(io()){Rp({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}D.clearMessages(),Tn.clear(),hn(),dr(Q.composerOverlay);try{localStorage.removeItem(xi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xi}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),x?.clear&&pl(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},Z.syncFromMetadata(),Ae?.clear(),Fe?.reset(),at?.update()})})(),Ue&&Ue.addEventListener("submit",Fl);let jm=[["keydown",dx],["input",cx],["paste",px],["focus",_C]],$p=a=>{if(a)for(let[c,f]of jm)a.addEventListener(c,f)},jp=a=>{if(a)for(let[c,f]of jm)a.removeEventListener(c,f)};$p(he);let zm=()=>{rn?.onComposerSwap((a,c)=>{jp(c),he=a,$p(a)})};zm();let zp=!1;function bx(){if(!zp){zp=!0;try{let a=he?.value??"",c=$e.ownerDocument??document,f=he?c.activeElement===he:!1;jp(he),Ue?.removeEventListener("submit",Fl),re?.removeEventListener("click",$s),rn?.destroy(),rn=null;let h=null,C=()=>(h=le()?ed({config:o}):ps({config:o}),h.footer),E=Yg(C)??C();I.replaceComposer(E),$e=I.composer.footer;let z=h!==null&&E===h.footer;Mi=!z,Ng=z?h.setSendButtonMode:()=>{},Gg($e),Xg($e),Qg(),Zg(),ef(),zm(),Ue&&Ue.addEventListener("submit",Fl),$p(he),re?.addEventListener("click",$s);let $=Ir.indexOf(Ao);Ao.destroy(),Ao=_a(xt),$>=0&&(Ir[$]=Ao),he&&(he.value=a),np(),Ts(),Fi(D.isStreaming()),Pr(),kr(),f&&he?.focus()}finally{zp=!1}}}let Um=e.ownerDocument??document;Um.addEventListener("keydown",Hm,!0);let qm="persona-attachment-drop-active",ra=0,Up=()=>{ra=0,G.classList.remove(qm)},js=()=>o.attachments?.enabled===!0&&ht!==null,Vm=a=>{!bd(a.dataTransfer)||!js()||(ra++,ra===1&&G.classList.add(qm))},Km=a=>{!bd(a.dataTransfer)||!js()||(ra--,ra<=0&&Up())},Gm=a=>{!bd(a.dataTransfer)||!js()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Ym=a=>{if(!bd(a.dataTransfer)||!js())return;a.preventDefault(),a.stopPropagation(),Up();let c=Array.from(a.dataTransfer.files??[]);c.length!==0&&ht.handleFiles(c)},rr=!0;G.addEventListener("dragenter",Vm,rr),G.addEventListener("dragleave",Km,rr),e.addEventListener("dragover",Gm,rr),e.addEventListener("drop",Ym,rr);let Ul=e.ownerDocument,Jm=a=>{js()&&a.preventDefault()},Xm=a=>{js()&&a.preventDefault()};Ul.addEventListener("dragover",Jm),Ul.addEventListener("drop",Xm),ke.push(()=>{Ue&&Ue.removeEventListener("submit",Fl),jp(he),Um.removeEventListener("keydown",Hm,!0),rn?.destroy()}),ke.push(()=>{G.removeEventListener("dragenter",Vm,rr),G.removeEventListener("dragleave",Km,rr),e.removeEventListener("dragover",Gm,rr),e.removeEventListener("drop",Ym,rr),Ul.removeEventListener("dragover",Jm),Ul.removeEventListener("drop",Xm),Up()}),ke.push(()=>{D.cancel()}),At?ke.push(()=>{At?.destroy()}):an&&ke.push(()=>{an?.remove()});let Tt={update(a){let c=o.toolCall,f=o.messageActions,h=o.layout?.messages,C=o.colorScheme,E=o.loadingIndicator,z=o.iterationDisplay,$=o.features?.showReasoning,J=o.features?.showToolCalls,q=o.features?.toolCallDisplay,ne=o.features?.reasoningDisplay,ie=o.features?.streamAnimation?.type,fe=o.features?.history?.enabled===!0,Je=o.features?.history?.provider,vt=o.getIdentityProof,Vt=o.clientToken;o=dd({...o,features:s},a),s=o.features,o=qa(o),r(),_d(),rs(e,o),za(e,o),Ua(e,o),Zt(),So(),o.colorScheme!==C&&uf();let bn=Va.getForInstance(o.plugins);i.length=0,i.push(...bn),lm(),j=o.launcher?.enabled??!0,X=o.launcher?.autoExpand??!1,Se=o.features?.showReasoning??!0,Le=o.features?.showToolCalls??!0,Qe=o.features?.scrollToBottom??{};let Et=Sn();Oe=o.features?.scrollBehavior??{},Et!==Sn()&&(Xn(),hn()),Tf(),Ug(),$t();let Pt=He;if(He=o.features?.showEventStreamToggle??!1,He&&!Pt){if(Ae||(Ne=new $a(ve),Ae=new Fa(ft,Ne),Fe=Fe??new ja,Ne.open().then(()=>Ae?.restore()).catch(()=>{}),D.setSSEEventCallback((se,ze)=>{o.onSSEEvent?.(se,ze),Fe?.processEvent(se,ze),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify(ze)})})),!Ye&&Ee){let se=o.features?.eventStream?.classNames,ze="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"+(se?.toggleButton?" "+se.toggleButton:"");Ye=v("button",ze),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=un.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let Ge=de("activity","18px","currentColor",1.5);Ge&&Ye.appendChild(Ge);let gt=Q.clearChatButtonWrapper,ot=Q.closeButtonWrapper,Jt=gt||ot;Jt&&Jt.parentNode===Ee?Ee.insertBefore(Ye,Jt):Ee.appendChild(Ye),Ye.addEventListener("click",()=>{Gt?ws():Hd()})}}else!He&&Pt&&(ws(),Ye&&(Ye.remove(),Ye=null),Ae?.clear(),Ne?.destroy(),Ae=null,Ne=null,Fe?.reset(),Fe=null);if(o.launcher?.enabled===!1&&At&&(At.destroy(),At=null),o.launcher?.enabled===!1&&an&&(an.remove(),an=null),o.launcher?.enabled!==!1&&!At&&!an){let{instance:se,element:ze}=ng({config:o,plugins:i,onToggle:Rm});At=se,se||(an=ze),e.appendChild(ze)}At&&At.update(o),ea(),Er&&o.launcher?.subtitle!==void 0&&(Er.textContent=o.launcher.subtitle);let N=o.layout?.header;if(N?.layout!==ye&&Ee){let se=N?fi(o,N,{showClose:ae(),onClose:()=>lt(!1,"user")}):jo({config:o,showClose:ae(),onClose:()=>lt(!1,"user")});I.replaceHeader(se),Ee=I.header.element,St=I.header.iconHolder,Go=I.header.headerTitle,Er=I.header.headerSubtitle,Be=I.header.closeButton,ye=N?.layout,ea()}else if(N){if(St&&(St.style.display=N.showIcon===!1?"none":""),Go&&(Go.style.display=N.showTitle===!1?"none":""),Er&&(Er.style.display=N.showSubtitle===!1?"none":""),Be){let se=ae()&&N.showCloseButton!==!1;Be.style.display=se?"":"none"}if(Q.clearChatButtonWrapper){let se=N.showClearChat;if(se!==void 0){Q.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:ze}=Q;ze&&!ze.classList.contains("persona-absolute")&&(se?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}}let Ie=o.layout?.showHeader!==!1;Ee&&(Ee.style.display=Ie?"":"none");let Te=o.layout?.showFooter!==!1;$e&&($e.style.display=Te?"":"none"),kr(),$t(),j!==Ce?j?lt(X,"auto"):(M=!0,Ni()):X!==xe&&lt(X,"auto"),xe=X,Ce=j,oa(),$m();let Kt=JSON.stringify(o.toolCall)!==JSON.stringify(c),ct=JSON.stringify(o.messageActions)!==JSON.stringify(f),ln=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),Yt=o.loadingIndicator?.render!==E?.render||o.loadingIndicator?.renderIdle!==E?.renderIdle||o.loadingIndicator?.showBubble!==E?.showBubble,jt=o.iterationDisplay!==z,Re=(o.features?.showReasoning??!0)!==($??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(q)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ne);(Kt||ct||ln||Yt||jt||Re)&&D&&(Fd++,Bi(ce,D.getMessages(),me));let zt=o.features?.streamAnimation?.type;if(zt!==ie&&zt&&zt!=="none"){let se=pi(zt,o.features?.streamAnimation?.plugins);se&&qc(se,e)}let Me=o.launcher??{},Bt=Me.headerIconHidden??!1,ut=o.layout?.header?.showIcon,Ve=Bt||ut===!1,Ot=Me.headerIconName,Lt=Me.headerIconSize??"48px";if(St){let se=Ee,ze=se?.querySelector(".persona-flex-col");if(Ve)St.style.display="none",se&&ze&&!se.contains(ze)&&se.insertBefore(ze,se.firstChild);else{if(St.style.display="",St.style.height=Lt,St.style.width=Lt,se&&ze&&(se.contains(St)?St.nextSibling!==ze&&(St.remove(),se.insertBefore(St,ze)):se.insertBefore(St,ze)),Ot){let gt=parseFloat(Lt)||24,ot=de(Ot,gt*.6,"currentColor",1);ot?St.replaceChildren(ot):St.textContent=Me.agentIconText??"\u{1F4AC}"}else if(Me.iconUrl){let gt=St.querySelector("img");if(gt)gt.src=Me.iconUrl,gt.style.height=Lt,gt.style.width=Lt;else{let ot=document.createElement("img");ot.src=Me.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=Lt,ot.style.width=Lt,St.replaceChildren(ot)}}else{let gt=St.querySelector("svg"),ot=St.querySelector("img");(gt||ot)&&St.replaceChildren(),St.textContent=Me.agentIconText??"\u{1F4AC}"}let Ge=St.querySelector("img");Ge&&(Ge.style.height=Lt,Ge.style.width=Lt)}}let tn=o.layout?.header?.showTitle,$n=o.layout?.header?.showSubtitle;if(Go&&(Go.style.display=tn===!1?"none":""),Er&&(Er.style.display=$n===!1?"none":""),Be){let se=ae()&&o.layout?.header?.showCloseButton!==!1;if(Be.style.display=se?"":"none",!le()){let It=Me.closeButtonSize??"";Be.style.height=It,Be.style.width=It,Be.style.minWidth=It,Be.style.minHeight=It}let ze=Me.closeButtonPlacement??"inline",{closeButtonWrapper:Ge}=Q,gt=ze==="top-right",ot=Ge?.classList.contains("persona-absolute");if(Ge&&gt!==ot)if(Ge.remove(),gt){Ge.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let It=Vi??G;It.style.position="relative",It.appendChild(Ge)}else{let It=Me.clearChat?.placement??"inline",_t=Me.clearChat?.enabled??!0;Ge.className=_t&&It==="inline"?"":"persona-ml-auto",Ee&&Ee.appendChild(Ge)}if(Be.style.color=Me.closeButtonColor||un.actionIconColor,Me.closeButtonBackgroundColor?(Be.style.backgroundColor=Me.closeButtonBackgroundColor,Be.classList.remove("hover:persona-bg-gray-100")):(Be.style.backgroundColor="",Be.classList.add("hover:persona-bg-gray-100")),Me.closeButtonBorderWidth||Me.closeButtonBorderColor){let It=Me.closeButtonBorderWidth||"0px",_t=Me.closeButtonBorderColor||"transparent";Be.style.border=`${It} solid ${_t}`,Be.classList.remove("persona-border-none")}else Be.style.border="",Be.classList.add("persona-border-none");Me.closeButtonBorderRadius?(Be.style.borderRadius=Me.closeButtonBorderRadius,Be.classList.remove("persona-rounded-full")):(Be.style.borderRadius="",Be.classList.add("persona-rounded-full")),Me.closeButtonPaddingX?(Be.style.paddingLeft=Me.closeButtonPaddingX,Be.style.paddingRight=Me.closeButtonPaddingX):(Be.style.paddingLeft="",Be.style.paddingRight=""),Me.closeButtonPaddingY?(Be.style.paddingTop=Me.closeButtonPaddingY,Be.style.paddingBottom=Me.closeButtonPaddingY):(Be.style.paddingTop="",Be.style.paddingBottom=""),Vc(Be,Me.closeButtonIconName??"x",{iconSize:le()?Qu:void 0,iconText:Me.closeButtonIconText??"\xD7"});let Jt=Me.closeButtonTooltipText??"Close chat",vn=Me.closeButtonShowTooltip??!0;Be.setAttribute("aria-label",Jt),Ge&&Qt({anchor:Be,trigger:Ge,text:()=>Be?.getAttribute("aria-label")??Jt,enabled:vn})}let{clearChatButton:Ke,clearChatButtonWrapper:nn}=Q;if(Ke){let se=Me.clearChat??{},ze=se.enabled??!0,Ge=o.layout?.header?.showClearChat,gt=Ge!==void 0?Ge:ze,ot=se.placement??"inline";if(nn){nn.style.display=gt?"":"none";let{closeButtonWrapper:Jt}=Q;!le()&&Jt&&!Jt.classList.contains("persona-absolute")&&(gt?Jt.classList.remove("persona-ml-auto"):Jt.classList.add("persona-ml-auto"));let vn=ot==="top-right",It=nn.classList.contains("persona-absolute");if(!le()&&vn!==It&&gt){if(nn.remove(),vn){nn.className="persona-absolute persona-top-4 persona-z-50",nn.style.right="48px";let Ln=Vi??G;Ln.style.position="relative",Ln.appendChild(nn)}else{nn.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",nn.style.right="";let Ln=Q.closeButtonWrapper;Ee&&Ln&&Ln.parentElement===Ee?Ee.insertBefore(nn,Ln):Ee&&Ee.appendChild(nn)}let _t=Q.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(vn?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(gt){if(!le()){let _t=se.size??"";Ke.style.height=_t,Ke.style.width=_t,Ke.style.minWidth=_t,Ke.style.minHeight=_t}let Jt=se.iconColor??"";if(Ke.style.color=Jt||un.actionIconColor,Vc(Ke,se.iconName??"refresh-cw",{iconSize:le()?Zu:void 0}),se.backgroundColor?(Ke.style.backgroundColor=se.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let _t=se.borderWidth||"0px",Ln=se.borderColor||"transparent";Ke.style.border=`${_t} solid ${Ln}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");se.borderRadius?(Ke.style.borderRadius=se.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),se.paddingX?(Ke.style.paddingLeft=se.paddingX,Ke.style.paddingRight=se.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),se.paddingY?(Ke.style.paddingTop=se.paddingY,Ke.style.paddingBottom=se.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let vn=se.tooltipText??"Clear chat",It=se.showTooltip??!0;Ke.setAttribute("aria-label",vn),nn&&Qt({anchor:Ke,trigger:nn,text:()=>Ke?.getAttribute("aria-label")??vn,enabled:It})}}let Ht=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ka],dn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[bs.message,bs.messageAndClick];Z=Ga({parsers:Ht,handlers:dn,getSessionMetadata:R,updateSessionMetadata:W,emit:m.emit,documentRef:typeof document<"u"?document:null}),me=Nv(o,Z,we),bw(),D.updateConfig(o),(o.features?.history?.enabled===!0!==fe||o.features?.history?.provider!==Je||o.getIdentityProof!==vt||o.clientToken!==Vt)&&(yn({restoreFocus:!1}),em()),nr(),Hl(),Bi(ce,D.getMessages(),me),Ts(),np(),hw(),Fi(D.isStreaming());let sa=o.voiceRecognition?.enabled===!0,Qm=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),ia=o.voiceRecognition?.provider?.type==="runtype";if(sa&&(Qm||ia))if(!re||!Co){let se=ux(o.voiceRecognition,o.sendButton);se&&(re=se.micButton,Co=se.micButtonWrapper,RC.insertBefore(Co,en),re.addEventListener("click",$s),re.disabled=D.isStreaming())}else{let se=o.voiceRecognition??{},ze=o.sendButton??{},Ge=se.iconName??"mic",gt=ze.size??"40px",ot=se.iconSize??gt,Jt=parseFloat(ot)||24;re.style.width=ot,re.style.height=ot,re.style.minWidth=ot,re.style.minHeight=ot;let vn=se.iconColor??ze.textColor;re.innerHTML="";let It=de(Ge,Jt,vn||"currentColor",1.5);It?re.appendChild(It):re.textContent="\u{1F3A4}";let _t=se.backgroundColor??ze.backgroundColor;_t?re.style.backgroundColor=_t:re.style.backgroundColor="",vn?re.style.color=vn:re.style.color="var(--persona-text, #111827)",se.borderWidth?(re.style.borderWidth=se.borderWidth,re.style.borderStyle="solid"):(re.style.borderWidth="",re.style.borderStyle=""),se.borderColor?re.style.borderColor=se.borderColor:re.style.borderColor="",se.paddingX?(re.style.paddingLeft=se.paddingX,re.style.paddingRight=se.paddingX):(re.style.paddingLeft="",re.style.paddingRight=""),se.paddingY?(re.style.paddingTop=se.paddingY,re.style.paddingBottom=se.paddingY):(re.style.paddingTop="",re.style.paddingBottom="");let Ln=se.tooltipText??"Start voice recognition",xx=se.showTooltip??!1;re.setAttribute("aria-label",Ln),Co&&Qt({anchor:re,trigger:Co,text:()=>re?.getAttribute("aria-label")??Ln,enabled:xx}),Co.style.display="",re.disabled=D.isStreaming()}else re&&Co&&(Co.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?D.isVoiceActive()&&D.toggleVoice():ao&&or());if(o.attachments?.enabled===!0){if(!Wn||!mt){let se=o.attachments??{},Ge=(o.sendButton??{}).size??"40px";Kn||(Kn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Kn.style.display="none",Ue.insertBefore(Kn,he)),kt||(kt=document.createElement("input"),kt.type="file",kt.accept=(se.allowedTypes??No).join(","),kt.multiple=(se.maxFiles??4)>1,kt.style.display="none",kt.setAttribute("aria-label","Attach files"),Ue.insertBefore(kt,he)),Wn=v("div","persona-send-button-wrapper"),mt=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),mt.type="button",mt.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let gt=se.buttonIconName??"paperclip",ot=Ge,Jt=parseFloat(ot)||40,vn=Math.round(Jt*.6);mt.style.width=ot,mt.style.height=ot,mt.style.minWidth=ot,mt.style.minHeight=ot,mt.style.fontSize="18px",mt.style.lineHeight="1";let It=de(gt,vn,"currentColor",1.5);It?mt.appendChild(It):mt.textContent="\u{1F4CE}",mt.addEventListener("click",Ln=>{Ln.preventDefault(),kt?.click()}),Wn.appendChild(mt);let _t=se.buttonTooltipText??"Attach file";Qt({anchor:mt,trigger:Wn,text:()=>mt?.getAttribute("aria-label")??_t}),Cs?Cs.append(Wn):Ue.appendChild(Wn),!ht&&kt&&Kn&&(ht=os.fromConfig(se),ht.setPreviewsContainer(Kn),kt.addEventListener("change",async()=>{ht&&kt?.files&&(await ht.handleFileSelect(kt.files),kt.value="")}))}else{Wn.style.display="";let se=o.attachments??{};kt&&(kt.accept=(se.allowedTypes??No).join(","),kt.multiple=(se.maxFiles??4)>1),ht&&ht.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(G.querySelector(".persona-attachment-drop-overlay")?.remove(),G.appendChild(Fv(o.attachments?.dropOverlay)),mt){let se=o.attachments??{},ze=se.buttonTooltipText??"Attach file";mt.setAttribute("aria-label",ze),mt.textContent="";let Ge=parseFloat(o.sendButton?.size??"40px")||40,gt=de(se.buttonIconName??"paperclip",Math.round(Ge*.6),"currentColor",1.5);gt?mt.appendChild(gt):mt.textContent="\u{1F4CE}",Wn&&Qt({anchor:mt,trigger:Wn,text:()=>mt?.getAttribute("aria-label")??ze})}}else Wn&&(Wn.style.display="none"),ht&&ht.clearAttachments(),G.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},qp=Dt.useIcon??!1,Vl=Dt.iconText??"\u2191",Yr=Dt.iconName,Kl=Dt.tooltipText??"Send message",vx=Dt.showTooltip??!1,aa=Dt.size??"40px",Gl=Dt.backgroundColor,la=Dt.textColor;if(qp){if(be.style.width=aa,be.style.height=aa,be.style.minWidth=aa,be.style.minHeight=aa,be.style.fontSize="18px",be.style.lineHeight="1",la?be.style.color=la:be.style.color="var(--persona-button-primary-fg, #ffffff)",!D.isStreaming())if(be.innerHTML="",Yr){let se=parseFloat(aa)||24,ze=la?.trim()||"currentColor",Ge=de(Yr,se,ze,2);Ge?be.appendChild(Ge):be.textContent=Vl}else be.textContent=Vl;be.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Gl?(be.style.backgroundColor=Gl,be.classList.remove("persona-bg-persona-primary")):(be.style.backgroundColor="",be.classList.add("persona-bg-persona-primary"))}else be.textContent=o.copy?.sendButtonLabel??"Send",be.style.width="",be.style.height="",be.style.minWidth="",be.style.minHeight="",be.style.fontSize="",be.style.lineHeight="",be.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",Gl?(be.style.backgroundColor=Gl,be.classList.remove("persona-bg-persona-accent")):be.classList.add("persona-bg-persona-accent"),la?be.style.color=la:be.classList.add("persona-text-white");Dt.borderWidth?(be.style.borderWidth=Dt.borderWidth,be.style.borderStyle="solid"):(be.style.borderWidth="",be.style.borderStyle=""),Dt.borderColor?be.style.borderColor=Dt.borderColor:be.style.borderColor="",Dt.paddingX?(be.style.paddingLeft=Dt.paddingX,be.style.paddingRight=Dt.paddingX):(be.style.paddingLeft="",be.style.paddingRight=""),Dt.paddingY?(be.style.paddingTop=Dt.paddingY,be.style.paddingBottom=Dt.paddingY):(be.style.paddingTop="",be.style.paddingBottom=""),D.isStreaming()||be.setAttribute("aria-label",Kl),en&&Qt({anchor:be,trigger:en,text:()=>be.getAttribute("aria-label")??Kl,enabled:vx});let zs=br(o,le());Nd(),zs?(ce.style.maxWidth=zs,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",xn.style.maxWidth=zs,xn.style.marginLeft="auto",xn.style.marginRight="auto",xn.style.width="100%",Ue&&(Ue.style.maxWidth=zs,Ue.style.marginLeft="auto",Ue.style.marginRight="auto"),xt&&(xt.style.maxWidth=zs,xt.style.marginLeft="auto",xt.style.marginRight="auto"),on.style.maxWidth=zs,on.style.marginLeft="auto",on.style.marginRight="auto"):(ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",xn.style.maxWidth="",xn.style.marginLeft="",xn.style.marginRight="",xn.style.width="",Ue&&(Ue.style.maxWidth="",Ue.style.marginLeft="",Ue.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),on.style.maxWidth="",on.style.marginLeft="",on.style.marginRight="");let sr=o.statusIndicator??{},Cx=sr.visible??!0;if(on.style.display=Cx?"":"none",D){let se=D.getStatus();S(on,(Ge=>Ge==="idle"?sr.idleText??Nt.idle:Ge==="connecting"?sr.connectingText??Nt.connecting:Ge==="connected"?sr.connectedText??Nt.connected:Ge==="error"?sr.errorText??Nt.error:Nt[Ge])(se),sr,se)}on.classList.remove("persona-text-left","persona-text-center","persona-text-right");let wx=sr.align==="left"?"persona-text-left":sr.align==="center"?"persona-text-center":"persona-text-right";on.classList.add(wx),wt()},open(){ae()&&lt(!0,"api")},close(){ae()&&lt(!1,"api")},toggle(){ae()&&lt(!M,"api")},reconnect(){D.reconnectNow()},clearChat(){xo=!1,D.clearMessages(),Tn.clear(),hn();try{localStorage.removeItem(xi),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xi}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xi)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),x?.clear&&pl(()=>x.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},Z.syncFromMetadata(),Ae?.clear(),Fe?.reset(),at?.update()},setMessage(a){return!he||D.isStreaming()?!1:(!M&&ae()&&lt(!0,"system"),he.value=a,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(D.isStreaming())return!1;let c=a?.trim()||he.value.trim();return c?(!M&&ae()&&lt(!0,"system"),he.value="",he.style.height="auto",D.sendMessage(c),!0):!1},startVoiceRecognition(){return D.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(D.isVoiceActive()||(!M&&ae()&&lt(!0,"system"),je.manuallyDeactivated=!1,Jn(),D.toggleVoice().then(()=>{je.active=D.isVoiceActive(),Mo("user"),D.isVoiceActive()&&Fs()})),!0):ao?!0:Im()?(!M&&ae()&&lt(!0,"system"),je.manuallyDeactivated=!1,Jn(),$l("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Jn(),Mo("user"),Wo()}),!0):!1:ao?(je.manuallyDeactivated=!0,Jn(),or("user"),!0):!1},injectMessage(a){return!M&&ae()&&lt(!0,"system"),D.injectMessage(a)},injectAssistantMessage(a){!M&&ae()&&lt(!0,"system");let c=D.injectAssistantMessage(a);return ee&&(ee=!1,pe&&(clearTimeout(pe),pe=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),c},injectUserMessage(a){return!M&&ae()&&lt(!0,"system"),D.injectUserMessage(a)},injectSystemMessage(a){return!M&&ae()&&lt(!0,"system"),D.injectSystemMessage(a)},injectMessageBatch(a){return!M&&ae()&&lt(!0,"system"),D.injectMessageBatch(a)},injectComponentDirective(a){return!M&&ae()&&lt(!0,"system"),D.injectComponentDirective(a)},injectTestMessage(a){!M&&ae()&&lt(!0,"system"),D.injectTestEvent(a)},async connectStream(a,c){return D.connectStream(a,c)},__pushEventStreamEvent(a){Ae&&(Fe?.processEvent(a.type,a.payload),Ae.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!He||!Ae||Hd()},hideEventStream(){Gt&&ws()},isEventStreamVisible(){return Gt},listConversations(a){return D.listConversations(a)},getActiveConversationId(){return D.getActiveConversationId()},openConversation(a,c){return Ip(a,{focusComposer:c?.focus===!0})},startNewConversation(a){return Rp({focusComposer:a?.focus===!0})},deleteConversation(a){return Am(a)},renameConversation(a,c){return Wp(a,{title:c})},setConversationStarred(a,c){return Wp(a,{starred:c})},clearConversationHistory(a){return Tm(a)},resetHistoryIdentity(){return Em()},getHistoryIdentityStatus(){return kn?kn.getIdentityStatus():gp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(a){return Zi({...a?.returnSurface?{returnSurface:a.returnSurface}:{},...a?.focus!==void 0?{focus:a.focus}:{}})},hideHistory(a){yn(a?.restoreFocus!==void 0?{restoreFocus:a.restoreFocus}:void 0)},isHistoryVisible(){return et},showArtifacts(){gn(o)&&(xo=!1,xs=!0,So(),_e?.setMobileOpen(!0))},hideArtifacts(){gn(o)&&(xo=!0,So())},upsertArtifact(a){return gn(o)?(po(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(xo=!1,xs=!0),D.upsertArtifact(a)):null},selectArtifact(a){gn(o)&&D.selectArtifact(a)},clearArtifacts(){gn(o)&&D.clearArtifacts()},getArtifacts(){return D?.getArtifacts()??[]},getSelectedArtifactId(){return D?.getSelectedArtifactId()??null},focusInput(){return j&&!M&&!le()||!he?!1:(he.focus(),!0)},async resolveApproval(a,c,f){let C=D.getMessages().find(E=>E.variant==="approval"&&E.approval?.id===a);if(!C?.approval)throw new Error(`Approval not found: ${a}`);if(C.approval.toolType==="webmcp"){D.resolveWebMcpApproval(C.id,c);return}return D.resolveApproval(C.approval,c,f)},setFollowUpSuggestions(a){UC(a)},clearFollowUpSuggestions(){Af()},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...T}},updatePersistentMetadata(a){W(a)},on(a,c){return m.on(a,c)},off(a,c){m.off(a,c)},isOpen(){return ae()&&M},isVoiceActive(){return je.active},toggleReadAloud(a){D.toggleReadAloud(a)},stopReadAloud(){D.stopSpeaking()},getReadAloudState(a){return D.getReadAloudState(a)},onReadAloudChange(a){return D.onReadAloudChange(a)},getState(){return{open:ae()&&M,launcherEnabled:j,voiceActive:je.active,streaming:D.isStreaming()}},showCSATFeedback(a){!M&&ae()&&lt(!0,"system");let c=ce.querySelector(".persona-feedback-container");c&&c.remove();let f=hd({onSubmit:async(h,C)=>{D.isClientTokenMode()&&await D.submitCSATFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});ce.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!M&&ae()&&lt(!0,"system");let c=ce.querySelector(".persona-feedback-container");c&&c.remove();let f=yd({onSubmit:async(h,C)=>{D.isClientTokenMode()&&await D.submitNPSFeedback(h,C),a?.onSubmit?.(h,C)},onDismiss:a?.onDismiss,...a});ce.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,c){return D.submitCSATFeedback(a,c)},async submitNPSFeedback(a,c){return D.submitNPSFeedback(a,c)},destroy(){ip(),Ur!=null&&(clearInterval(Ur),Ur=null),ke.forEach(a=>a()),L.remove(),Y?.remove(),At?.destroy(),an?.remove(),Rr&&Be.removeEventListener("click",Rr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,c={controller:Tt,getMessages:Tt.getMessages,getStatus:Tt.getStatus,getMetadata:Tt.getPersistentMetadata,updateMetadata:Tt.updatePersistentMetadata,clearHistory:()=>Tt.clearChat(),setVoiceActive:f=>f?Tt.startVoiceRecognition():Tt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,ke.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),c=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.focusInput()};if(window.addEventListener("persona:focusInput",c),ke.push(()=>{window.removeEventListener("persona:focusInput",c)}),He){let q=ie=>{let fe=ie.detail;(!fe?.instanceId||fe.instanceId===a)&&Tt.showEventStream()},ne=ie=>{let fe=ie.detail;(!fe?.instanceId||fe.instanceId===a)&&Tt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",ne),ke.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",ne)})}let f=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.showHistory()},h=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",h),ke.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",h)});let C=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.showArtifacts()},E=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.hideArtifacts()},z=q=>{let ne=q.detail;ne?.instanceId&&ne.instanceId!==a||ne?.artifact&&Tt.upsertArtifact(ne.artifact)},$=q=>{let ne=q.detail;ne?.instanceId&&ne.instanceId!==a||typeof ne?.id=="string"&&Tt.selectArtifact(ne.id)},J=q=>{let ne=q.detail;(!ne?.instanceId||ne.instanceId===a)&&Tt.clearArtifacts()};window.addEventListener("persona:showArtifacts",C),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",z),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",J),ke.push(()=>{window.removeEventListener("persona:showArtifacts",C),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",z),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",J)})}let Fn=tM(o.persistState);if(Fn&&ae()){let a=nM(Fn.storage),c=`${Fn.keyPrefix}widget-open`,f=`${Fn.keyPrefix}widget-voice`,h=`${Fn.keyPrefix}widget-voice-mode`;if(a){let C=Fn.persist?.openState&&a.getItem(c)==="true",E=Fn.persist?.voiceState&&a.getItem(f)==="true",z=Fn.persist?.voiceState&&a.getItem(h)==="true";if(C&&(At?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open(),setTimeout(()=>{if(E||z)Tt.startVoiceRecognition();else if(Fn.persist?.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0)),Fn.persist?.openState&&(m.on("widget:opened",()=>{a.setItem(c,"true")}),m.on("widget:closed",()=>{a.setItem(c,"false")})),Fn.persist?.voiceState&&(m.on("voice:state",$=>{a.setItem(f,$.active?"true":"false")}),m.on("user:message",$=>{a.setItem(h,$.viaVoice?"true":"false")})),Fn.clearOnChatClear){let $=()=>{a.removeItem(c),a.removeItem(f),a.removeItem(h)},J=()=>$();window.addEventListener("persona:clear-chat",J),ke.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(A&&ae()&&(At?.setPanelOpen(!0,"auto"),setTimeout(()=>{Tt.open()},0)),Hs(),!qC){let a=qs(()=>{D&&(Fd++,Tn.clear(),Bi(ce,D.getMessages(),me))});ke.push(a)}return Tt};var $v=(e,t)=>{let n=e.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,t*parseFloat(r[1])/100):420},sM=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},iM=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},aM=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},jv=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},Tg=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=""},zv=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Tg(e)},xg=e=>{e.style.transition=""},Sg=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=""},Ag=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cd=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},lM=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},cM=(e,t,n,o,r,s)=>{let i=s?t:e;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},dM=e=>{let t=yr(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:pn(t,r)??r;return{inset:o(n?.inset,Sc),canvasBackground:o(n?.canvasBackground,Ac)}},Uv=(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},pM=(e,t,n,o,r,s,i,l)=>{let d=wn(s),u=d.reveal==="push",p=l!=null,g=l?.inset??"",y=l?.canvasBackground??"";lM(e,t,n,o,u),cM(e,t,n,o,d.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=d.side,e.dataset.personaDockOpen=i?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let m=e.ownerDocument.defaultView,b=s?.launcher?.mobileFullscreen??!0,x=s?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=x:!1;if(b&&T&&i){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Sg(t),xg(o),zv(o),Ag(n),Cd(r,o),Uv(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Xt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",u&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),zv(o),sM(o,d.maxHeight),Uv(o,p&&i,g,y),d.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Sg(t),xg(o),Ag(n),Cd(r,o);let _=d.animate?"transform 180ms ease":"none",P=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=i?"translateX(0)":P;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=_,o.style.transform=A,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",xg(o),Tg(o),Cd(r,o);let _=$v(d.width,e.clientWidth),P=Math.max(0,e.clientWidth),A=d.animate?"margin-left 180ms ease":"none",B=d.side==="right"?i?-_:0:i?0:-_;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=`${P+_}px`,t.style.transition=A,t.style.marginLeft=`${B}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Sg(t),Tg(o),Ag(n),Cd(r,o);let _=d.reveal==="emerge";_?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=i?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${p?", padding 180ms ease":""}`:"none",B=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${P}`,o.style.width=P,o.style.maxWidth=P,o.style.minWidth=P,o.style.minHeight="0",iM(o,d.maxHeight),o.style.overflow=_||B?"hidden":"visible",o.style.transition=A,_){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let R=p?`calc(${$v(d.width,e.clientWidth)}px - (2 * ${g}))`:d.width;r.style.width=R,r.style.minWidth=R,r.style.maxWidth=R,r.style.boxSizing="border-box"}}},uM=(e,t)=>{let n=e.ownerDocument.createElement("div");return jv(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){jv(n,o)},destroy(){n.remove()}}},gM=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,i=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),u=n.createElement("aside"),p=n.createElement("div"),g=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",u.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",u.appendChild(p),o.insertBefore(i,e),d.appendChild(e);let y=null,m=()=>{y?.disconnect(),y=null},b=null,x=()=>{b=t?.launcher?.detachedPanel===!0?dM(t):null};x();let T=()=>{pM(i,l,d,u,p,t,g,b)},H=null,_=()=>{H?.(),H=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(H=ai(()=>{x(),T()}))},P=()=>{m(),wn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{T()}),y.observe(i)))},A=!1,B=()=>{T(),P(),g&&!A&&i.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,aM(i,wn(t)))},R=i.ownerDocument.defaultView,W=()=>{B()};return R?.addEventListener("resize",W),wn(t).reveal==="push"?(l.appendChild(d),l.appendChild(u),i.appendChild(l)):(i.appendChild(d),i.appendChild(u)),B(),_(),{mode:"docked",host:p,shell:i,syncWidgetState(U){let V=U.launcherEnabled?U.open:!0;g!==V&&(g=V,B())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(g=!0),x(),B(),_()},destroy(){R?.removeEventListener("resize",W),H?.(),H=null,m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),i.remove()}}},Ja=(e,t)=>Ct(t)?gM(e,t):uM(e,t);var fM=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},qv=(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)},Eg=e=>{let t=fM(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=Ja(t,r),i,l=[],d=(T,H)=>{let P=!(H?.launcher?.enabled??!0)||Ct(H),A=o.createElement("div");if(A.setAttribute("data-persona-root","true"),P&&(A.style.height="100%",A.style.display="flex",A.style.flexDirection="column",A.style.flex="1",A.style.minHeight="0",A.style.minWidth="0"),n){let B=T.attachShadow({mode:"open"});B.appendChild(A),qv(B,o)}else T.appendChild(A),qv(T,o);return t.id&&A.setAttribute("data-persona-instance",t.id),A},u=()=>{s.syncWidgetState(i.getState())},p=()=>{l.forEach(T=>T()),l=[i.on("widget:opened",u),i.on("widget:closed",u)],u()},g=()=>{let T=d(s.host,r);i=vd(T,r,{debugTools:e.debugTools}),p()},y=()=>{l.forEach(T=>T()),l=[],i.destroy()};g(),e.onChatReady?.();let m=T=>{y(),s.destroy(),s=Ja(t,T),r=T,g()},b={update(T){let H=dd(r??{},T),_=Ct(r),P=Ct(H),A=Sr(r),B=Sr(H);if(_!==P||A!==B){m(H);return}r=H,s.updateConfig(r),i.update(T),u()},destroy(){y(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},x=new Proxy(b,{get(T,H,_){if(H==="host")return s.host;if(H in T)return Reflect.get(T,H,_);let P=i[H];return typeof P=="function"?P.bind(i):P}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=x),x};function mM(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function hM(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:mM(o,n)?2:3}function Vv(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function wd(e,t){let n=t.trim();if(!n)return[...e].sort(Vv);let o=[];for(let r of e){let s=hM(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Vv(r.item,s.item)),o.map(r=>r.item)}function yM(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function Kv(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>wd(e.items,t),resolve:e.resolve}}function Gv(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>wd(t,yM(r).name),resolve:(r,s)=>{let i=n.get(r.id);return i?i.kind==="server"?{context:(typeof i.data=="function"?i.data(s.args):i.data)??{}}:{insertText:typeof i.prompt=="function"?i.prompt(s.args):i.prompt??""}:{}}}}var Zv=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),bM=new Set(["button","a","input","select","textarea","details","summary"]),vM=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Mg=/\b(product|card|item|listing|result)\b/i,Pg=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,CM=3e3,wM=100;function eC(e){let t=typeof e.className=="string"?e.className:"";if(Mg.test(t)||e.id&&Mg.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Mg.test(o.value))return!0}return!1}function tC(e){return Pg.test((e.textContent??"").trim())}function nC(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 xM(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Yv(e){let t=e.match(Pg);return t?t[0]:null}function Jv(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 SM(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var AM="commerce-card",TM="result-card";function Xv(e){return!eC(e)||!tC(e)||!nC(e)&&!xM(e)?0:5200}function Qv(e){return!eC(e)||tC(e)||!nC(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Lg=[{id:AM,scoreElement(e){return Xv(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||Pg.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Xv(e)===0)return null;let{title:n,href:o}=Jv(e),r=Yv((e.textContent??"").trim())??Yv(t.text)??"",s=SM(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
+ `)}},{id:TM,scoreElement(e){return Qv(e)},formatSummary(e,t){if(Qv(e)===0)return null;let{title:n,href:o}=Jv(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
+ `)}}];function EM(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function MM(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,i=t.root??e.root,l=t.mode??"structured",d=t.maxCandidates??Math.max(500,n*10),u=e.rules??Lg;return l==="simple"&&e.rules&&e.rules.length>0?(EM(),u=[]):l==="simple"&&(u=[]),{mode:l,maxElements:n,maxCandidates:d,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:i,rules:u}}function kg(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var kM=["data-testid","data-product","data-action","data-id","data-name","data-type"];function PM(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"||bM.has(t)||n&&vM.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function oC(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 LM(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let i=e.getAttribute("value");i&&(t.value=i);let l=e.getAttribute("name");l&&(t.name=l);let d=e.getAttribute("role");d&&(t.role=d);for(let u=0;u<e.attributes.length;u++){let p=e.attributes[u];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Hg(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${kg(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of kM){let s=e.getAttribute(r);if(s){let i=`${t}[${r}="${kg(s)}"]`;try{if(e.ownerDocument.querySelectorAll(i).length===1)return i}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(i=>kg(i)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let l=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let d=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function HM(e){return e==="static"?wM:CM}function rC(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:Hg(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:PM(e),attributes:LM(e)}}function IM(e,t,n,o){let r=HM(t.interactivity),s=null;for(let i of n){let l=i.scoreElement(e,t,o);l>0&&(r+=l,i.formatSummary&&!s&&(s=i))}return{score:r,formattingRule:s}}function RM(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 WM(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,i=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=i.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let u=l,p=u.tagName.toLowerCase();if(Zv.has(p)){l=i.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){l=i.nextNode();continue}}catch{}if(e.visibleOnly&&!oC(u)){l=i.nextNode();continue}let g=rC(u,e.maxTextLength),y=g.text.length>0,m=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(T=>T==="role");if(!y&&!m){l=i.nextNode();continue}if(o.has(g.selector)){l=i.nextNode();continue}o.add(g.selector);let{score:b,formattingRule:x}=IM(u,g,e.rules,n);r.push({el:u,domIndex:s,enriched:g,score:b,formattingRule:x}),s+=1}l=i.nextNode()}r.sort((u,p)=>{let g=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return g!==y?g-y:p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex});let d=[];for(let u of r){if(d.length>=e.maxElements)break;RM(d,u)||d.push(u)}return d.sort((u,p)=>{let g=u.enriched.interactivity==="static"?1:0,y=p.enriched.interactivity==="static"?1:0;return g!==y?g-y:g===1&&p.score!==u.score?p.score-u.score:u.domIndex-p.domIndex}),d.map(u=>{let p;if(u.formattingRule?.formatSummary){let y=u.formattingRule.formatSummary(u.el,u.enriched,n);y&&(p=y)}let g={...u.enriched};return p&&(g.formattedSummary=p),g})}function BM(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,u=d.tagName.toLowerCase();if(Zv.has(u)){s=r.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!oC(d)){s=r.nextNode();continue}let p=rC(d,e.maxTextLength),g=p.text.length>0,y=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!g&&!y){s=r.nextNode();continue}o.has(p.selector)||(o.add(p.selector),n.push(p))}s=r.nextNode()}let i=[],l=[];for(let d of n)d.interactivity!=="static"?i.push(d):l.push(d);return[...i,...l].slice(0,e.maxElements)}function sC(e={}){let t=MM(e),n=t.root??document.body;return n?t.mode==="simple"?BM(t,n):WM(t,n):[]}var xd=100;function iC(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);s.length>0&&o.push(`Structured summaries:
145
+ ${s.map(i=>`- ${i.split(`
146
146
  `).join(`
147
147
  `)}`).join(`
148
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(a=>`- ${a.selector}: "${a.text.substring(0,Ol)}" (clickable)`);o.push(`Interactive elements:
148
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let s of e)n==="structured"&&s.formattedSummary||r[s.interactivity].push(s);if(r.clickable.length>0){let s=r.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,xd)}" (clickable)`);o.push(`Interactive elements:
149
149
  ${s.join(`
150
- `)}`)}if(r.navigable.length>0){let s=r.navigable.map(a=>`- ${a.selector}${a.attributes.href?`[href="${a.attributes.href}"]`:""}: "${a.text.substring(0,Ol)}" (navigable)`);o.push(`Navigation links:
150
+ `)}`)}if(r.navigable.length>0){let s=r.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,xd)}" (navigable)`);o.push(`Navigation links:
151
151
  ${s.join(`
152
- `)}`)}if(r.input.length>0){let s=r.input.map(a=>`- ${a.selector}${a.attributes.type?`[type="${a.attributes.type}"]`:""}: "${a.text.substring(0,Ol)}" (input)`);o.push(`Form inputs:
152
+ `)}`)}if(r.input.length>0){let s=r.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,xd)}" (input)`);o.push(`Form inputs:
153
153
  ${s.join(`
154
- `)}`)}if(r.static.length>0){let s=r.static.map(a=>`- ${a.selector}: "${a.text.substring(0,Ol)}"`);o.push(`Content:
154
+ `)}`)}if(r.static.length>0){let s=r.static.map(i=>`- ${i.selector}: "${i.text.substring(0,xd)}"`);o.push(`Content:
155
155
  ${s.join(`
156
156
  `)}`)}return o.join(`
157
157
 
158
- `)}function Ph(){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 Rh(){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 Ih(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:qn(e.colors.primary,.95),100:qn(e.colors.primary,.9),200:qn(e.colors.primary,.8),300:qn(e.colors.primary,.7),400:qn(e.colors.primary,.6),500:e.colors.primary,600:qn(e.colors.primary,.8),700:qn(e.colors.primary,.7),800:qn(e.colors.primary,.6),900:qn(e.colors.primary,.5),950:qn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Wh(){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 Hh(){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 qn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Bh(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Zw={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"}}},Dh={components:{panel:{borderRadius:"0",shadow:"none"}}},dp={id:"shop",label:"Shopping Assistant",config:{theme:Zw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},pp={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Dh}},up={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Dh}},gp={shop:dp,minimal:pp,fullscreen:up};function Oh(e){return gp[e]}var Nh=rp;function fp(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ao}/dist`}function mo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function eA(e){if(e)return{getHeaders:mo(e.getHeaders),onFeedback:mo(e.onFeedback),onCopy:mo(e.onCopy),requestMiddleware:mo(e.requestMiddleware),actionHandlers:mo(e.actionHandlers),actionParsers:mo(e.actionParsers),postprocessMessage:mo(e.postprocessMessage),contextProviders:mo(e.contextProviders),streamParser:mo(e.streamParser)}}var Fh=`({ text, message }: any) => {
158
+ `)}function aC(){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 lC(){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 cC(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:bo(e.colors.primary,.95),100:bo(e.colors.primary,.9),200:bo(e.colors.primary,.8),300:bo(e.colors.primary,.7),400:bo(e.colors.primary,.6),500:e.colors.primary,600:bo(e.colors.primary,.8),700:bo(e.colors.primary,.7),800:bo(e.colors.primary,.6),900:bo(e.colors.primary,.5),950:bo(e.colors.primary,.45)}}),{...t,palette:n}}}}function dC(){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 pC(){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 bo(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),i=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function uC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var OM={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"}}},gC={components:{panel:{borderRadius:"0",shadow:"none"}}},Ig={id:"shop",label:"Shopping Assistant",config:{theme:OM,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Hn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"]}},Rg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:gC}},Wg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:gC}},Bg={shop:Ig,minimal:Rg,fullscreen:Wg};function fC(e){return Bg[e]}var mC=Eg;function Og(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${uo}/dist`}function Vo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function DM(e){if(e)return{getHeaders:Vo(e.getHeaders),onFeedback:Vo(e.onFeedback),onCopy:Vo(e.onCopy),requestMiddleware:Vo(e.requestMiddleware),actionHandlers:Vo(e.actionHandlers),actionParsers:Vo(e.actionParsers),postprocessMessage:Vo(e.postprocessMessage),contextProviders:Vo(e.contextProviders),streamParser:Vo(e.streamParser)}}var hC=`({ text, message }: any) => {
159
159
  const jsonSource = (message as any).rawContent || text || message.content;
160
160
  if (!jsonSource || typeof jsonSource !== 'string') return null;
161
161
  let cleanJson = jsonSource
@@ -168,7 +168,7 @@ ${s.join(`
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,_h=`function(ctx) {
171
+ }`,yC=`function(ctx) {
172
172
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
173
173
  if (!jsonSource || typeof jsonSource !== 'string') return null;
174
174
  var cleanJson = jsonSource
@@ -181,7 +181,7 @@ ${s.join(`
181
181
  if (parsed.action) return { type: parsed.action, payload: parsed };
182
182
  } catch (e) { return null; }
183
183
  return null;
184
- }`,$h=`(action: any, context: any) => {
184
+ }`,bC=`(action: any, context: any) => {
185
185
  if (action.type !== 'nav_then_click') return;
186
186
  const payload = action.payload || action.raw || {};
187
187
  const url = payload?.page;
@@ -198,7 +198,7 @@ ${s.join(`
198
198
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
199
199
  window.location.href = targetUrl;
200
200
  return { handled: true, displayText: text };
201
- }`,jh=`function(action, context) {
201
+ }`,vC=`function(action, context) {
202
202
  if (action.type !== 'nav_then_click') return;
203
203
  var payload = action.payload || action.raw || {};
204
204
  var url = payload.page;
@@ -215,27 +215,27 @@ ${s.join(`
215
215
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
216
216
  window.location.href = targetUrl;
217
217
  return { handled: true, displayText: text };
218
- }`,tA=`(parsed: any) => {
218
+ }`,_M=`(parsed: any) => {
219
219
  if (!parsed || typeof parsed !== 'object') return null;
220
220
  if (parsed.action === 'nav_then_click') return 'Navigating...';
221
221
  if (parsed.action === 'message') return parsed.text || '';
222
222
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
223
223
  return parsed.text || null;
224
- }`,nA=`function(parsed) {
224
+ }`,NM=`function(parsed) {
225
225
  if (!parsed || typeof parsed !== 'object') return null;
226
226
  if (parsed.action === 'nav_then_click') return 'Navigating...';
227
227
  if (parsed.action === 'message') return parsed.text || '';
228
228
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
229
229
  return parsed.text || null;
230
- }`;function oA(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 Nl(e){return e.parserType??oA(e.streamParser)??"plain"}function Fl(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function _l(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(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 $l(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function jl(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
231
- `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,a=r===n.length-1?",":"";return`${s}${o}${a}`})}function Ul(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(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,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="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} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function mp(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 Uh(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),Uh(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Jo(e,t,n,o){n&&(e.push(`${o}${t}: {`),Uh(e,n,`${o} `),e.push(`${o}},`))}function Oa(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function zh(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:eA(n.hooks)}:void 0;return t==="esm"?rA(o,r):t==="script-installer"?iA(o,r):t==="script-advanced"?cA(o,r):t==="react-component"?sA(o,r):t==="react-advanced"?aA(o,r):lA(o,r)}function rA(e,t){let n=t?.hooks,o=Nl(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Oa(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Jo(s,"theme",e.theme," "),e.launcher&&Jo(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(" },")),s.push(...jl(e," ")),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(...Fl(e," ")),s.push(..._l(e," ",n)),s.push(...$l(e," ")),s.push(...Ul(e," ")),s.push(...mp(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
232
- `)}function sA(e,t){let n=t?.hooks,o=Nl(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Oa(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Jo(s,"theme",e.theme," "),e.launcher&&Jo(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(" },")),s.push(...jl(e," ")),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(...Fl(e," ")),s.push(..._l(e," ",n)),s.push(...$l(e," ")),s.push(...Ul(e," ")),s.push(...mp(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
233
- `)}function aA(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: '${Oa(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&&Jo(o,"theme",e.theme," "),e.launcher&&Jo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...jl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Fl(e," ")),o.push(..._l(e," ",n)),o.push(...$l(e," ")),o.push(...Ul(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${tA}),`)),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(` ${Fh}`),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(` ${Fh}`),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(` ${$h}`),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(` ${$h}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
234
- `)}function qh(e){let t=Nl(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.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&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function iA(e,t){let n=qh(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${fp(t)}/install.global.js" data-config='${s}'></script>`}function lA(e,t){let n=t?.hooks,o=Nl(e),r=o!=="plain",s=fp(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Oa(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Jo(a,"theme",e.theme," "),e.launcher&&Jo(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,p])=>{a.push(` ${i}: "${p}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"?a.push(` ${i}: ${p},`):typeof p=="number"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,p])=>{a.push(` ${i}: ${p},`)}),a.push(" },")),a.push(...jl(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{a.push(` "${i}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...Fl(e," ")),a.push(..._l(e," ",n)),a.push(...$l(e," ")),a.push(...Ul(e," ")),a.push(...mp(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
235
- `)}function cA(e,t){let n=t?.hooks,o=qh(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
236
- `).map((a,i)=>i===0?a:" "+a).join(`
237
- `)};`,""," // Constants",` var CDN_BASE = '${fp(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${nA});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${_h}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${_h}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${jh}`),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(` ${jh}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Oa(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
238
- `)}var Vh={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kh=.1,Gh=.15,Jh=1.5,hp=24,Yh=40,dA=`
230
+ }`;function FM(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 Sd(e){return e.parserType??FM(e.streamParser)??"plain"}function Ad(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function Td(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,l])=>i!=="onFeedback"&&i!=="onCopy"&&l!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([i,l])=>{i==="onFeedback"||i==="onCopy"||(typeof l=="string"?o.push(`${t} ${i}: "${l}",`):typeof l=="boolean"&&o.push(`${t} ${i}: ${l},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function Ed(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Md(e,t){if(!e.suggestions)return[];let n=JSON.stringify(e.suggestions,null,2).split(`
231
+ `);return n.map((o,r)=>{let s=r===0?`${t}suggestions: `:t,i=r===n.length-1?",":"";return`${s}${o}${i}`})}function kd(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(n.push(`${t} avatar: {`),Object.entries(i).forEach(([l,d])=>{typeof d=="string"?n.push(`${t} ${l}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${l}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?n.push(`${t} ${d}: "${u}",`):typeof u=="boolean"&&n.push(`${t} ${d}: ${u},`))}),n.push(`${t} },`)):typeof i=="string"?n.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&n.push(`${t} ${s}: ${i},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Dg(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 CC(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),CC(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function Tr(e,t,n,o){n&&(e.push(`${o}${t}: {`),CC(e,n,`${o} `),e.push(`${o}},`))}function Xa(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function wC(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:DM(n.hooks)}:void 0;return t==="esm"?$M(o,r):t==="script-installer"?UM(o,r):t==="script-advanced"?VM(o,r):t==="react-component"?jM(o,r):t==="react-advanced"?zM(o,r):qM(o,r)}function $M(e,t){let n=t?.hooks,o=Sd(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Xa(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Tr(s,"theme",e.theme," "),e.launcher&&Tr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Md(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ad(e," ")),s.push(...Td(e," ",n)),s.push(...Ed(e," ")),s.push(...kd(e," ")),s.push(...Dg(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
232
+ `)}function jM(e,t){let n=t?.hooks,o=Sd(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Xa(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Tr(s,"theme",e.theme," "),e.launcher&&Tr(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([i,l])=>{s.push(` ${i}: "${l}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"?s.push(` ${i}: ${l},`):typeof l=="number"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,l])=>{typeof l=="string"?s.push(` ${i}: "${l}",`):typeof l=="boolean"&&s.push(` ${i}: ${l},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([i,l])=>{s.push(` ${i}: ${l},`)}),s.push(" },")),s.push(...Md(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ad(e," ")),s.push(...Td(e," ",n)),s.push(...Ed(e," ")),s.push(...kd(e," ")),s.push(...Dg(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
233
+ `)}function zM(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: '${Xa(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&&Tr(o,"theme",e.theme," "),e.launcher&&Tr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),o.push(...Md(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Ad(e," ")),o.push(...Td(e," ",n)),o.push(...Ed(e," ")),o.push(...kd(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(${_M}),`)),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(` ${hC}`),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(` ${hC}`),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(` ${bC}`),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(` ${bC}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
234
+ `)}function xC(e){let t=Sd(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestions&&(o.suggestions=e.suggestions),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,i])=>{typeof i=="string"&&(r[s]=i)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,i])=>{s!=="onFeedback"&&s!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(r[s]=i)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([i,l])=>{i!=="render"&&(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([i,l])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof l=="object"&&l!==null)s.avatar=l;else if(i==="timestamp"&&typeof l=="object"&&l!==null){let d={};Object.entries(l).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(d[u]=p)}),Object.keys(d).length>0&&(s.timestamp=d)}else(typeof l=="string"||typeof l=="boolean")&&(s[i]=l)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function UM(e,t){let n=xC(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${Og(t)}/install.global.js" data-config='${s}'></script>`}function qM(e,t){let n=t?.hooks,o=Sd(e),r=o!=="plain",s=Og(t),i=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Xa(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&i.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&i.push(` clientToken: "${e.clientToken}",`),e.agentId&&i.push(` agentId: "${e.agentId}",`),e.target&&i.push(` target: "${e.target}",`),e.flowId&&i.push(` flowId: "${e.flowId}",`),r&&i.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Tr(i,"theme",e.theme," "),e.launcher&&Tr(i,"launcher",e.launcher," "),e.copy&&(i.push(" copy: {"),Object.entries(e.copy).forEach(([l,d])=>{i.push(` ${l}: "${d}",`)}),i.push(" },")),e.sendButton&&(i.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.voiceRecognition&&(i.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"?i.push(` ${l}: ${d},`):typeof d=="number"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.statusIndicator&&(i.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([l,d])=>{typeof d=="string"?i.push(` ${l}: "${d}",`):typeof d=="boolean"&&i.push(` ${l}: ${d},`)}),i.push(" },")),e.features&&(i.push(" features: {"),Object.entries(e.features).forEach(([l,d])=>{i.push(` ${l}: ${d},`)}),i.push(" },")),i.push(...Md(e," ")),e.suggestionChips&&e.suggestionChips.length>0&&(i.push(" suggestionChips: ["),e.suggestionChips.forEach(l=>{i.push(` "${l}",`)}),i.push(" ],")),e.suggestionChipsConfig&&(i.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&i.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&i.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&i.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&i.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),i.push(" },")),i.push(...Ad(e," ")),i.push(...Td(e," ",n)),i.push(...Ed(e," ")),i.push(...kd(e," ")),i.push(...Dg(n," ")),e.debug&&i.push(` debug: ${e.debug},`),n?.postprocessMessage?i.push(` postprocessMessage: ${n.postprocessMessage}`):i.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),i.push(" }"),i.push(" });"),i.push("</script>"),i.join(`
235
+ `)}function VM(e,t){let n=t?.hooks,o=xC(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
236
+ `).map((i,l)=>l===0?i:" "+i).join(`
237
+ `)};`,""," // Constants",` var CDN_BASE = '${Og(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${NM});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${yC}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${yC}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${vC}`),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(` ${vC}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Xa(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
238
+ `)}var SC={desktop:{w:1280,h:800},mobile:{w:390,h:844}},AC=.1,TC=.15,EC=1.5,_g=24,MC=40,KM=`
239
239
  /* \u2500\u2500 Root \u2500\u2500 */
240
240
  .persona-dc-root {
241
241
  display: flex;
@@ -386,7 +386,7 @@ ${s.join(`
386
386
  .persona-dc-stage {
387
387
  height: 550px;
388
388
  min-height: 400px;
389
- padding: ${hp}px;
389
+ padding: ${_g}px;
390
390
  overflow: auto;
391
391
  background: #f0f1f3;
392
392
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -476,5 +476,5 @@ ${s.join(`
476
476
  min-height: 300px;
477
477
  }
478
478
  }
479
- `;function pA(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=dA,document.head.appendChild(e)}function uA(e,t){let n=e.clientWidth-hp*2-Yh,o=e.clientHeight-hp*2-Yh;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function gA(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function Xh(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="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");pA();let c=Math.max(0,Math.min(o,n.length-1)),g=r,b=s,f=null,x=1,C=!1,S=y("div","persona-dc-root"),k=y("div","persona-dc-toolbar"),R=y("div","persona-dc-toolbar-lead"),E=y("div","persona-dc-toolbar-trail"),P=it({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>je(-1)}),B=y("div");B.style.position="relative";let N=y("button","persona-dc-title-btn");N.type="button",N.setAttribute("aria-expanded","false"),N.setAttribute("aria-haspopup","listbox");let $=y("span","persona-dc-title-text"),z=y("span","persona-dc-title-chevron"),q=se("chevron-down",12,"currentColor",2);q&&z.appendChild(q),N.append($,z);let X=y("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let A=!1;function J(){X.innerHTML="";for(let ie=0;ie<n.length;ie++){let Ie=n[ie],dt=y("button","persona-dc-dropdown-item");dt.type="button",dt.setAttribute("role","option"),dt.setAttribute("aria-current",ie===c?"true":"false");let tt=y("span");if(tt.textContent=Ie.title,dt.appendChild(tt),Ie.description){let xt=y("span","persona-dc-dropdown-desc");xt.textContent=Ie.description,dt.appendChild(xt)}dt.addEventListener("click",()=>{ce(),Ke(ie)}),X.appendChild(dt)}}function Z(){A=!A,X.style.display=A?"":"none",N.setAttribute("aria-expanded",A?"true":"false"),A&&J()}function ce(){A&&(A=!1,X.style.display="none",N.setAttribute("aria-expanded","false"))}N.addEventListener("click",ie=>{ie.stopPropagation(),Z()});let Y=()=>ce();document.addEventListener("click",Y),B.append(N,X);let he=it({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>je(1)}),te=y("span","persona-dc-counter");R.append(P,B,he,te);let be=null;i&&(be=co({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:ie=>{g=ie,ve.dataset.device=g,f=null,Pe()}}),E.appendChild(be.element));let ee=null;if(a){let ie=y("div","persona-dc-zoom-controls"),Ie=it({icon:"minus",label:"Zoom out",size:14,onClick:()=>{f=Math.max(Gh,(f??x)-Kh),Pe()}});ee=y("span","persona-dc-zoom-level"),ee.title="Reset to 100%",ee.style.cursor="pointer",ee.addEventListener("click",()=>{f=1,Pe()});let dt=it({icon:"plus",label:"Zoom in",size:14,onClick:()=>{f=Math.min(Jh,(f??x)+Kh),Pe()}}),tt=it({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,Pe()}});ie.append(Ie,ee,dt,tt),E.appendChild(ie)}if(p){let ie=y("div","persona-dc-separator");E.appendChild(ie);let Ie=co({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:dt=>{b=dt,ve.dataset.colorScheme=b,De()}});E.appendChild(Ie.element)}let ge=y("div","persona-dc-separator");E.appendChild(ge);let ne=it({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});E.appendChild(ne),k.append(R,E);let me=y("div","persona-dc-stage"),ve=y("div","persona-dc-iframe-wrapper");ve.dataset.device=g,ve.dataset.colorScheme=b;let ye=y("iframe","persona-dc-iframe");ye.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ye.setAttribute("loading","lazy"),ye.title=n[c].title,ve.appendChild(ye),me.appendChild(ve),S.append(k,me),e.appendChild(S);function De(){try{let ie=ye.contentDocument?.body;if(!ie)return;b==="dark"?ie.classList.add("theme-dark"):ie.classList.remove("theme-dark")}catch{}}ye.addEventListener("load",()=>De());function at(){let ie=n[c];$.textContent=ie.title,te.textContent=`${c+1} / ${n.length}`,ye.title=ie.title}function je(ie){let Ie=((c+ie)%n.length+n.length)%n.length;Ke(Ie)}function Ke(ie){ie<0||ie>=n.length||(c=ie,ye.src=n[c].url,at(),d?.(c,n[c]))}function Pe(){if(C)return;let ie=Vh[g]??Vh.desktop;x=uA(me,ie);let Ie=Math.max(Gh,Math.min(Jh,f??x));gA(ve,ye,ie,Ie,g),ee&&(ee.textContent=`${Math.round(Ie*100)}%`)}let $e=new ResizeObserver(()=>Pe());$e.observe(me),at(),ye.src=n[c].url,requestAnimationFrame(()=>Pe());function Ae(){C||(C=!0,$e.disconnect(),document.removeEventListener("click",Y),S.remove())}return{element:S,goTo:Ke,next:()=>je(1),prev:()=>je(-1),getIndex:()=>c,setDevice(ie){g=ie,ve.dataset.device=ie,be?.setSelected(ie),f=null,Pe()},setColorScheme(ie){b=ie,ve.dataset.colorScheme=ie},setZoom(ie){f=ie,Pe()},destroy:Ae}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
479
+ `;function GM(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=KM,document.head.appendChild(e)}function YM(e,t){let n=e.clientWidth-_g*2-MC,o=e.clientHeight-_g*2-MC;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function JM(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function kC(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:i=!0,showDeviceToggle:l=!0,showColorSchemeToggle:d=!0,onChange:u}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");GM();let p=Math.max(0,Math.min(o,n.length-1)),g=r,y=s,m=null,b=1,x=!1,T=v("div","persona-dc-root"),H=v("div","persona-dc-toolbar"),_=v("div","persona-dc-toolbar-lead"),P=v("div","persona-dc-toolbar-trail"),A=rt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>He(-1)}),B=v("div");B.style.position="relative";let R=v("button","persona-dc-title-btn");R.type="button",R.setAttribute("aria-expanded","false"),R.setAttribute("aria-haspopup","listbox");let W=v("span","persona-dc-title-text"),U=v("span","persona-dc-title-chevron"),V=de("chevron-down",12,"currentColor",2);V&&U.appendChild(V),R.append(W,U);let Z=v("div","persona-dc-dropdown");Z.setAttribute("role","listbox"),Z.style.display="none";let j=!1;function X(){Z.innerHTML="";for(let ve=0;ve<n.length;ve++){let Ne=n[ve],ft=v("button","persona-dc-dropdown-item");ft.type="button",ft.setAttribute("role","option"),ft.setAttribute("aria-current",ve===p?"true":"false");let Ae=v("span");if(Ae.textContent=Ne.title,ft.appendChild(Ae),Ne.description){let Fe=v("span","persona-dc-dropdown-desc");Fe.textContent=Ne.description,ft.appendChild(Fe)}ft.addEventListener("click",()=>{xe(),Qe(ve)}),Z.appendChild(ft)}}function ue(){j=!j,Z.style.display=j?"":"none",R.setAttribute("aria-expanded",j?"true":"false"),j&&X()}function xe(){j&&(j=!1,Z.style.display="none",R.setAttribute("aria-expanded","false"))}R.addEventListener("click",ve=>{ve.stopPropagation(),ue()});let Ce=()=>xe();document.addEventListener("click",Ce),B.append(R,Z);let ye=rt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>He(1)}),oe=v("span","persona-dc-counter");_.append(A,B,ye,oe);let le=null;l&&(le=$o({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:g,onSelect:ve=>{g=ve,we.dataset.device=g,m=null,Oe()}}),P.appendChild(le.element));let ae=null;if(i){let ve=v("div","persona-dc-zoom-controls"),Ne=rt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{m=Math.max(TC,(m??b)-AC),Oe()}});ae=v("span","persona-dc-zoom-level"),ae.title="Reset to 100%",ae.style.cursor="pointer",ae.addEventListener("click",()=>{m=1,Oe()});let ft=rt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{m=Math.min(EC,(m??b)+AC),Oe()}}),Ae=rt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,Oe()}});ve.append(Ne,ae,ft,Ae),P.appendChild(ve)}if(d){let ve=v("div","persona-dc-separator");P.appendChild(ve);let Ne=$o({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:y,onSelect:ft=>{y=ft,we.dataset.colorScheme=y,Se()}});P.appendChild(Ne.element)}let M=v("div","persona-dc-separator");P.appendChild(M);let ee=rt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});P.appendChild(ee),H.append(_,P);let pe=v("div","persona-dc-stage"),we=v("div","persona-dc-iframe-wrapper");we.dataset.device=g,we.dataset.colorScheme=y;let me=v("iframe","persona-dc-iframe");me.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),me.setAttribute("loading","lazy"),me.title=n[p].title,we.appendChild(me),pe.appendChild(we),T.append(H,pe),e.appendChild(T);function Se(){try{let ve=me.contentDocument?.body;if(!ve)return;y==="dark"?ve.classList.add("theme-dark"):ve.classList.remove("theme-dark")}catch{}}me.addEventListener("load",()=>Se());function Le(){let ve=n[p];W.textContent=ve.title,oe.textContent=`${p+1} / ${n.length}`,me.title=ve.title}function He(ve){let Ne=((p+ve)%n.length+n.length)%n.length;Qe(Ne)}function Qe(ve){ve<0||ve>=n.length||(p=ve,me.src=n[p].url,Le(),u?.(p,n[p]))}function Oe(){if(x)return;let ve=SC[g]??SC.desktop;b=YM(pe,ve);let Ne=Math.max(TC,Math.min(EC,m??b));JM(we,me,ve,Ne,g),ae&&(ae.textContent=`${Math.round(Ne*100)}%`)}let We=new ResizeObserver(()=>Oe());We.observe(pe),Le(),me.src=n[p].url,requestAnimationFrame(()=>Oe());function tt(){x||(x=!0,We.disconnect(),document.removeEventListener("click",Ce),T.remove())}return{element:T,goTo:Qe,next:()=>He(1),prev:()=>He(-1),getIndex:()=>p,setDevice(ve){g=ve,we.dataset.device=ve,le?.setSelected(ve),m=null,Oe()},setColorScheme(ve){y=ve,we.dataset.colorScheme=ve},setZoom(ve){m=ve,Oe()},destroy:tt}}0&&(module.exports={ASK_USER_QUESTION_CLIENT_TOOL,ASK_USER_QUESTION_PARAMETERS_SCHEMA,ASK_USER_QUESTION_TOOL_NAME,AgentWidgetClient,AgentWidgetSession,AttachmentManager,BrowserSpeechEngine,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,HistoryProviderError,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,ReadAloudController,SUGGEST_REPLIES_CLIENT_TOOL,SUGGEST_REPLIES_PARAMETERS_SCHEMA,SUGGEST_REPLIES_TOOL_NAME,THEME_ZONES,VERSION,WEBMCP_TOOL_PREFIX,WebMcpBridge,accessibilityPlugin,animationsPlugin,applyFeaturePreferences,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,builtInClientToolsForDispatch,canonicalArtifactDisplayMode,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createAskUserQuestionBubble,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createRovingTablist,createSlashCommandsSource,createSplitButton,createStandardBubble,createStaticMentionSource,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultMentionFilter,defaultParseRules,detectColorScheme,directivePostprocessor,ensureAskUserQuestionSheet,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isAskUserQuestionMessage,isComponentDirectiveType,isDockedMountMode,isHistoryProviderError,isSuggestRepliesMessage,isVoiceSupported,isWebMcpToolName,isWelcomeVisible,latestAgentSuggestions,listRegisteredStreamAnimations,loadMarkdownParsers,markdownPostprocessor,mergeWithDefaults,normalizeContent,normalizeMediaType,onMarkdownParsersReady,parseAskUserQuestionPayload,parseSuggestRepliesPayload,parseWidgetPreferenceSlice,pickBestVoice,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,removeAskUserQuestionSheet,renderComponentDirective,renderLoadingIndicatorWithFallback,renderLucideIcon,resolveArtifactDisplay,resolveArtifactDisplayMode,resolveConfigPreferences,resolveDockConfig,resolveSanitizer,resolveTokens,resolveWelcomeConfig,stripWebMcpPrefix,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
480
480
  //# sourceMappingURL=index.cjs.map