@runtypelabs/persona 4.14.0 → 4.16.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 (119) hide show
  1. package/README.md +4 -4
  2. package/dist/animations/glyph-cycle.d.cts +1 -1
  3. package/dist/animations/glyph-cycle.d.ts +1 -1
  4. package/dist/animations/{types-DveIaNx6.d.cts → types-BpWGm7_6.d.cts} +17 -0
  5. package/dist/animations/{types-DveIaNx6.d.ts → types-BpWGm7_6.d.ts} +17 -0
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/chunk-QJ4LV2KW.js +1 -0
  9. package/dist/codegen.cjs +12 -11
  10. package/dist/codegen.js +14 -13
  11. package/dist/{context-mentions-ONG7A7M6.js → context-mentions-BTSTIBFC.js} +1 -1
  12. package/dist/context-mentions.cjs +11 -8
  13. package/dist/context-mentions.d.cts +520 -21
  14. package/dist/context-mentions.d.ts +520 -21
  15. package/dist/context-mentions.js +11 -8
  16. package/dist/index.cjs +69 -68
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.d.cts +595 -46
  19. package/dist/index.d.ts +595 -46
  20. package/dist/index.global.js +60 -57
  21. package/dist/index.global.js.map +1 -1
  22. package/dist/index.js +69 -68
  23. package/dist/index.js.map +1 -1
  24. package/dist/launcher.global.js +5 -2
  25. package/dist/launcher.global.js.map +1 -1
  26. package/dist/smart-dom-reader.d.cts +520 -21
  27. package/dist/smart-dom-reader.d.ts +520 -21
  28. package/dist/testing.cjs +3 -3
  29. package/dist/testing.d.cts +7 -0
  30. package/dist/testing.d.ts +7 -0
  31. package/dist/testing.js +3 -3
  32. package/dist/theme-editor-preview.cjs +67 -67
  33. package/dist/theme-editor-preview.d.cts +534 -22
  34. package/dist/theme-editor-preview.d.ts +534 -22
  35. package/dist/theme-editor-preview.js +57 -57
  36. package/dist/theme-editor.cjs +10 -10
  37. package/dist/theme-editor.d.cts +521 -23
  38. package/dist/theme-editor.d.ts +521 -23
  39. package/dist/theme-editor.js +10 -10
  40. package/dist/theme-reference.cjs +1 -1
  41. package/dist/theme-reference.d.cts +104 -3
  42. package/dist/theme-reference.d.ts +104 -3
  43. package/dist/theme-reference.js +1 -1
  44. package/dist/widget.css +1 -1
  45. package/package.json +1 -1
  46. package/src/ask-user-question-tool.ts +10 -7
  47. package/src/components/artifact-pane.test.ts +27 -0
  48. package/src/components/artifact-pane.ts +7 -3
  49. package/src/components/artifact-preview.ts +1 -1
  50. package/src/components/composer-parts.test.ts +103 -4
  51. package/src/components/composer-parts.ts +53 -15
  52. package/src/components/header-builder.ts +27 -2
  53. package/src/components/header-layouts.test.ts +56 -0
  54. package/src/components/header-layouts.ts +29 -9
  55. package/src/components/launcher-surface.test.ts +403 -0
  56. package/src/components/launcher.ts +297 -2
  57. package/src/components/messages.ts +5 -2
  58. package/src/components/panel.ts +92 -71
  59. package/src/components/pill-composer-builder.test.ts +18 -0
  60. package/src/components/suggestions.test.ts +273 -0
  61. package/src/components/suggestions.ts +528 -86
  62. package/src/components/welcome.test.ts +121 -0
  63. package/src/components/welcome.ts +305 -0
  64. package/src/components/widget-view.test.ts +5 -3
  65. package/src/components/widget-view.ts +18 -7
  66. package/src/defaults.ts +7 -5
  67. package/src/generated/runtype-openapi-contract.ts +17 -0
  68. package/src/index-core.ts +29 -2
  69. package/src/launcher-global.ts +11 -8
  70. package/src/plugins/types.ts +136 -3
  71. package/src/presets.ts +3 -3
  72. package/src/session.ts +10 -8
  73. package/src/styles/widget-styles.test.ts +382 -0
  74. package/src/styles/widget.css +778 -4
  75. package/src/suggest-replies-tool.test.ts +233 -2
  76. package/src/suggest-replies-tool.ts +115 -39
  77. package/src/testing/mock-stream.test.ts +19 -0
  78. package/src/testing/mock-stream.ts +20 -0
  79. package/src/theme-editor/preview-utils.test.ts +34 -0
  80. package/src/theme-editor/preview-utils.ts +77 -2
  81. package/src/theme-editor/sections.test.ts +33 -0
  82. package/src/theme-editor/sections.ts +83 -6
  83. package/src/theme-reference.ts +34 -5
  84. package/src/types/theme.ts +72 -3
  85. package/src/types.ts +312 -18
  86. package/src/ui.body-top-slot.test.ts +95 -0
  87. package/src/ui.content-width.test.ts +91 -0
  88. package/src/ui.detached-panel.test.ts +1 -1
  89. package/src/ui.docked.test.ts +7 -4
  90. package/src/ui.launcher-teaser.test.ts +162 -0
  91. package/src/ui.rebuild-composer.test.ts +491 -0
  92. package/src/ui.render-welcome.test.ts +505 -0
  93. package/src/ui.scroll-additive.test.ts +91 -21
  94. package/src/ui.scroll.test.ts +302 -14
  95. package/src/ui.suggest-replies.test.ts +1112 -1
  96. package/src/ui.ts +1008 -149
  97. package/src/ui.welcome.test.ts +504 -0
  98. package/src/utils/artifact-file.test.ts +1 -1
  99. package/src/utils/artifact-gate.test.ts +27 -0
  100. package/src/utils/artifact-gate.ts +9 -0
  101. package/src/utils/attachment-manager.test.ts +37 -0
  102. package/src/utils/attachment-manager.ts +15 -0
  103. package/src/utils/auto-follow.test.ts +23 -0
  104. package/src/utils/auto-follow.ts +11 -1
  105. package/src/utils/code-generators.test.ts +40 -0
  106. package/src/utils/code-generators.ts +22 -0
  107. package/src/utils/config-merge.test.ts +24 -0
  108. package/src/utils/config-merge.ts +2 -0
  109. package/src/utils/content-width.test.ts +37 -0
  110. package/src/utils/content-width.ts +17 -0
  111. package/src/utils/icons.test.ts +26 -0
  112. package/src/utils/icons.ts +8 -0
  113. package/src/utils/plugin-storage.test.ts +94 -0
  114. package/src/utils/plugin-storage.ts +98 -0
  115. package/src/utils/theme.test.ts +216 -0
  116. package/src/utils/tokens.ts +113 -3
  117. package/src/welcome.test.ts +213 -0
  118. package/src/welcome.ts +130 -0
  119. package/dist/chunk-MMUPR2JW.js +0 -1
@@ -1,37 +1,37 @@
1
- "use strict";var AgentWidget=(()=>{var lb=Object.create;var js=Object.defineProperty;var db=Object.getOwnPropertyDescriptor;var cb=Object.getOwnPropertyNames;var pb=Object.getPrototypeOf,ub=Object.prototype.hasOwnProperty;var Ea=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var fb=(e,t)=>()=>(e&&(t=e(e=0)),t);var Of=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Nf=(e,t)=>{for(var n in t)js(e,n,{get:t[n],enumerable:!0})},_f=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of cb(t))!ub.call(e,r)&&r!==n&&js(e,r,{get:()=>t[r],enumerable:!(o=db(t,r))||o.enumerable});return e};var ho=(e,t,n)=>(n=e!=null?lb(pb(e)):{},_f(t||!e||!e.__esModule?js(n,"default",{value:e,enumerable:!0}):n,e)),mb=e=>_f(js({},"__esModule",{value:!0}),e);var id=Of(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Allow=ye.ALL=ye.COLLECTION=ye.ATOM=ye.SPECIAL=ye.INF=ye._INFINITY=ye.INFINITY=ye.NAN=ye.BOOL=ye.NULL=ye.OBJ=ye.ARR=ye.NUM=ye.STR=void 0;ye.STR=1;ye.NUM=2;ye.ARR=4;ye.OBJ=8;ye.NULL=16;ye.BOOL=32;ye.NAN=64;ye.INFINITY=128;ye._INFINITY=256;ye.INF=ye.INFINITY|ye._INFINITY;ye.SPECIAL=ye.NULL|ye.BOOL|ye.INF|ye.NAN;ye.ATOM=ye.STR|ye.NUM|ye.SPECIAL;ye.COLLECTION=ye.ARR|ye.OBJ;ye.ALL=ye.ATOM|ye.COLLECTION;ye.Allow={STR:ye.STR,NUM:ye.NUM,ARR:ye.ARR,OBJ:ye.OBJ,NULL:ye.NULL,BOOL:ye.BOOL,NAN:ye.NAN,INFINITY:ye.INFINITY,_INFINITY:ye._INFINITY,INF:ye.INF,SPECIAL:ye.SPECIAL,ATOM:ye.ATOM,COLLECTION:ye.COLLECTION,ALL:ye.ALL};ye.default=ye.Allow});var Ys=Of(_t=>{"use strict";var Db=_t&&_t.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),Fb=_t&&_t.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Db(t,e,n)};Object.defineProperty(_t,"__esModule",{value:!0});_t.Allow=_t.MalformedJSON=_t.PartialJSON=_t.parseJSON=_t.parse=void 0;var Jt=id();Object.defineProperty(_t,"Allow",{enumerable:!0,get:function(){return Jt.Allow}});Fb(id(),_t);var Js=class extends Error{};_t.PartialJSON=Js;var Qs=class extends Error{};_t.MalformedJSON=Qs;function im(e,t=Jt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Ob(e.trim(),t)}_t.parseJSON=im;var Ob=(e,t)=>{let n=e.length,o=0,r=g=>{throw new Js(`${g} at position ${o}`)},a=g=>{throw new Qs(`${g} at position ${o}`)},s=()=>(u(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?c():e.substring(o,o+4)==="null"||Jt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Jt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Jt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Jt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Jt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Jt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):d()),l=()=>{let g=o,f=!1;for(o++;o<n&&(e[o]!=='"'||f&&e[o-1]==="\\");)f=e[o]==="\\"?!f:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(g,++o-Number(f)))}catch(h){a(String(h))}else if(Jt.Allow.STR&t)try{return JSON.parse(e.substring(g,o-Number(f))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},p=()=>{o++,u();let g={};try{for(;e[o]!=="}";){if(u(),o>=n&&Jt.Allow.OBJ&t)return g;let f=l();u(),o++;try{let h=s();g[f]=h}catch(h){if(Jt.Allow.OBJ&t)return g;throw h}u(),e[o]===","&&o++}}catch{if(Jt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},c=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),u(),e[o]===","&&o++}catch{if(Jt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},d=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(Jt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(f))}}let g=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(Jt.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,o))}catch{e.substring(g,o)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(h){a(String(h))}}},u=()=>{for(;o<n&&`
2
- \r `.includes(e[o]);)o++};return s()},Nb=im;_t.parse=Nb});var qm={};Nf(qm,{createReconnectController:()=>Mx});function Mx(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let h=n;n=null,h()}},s=()=>{let h=e.getStatus();h!=="resuming"&&h!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},c=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},d=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=h=>new Promise(A=>{n=A,o=setTimeout(()=>{o=null,n=null,A()},h)}),g=()=>{let h=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,d(),e.setAbortController(null);let A=!1;for(let k of e.getMessages())k.streaming&&(k.streaming=!1,A=!0);let E=e.buildErrorContent("Connection lost and the response could not be resumed.");E?e.appendMessage({id:`reconnect-failed-${h?.executionId??e.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):A&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},f=async()=>{let h=e.config.reconnect?.backoffMs??Sx,A=e.config.reconnect?.maxAttempts??h.length,E=e.config.reconnectStream;if(!E){e.setReconnecting(!1);return}for(;e.getResumable()&&t<A;){t+=1,e.setStatus("resuming");let k=e.getResumable(),M=k.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:k,attempt:t});let C=null;try{let T=await E({executionId:k.executionId,after:k.lastEventId,signal:S.signal});T&&T.ok&&T.body&&(C=T.body)}catch{C=null}if(S.signal.aborted)return;if(C){let T=e.getMessages().find(w=>w.id===k.assistantMessageId)?.content,W=typeof T=="string"?T:"";try{await e.resumeConnect(C,k.assistantMessageId,W)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,d(),e.emitReconnect({phase:"resumed",handle:k});return}e.getResumable().lastEventId!==M&&(t=0)}if(e.getResumable()&&t<A&&(e.setStatus("paused"),await u(h[Math.min(t-1,h.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,d()},wake:a}}var Sx,Vm=fb(()=>{"use strict";Sx=[1e3,2e3,4e3,8e3,8e3]});var pA={};Nf(pA,{ASK_USER_QUESTION_CLIENT_TOOL:()=>yd,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>hd,ASK_USER_QUESTION_TOOL_NAME:()=>Wa,AgentWidgetClient:()=>er,AgentWidgetSession:()=>Fr,AttachmentManager:()=>or,BrowserSpeechEngine:()=>Eo,DEFAULT_COMPONENTS:()=>Mp,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Ri,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>pn,DEFAULT_PALETTE:()=>Ap,DEFAULT_SEMANTIC:()=>Sp,DEFAULT_WIDGET_CONFIG:()=>st,PRESETS:()=>Su,PRESET_FULLSCREEN:()=>Au,PRESET_MINIMAL:()=>wu,PRESET_SHOP:()=>Cu,ReadAloudController:()=>nr,SUGGEST_REPLIES_CLIENT_TOOL:()=>ni,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>fd,SUGGEST_REPLIES_TOOL_NAME:()=>kn,THEME_ZONES:()=>ag,VERSION:()=>Zo,WEBMCP_TOOL_PREFIX:()=>En,WebMcpBridge:()=>Pr,accessibilityPlugin:()=>ey,animationsPlugin:()=>ty,applyFeaturePreferences:()=>su,applyThemeVariables:()=>rr,attachHeaderToContainer:()=>ir,brandPlugin:()=>ny,buildComposer:()=>jr,buildDefaultHeader:()=>_p,buildHeader:()=>eo,buildHeaderWithLayout:()=>$r,buildMinimalHeader:()=>Up,builtInClientToolsForDispatch:()=>Hr,canonicalArtifactDisplayMode:()=>on,collectEnrichedPageContext:()=>Yh,componentRegistry:()=>Ln,createActionManager:()=>cs,createAgentExperience:()=>vl,createAskUserQuestionBubble:()=>Cm,createBestAvailableVoiceProvider:()=>yi,createBubbleWithLayout:()=>Xg,createCSATFeedback:()=>yl,createComboButton:()=>_i,createComponentMiddleware:()=>kh,createComponentStreamParser:()=>ml,createDefaultSanitizer:()=>nd,createDirectivePostprocessor:()=>$f,createDropdownMenu:()=>Ro,createFlexibleJsonStreamParser:()=>Mm,createIconButton:()=>Mt,createImagePart:()=>Im,createJsonStreamParser:()=>ci,createLabelButton:()=>Zn,createLocalStorageAdapter:()=>fl,createMarkdownProcessor:()=>La,createMarkdownProcessorFromConfig:()=>Qo,createMessageActions:()=>Xp,createNPSFeedback:()=>bl,createPlainTextParser:()=>li,createPlugin:()=>ay,createRegexJsonParser:()=>di,createSlashCommandsSource:()=>Uh,createStandardBubble:()=>Gr,createStaticMentionSource:()=>_h,createTextPart:()=>Mo,createTheme:()=>za,createThemeObserver:()=>Nr,createToggleGroup:()=>qr,createTypingIndicator:()=>lr,createVoiceProvider:()=>To,createWidgetHostLayout:()=>us,createXmlParser:()=>pi,defaultActionHandlers:()=>mr,defaultJsonActionParser:()=>ds,defaultMentionFilter:()=>wl,defaultParseRules:()=>xu,detectColorScheme:()=>$a,directivePostprocessor:()=>jf,ensureAskUserQuestionSheet:()=>Wr,escapeHtml:()=>Hn,extractComponentDirectiveFromMessage:()=>hl,fileToImagePart:()=>Wm,formatEnrichedContext:()=>Zh,generateAssistantMessageId:()=>So,generateMessageId:()=>km,generateStableSelector:()=>vu,generateUserMessageId:()=>Br,getActiveTheme:()=>ko,getColorScheme:()=>Di,getDisplayText:()=>Pm,getHeaderLayout:()=>qp,getImageParts:()=>Rm,getPreset:()=>iy,hasComponentDirective:()=>ps,hasImages:()=>mi,headerLayouts:()=>el,highContrastPlugin:()=>ry,initAgentWidget:()=>Oh,isAskUserQuestionMessage:()=>Xn,isComponentDirectiveType:()=>Eh,isDockedMountMode:()=>Et,isSuggestRepliesMessage:()=>Ba,isVoiceSupported:()=>_a,isWebMcpToolName:()=>yo,latestAgentSuggestions:()=>oi,listRegisteredStreamAnimations:()=>Fp,loadMarkdownParsers:()=>ka,markdownPostprocessor:()=>td,mergeWithDefaults:()=>Or,normalizeContent:()=>Lm,normalizeMediaType:()=>bo,onMarkdownParsersReady:()=>kr,parseAskUserQuestionPayload:()=>Jn,parseSuggestRepliesPayload:()=>gd,parseWidgetPreferenceSlice:()=>au,pickBestVoice:()=>Dr,pluginRegistry:()=>ls,reducedMotionPlugin:()=>oy,registerStreamAnimationPlugin:()=>sr,removeAskUserQuestionSheet:()=>Co,renderComponentDirective:()=>gl,renderLoadingIndicatorWithFallback:()=>Gp,renderLucideIcon:()=>oe,resolveArtifactDisplay:()=>sd,resolveArtifactDisplayMode:()=>Bn,resolveConfigPreferences:()=>is,resolveDockConfig:()=>rn,resolveSanitizer:()=>Lr,resolveTokens:()=>Hi,stripWebMcpPrefix:()=>Xs,themeToCssVariables:()=>Bi,unregisterStreamAnimationPlugin:()=>Dp,validateImageFile:()=>Hm,validateTheme:()=>Tp});var Er=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:d=>{o=d,n&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(o??t)().then(u=>(r=u,u)).catch(u=>{throw a=null,u}),a),provide:d=>{r=d},getSync:()=>r}};var{setLoader:gb,load:hb,provide:bA,getSync:ed}=Er({fallbackImport:()=>import("./markdown-parsers-entry")}),Gs=new Set,yb=()=>{let e=[...Gs];Gs.clear();for(let t of e)try{t()}catch{}},Uf=gb,ka=()=>{let e=ed();return e?Promise.resolve(e):hb().then(t=>(yb(),t))},kr=e=>ed()?()=>{}:(Gs.add(e),ka().catch(()=>{}),()=>{Gs.delete(e)});var Gn=ed;var bb=e=>{if(e)return e},La=e=>{let t=null;return n=>{let o=Gn();if(!o)return Hn(n);if(!t){let{Marked:r}=o,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let s=bb(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},Qo=e=>e?La({markedOptions:e.options,renderer:e.renderer}):La(),xb=La(),td=e=>xb(e),Hn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Vf=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),qf=e=>`%%FORM_PLACEHOLDER_${e}%%`,zf=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=qf(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let a=qf(t.length);return t.push({token:a,type:r}),a}),n},$f=e=>{let t=Qo(e);return n=>{let o=[],r=zf(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Vf(l)}"></div>`;a=a.replace(p,d)}),a}},jf=e=>{let t=[],n=zf(e,t),o=td(n);return t.forEach(({token:r,type:a})=>{let s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Vf(a)}"></div>`;o=o.replace(s,p)}),o};var vb={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"]},Cb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,nd=()=>{let e=null;return t=>{let n=Gn();if(!n)return Hn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!Cb.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,vb)}},Lr=e=>e===!1?null:typeof e=="function"?e:nd();var Gf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Kf=e=>e.includes("|"),Xf=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())},wb=e=>`| ${e.join(" | ")} |`,Ab=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Sb=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Jf=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],a=t[o+1];if(!Kf(r)||Gf.test(r)||!Gf.test(a))continue;let s=Xf(r).length;if(s<1)continue;let l=Ab(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let c=t[p];if(c.trim()===""||!Kf(c))break;let d=wb(Sb(Xf(c),s));t[p]!==d&&(t[p]=d,n=!0)}o=p-1}return n?t.join(`
4
- `):e};var Qf="var(--persona-md-table-scroll-fade, 24px)",Yf=new WeakSet;function em(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 Zf(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":Qf),e.style.setProperty("--persona-fade-r",r<=1?"0px":Qf)}function od(e){Yf.has(e)||(Yf.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Zf(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Zf)}var En="webmcp:",rd=new Map,tm=e=>{rd.clear();for(let t of e){let n=t.title?.trim();n&&rd.set(t.name,n)}},Pa=e=>rd.get(Xs(e)),Ks={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ad=null,om=e=>{ad=e};function rm(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}:${Mb(t.join(""))}`}function nm(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);n=Math.imul(n^a,2654435761),o=Math.imul(o^a,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 Mb(e){let t=nm(e,0).toString(36),n=nm(e,2654435761).toString(36);return`${t}.${n}`}var Pr=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 Ks.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}tm(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let a={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=Eb(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Tn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let h=typeof document<"u"&&!!document.modelContext;return Tn(h?"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 a=Xs(t),s;try{s=await r.getTools()}catch(h){let A=h instanceof Error?h.message:String(h);return Tn(`Failed to read WebMCP registry: ${A}`)}tm(s);let l=s.find(h=>h.name===a);if(!l)return Tn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Tn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Tn("Aborted by cancel()");let p=Pa(a),c={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Tn("User declined the tool call.");if(o?.aborted)return Tn("Aborted by cancel()");let d=new AbortController,u=!1,g=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let h=await r.executeTool(l,Rb(n),{signal:d.signal});return kb(h)}catch(h){if(u)return Tn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Tn("Aborted by cancel()");let A=h instanceof Error?h.message:String(h);return Tn(A)}finally{clearTimeout(g),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}(ad?await ad():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ks.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,Ks.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??Lb;try{return await n(t)}catch(o){return Ks.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=>Tb(t,o))}},Xs=e=>e.startsWith(En)?e.slice(En.length):e,yo=e=>e.startsWith(En),Tb=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Eb=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},kb=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:Ib(t)}]}},Tn=e=>({isError:!0,content:[{type:"text",text:e}]}),Lb=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Pb(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ "use strict";var AgentWidget=(()=>{var Jx=Object.create;var hi=Object.defineProperty;var Qx=Object.getOwnPropertyDescriptor;var Yx=Object.getOwnPropertyNames;var Zx=Object.getPrototypeOf,ev=Object.prototype.hasOwnProperty;var es=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var tv=(e,t)=>()=>(e&&(t=e(e=0)),t);var rg=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ag=(e,t)=>{for(var n in t)hi(e,n,{get:t[n],enumerable:!0})},sg=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Yx(t))!ev.call(e,r)&&r!==n&&hi(e,r,{get:()=>t[r],enumerable:!(o=Qx(t,r))||o.enumerable});return e};var ko=(e,t,n)=>(n=e!=null?Jx(Zx(e)):{},sg(t||!e||!e.__esModule?hi(n,"default",{value:e,enumerable:!0}):n,e)),nv=e=>sg(hi({},"__esModule",{value:!0}),e);var Qc=rg(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.Allow=ve.ALL=ve.COLLECTION=ve.ATOM=ve.SPECIAL=ve.INF=ve._INFINITY=ve.INFINITY=ve.NAN=ve.BOOL=ve.NULL=ve.OBJ=ve.ARR=ve.NUM=ve.STR=void 0;ve.STR=1;ve.NUM=2;ve.ARR=4;ve.OBJ=8;ve.NULL=16;ve.BOOL=32;ve.NAN=64;ve.INFINITY=128;ve._INFINITY=256;ve.INF=ve.INFINITY|ve._INFINITY;ve.SPECIAL=ve.NULL|ve.BOOL|ve.INF|ve.NAN;ve.ATOM=ve.STR|ve.NUM|ve.SPECIAL;ve.COLLECTION=ve.ARR|ve.OBJ;ve.ALL=ve.ATOM|ve.COLLECTION;ve.Allow={STR:ve.STR,NUM:ve.NUM,ARR:ve.ARR,OBJ:ve.OBJ,NULL:ve.NULL,BOOL:ve.BOOL,NAN:ve.NAN,INFINITY:ve.INFINITY,_INFINITY:ve._INFINITY,INF:ve.INF,SPECIAL:ve.SPECIAL,ATOM:ve.ATOM,COLLECTION:ve.COLLECTION,ALL:ve.ALL};ve.default=ve.Allow});var wi=rg(_t=>{"use strict";var Sv=_t&&_t.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var r=Object.getOwnPropertyDescriptor(t,n);(!r||("get"in r?!t.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,r)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),Mv=_t&&_t.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Sv(t,e,n)};Object.defineProperty(_t,"__esModule",{value:!0});_t.Allow=_t.MalformedJSON=_t.PartialJSON=_t.parseJSON=_t.parse=void 0;var Zt=Qc();Object.defineProperty(_t,"Allow",{enumerable:!0,get:function(){return Zt.Allow}});Mv(Qc(),_t);var vi=class extends Error{};_t.PartialJSON=vi;var Ci=class extends Error{};_t.MalformedJSON=Ci;function Eg(e,t=Zt.Allow.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Tv(e.trim(),t)}_t.parseJSON=Eg;var Tv=(e,t)=>{let n=e.length,o=0,r=g=>{throw new vi(`${g} at position ${o}`)},a=g=>{throw new Ci(`${g} at position ${o}`)},s=()=>(f(),o>=n&&r("Unexpected end of input"),e[o]==='"'?l():e[o]==="{"?p():e[o]==="["?d():e.substring(o,o+4)==="null"||Zt.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):e.substring(o,o+4)==="true"||Zt.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):e.substring(o,o+5)==="false"||Zt.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):e.substring(o,o+8)==="Infinity"||Zt.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):e.substring(o,o+9)==="-Infinity"||Zt.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):e.substring(o,o+3)==="NaN"||Zt.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):c()),l=()=>{let g=o,m=!1;for(o++;o<n&&(e[o]!=='"'||m&&e[o-1]==="\\");)m=e[o]==="\\"?!m:!1,o++;if(e.charAt(o)=='"')try{return JSON.parse(e.substring(g,++o-Number(m)))}catch(b){a(String(b))}else if(Zt.Allow.STR&t)try{return JSON.parse(e.substring(g,o-Number(m))+'"')}catch{return JSON.parse(e.substring(g,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},p=()=>{o++,f();let g={};try{for(;e[o]!=="}";){if(f(),o>=n&&Zt.Allow.OBJ&t)return g;let m=l();f(),o++;try{let b=s();g[m]=b}catch(b){if(Zt.Allow.OBJ&t)return g;throw b}f(),e[o]===","&&o++}}catch{if(Zt.Allow.OBJ&t)return g;r("Expected '}' at end of object")}return o++,g},d=()=>{o++;let g=[];try{for(;e[o]!=="]";)g.push(s()),f(),e[o]===","&&o++}catch{if(Zt.Allow.ARR&t)return g;r("Expected ']' at end of array")}return o++,g},c=()=>{if(o===0){e==="-"&&a("Not sure what '-' is");try{return JSON.parse(e)}catch(m){if(Zt.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(m))}}let g=o;for(e[o]==="-"&&o++;e[o]&&",]}".indexOf(e[o])===-1;)o++;o==n&&!(Zt.Allow.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(g,o))}catch{e.substring(g,o)==="-"&&r("Not sure what '-' is");try{return JSON.parse(e.substring(g,e.lastIndexOf("e")))}catch(b){a(String(b))}}},f=()=>{for(;o<n&&`
2
+ \r `.includes(e[o]);)o++};return s()},Ev=Eg;_t.parse=Ev});var lh={};ag(lh,{createReconnectController:()=>mC});function mC(e){let t=0,n=null,o=null,r=!1,a=()=>{if(o&&(clearTimeout(o),o=null),n){let b=n;n=null,b()}},s=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||a()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||s()},p=()=>{s()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},f=b=>new Promise(w=>{n=w,o=setTimeout(()=>{o=null,n=null,w()},b)}),g=()=>{let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let w=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,w=!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()}):w&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},m=async()=>{let b=e.config.reconnect?.backoffMs??fC,w=e.config.reconnect?.maxAttempts??b.length,T=e.config.reconnectStream;if(!T){e.setReconnecting(!1);return}for(;e.getResumable()&&t<w;){t+=1,e.setStatus("resuming");let L=e.getResumable(),A=L.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let C=null;try{let M=await T({executionId:L.executionId,after:L.lastEventId,signal:S.signal});M&&M.ok&&M.body&&(C=M.body)}catch{C=null}if(S.signal.aborted)return;if(C){let M=e.getMessages().find(R=>R.id===L.assistantMessageId)?.content,P=typeof M=="string"?M:"";try{await e.resumeConnect(C,L.assistantMessageId,P)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==A&&(t=0)}if(e.getResumable()&&t<w&&(e.setStatus("paused"),await f(b[Math.min(t-1,b.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&g()};return{begin(){t=0,d(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:a}}var fC,ch=tv(()=>{"use strict";fC=[1e3,2e3,4e3,8e3,8e3]});var b0={};ag(b0,{ASK_USER_QUESTION_CLIENT_TOOL:()=>id,ASK_USER_QUESTION_PARAMETERS_SCHEMA:()=>sd,ASK_USER_QUESTION_TOOL_NAME:()=>ss,AgentWidgetClient:()=>vr,AgentWidgetSession:()=>ca,AttachmentManager:()=>Ar,BrowserSpeechEngine:()=>_o,DEFAULT_COMPONENTS:()=>hu,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>ol,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>mn,DEFAULT_PALETTE:()=>mu,DEFAULT_SEMANTIC:()=>gu,DEFAULT_WIDGET_CONFIG:()=>rt,PRESETS:()=>wf,PRESET_FULLSCREEN:()=>Cf,PRESET_MINIMAL:()=>vf,PRESET_SHOP:()=>xf,ReadAloudController:()=>wr,SUGGEST_REPLIES_CLIENT_TOOL:()=>Ti,SUGGEST_REPLIES_PARAMETERS_SCHEMA:()=>od,SUGGEST_REPLIES_TOOL_NAME:()=>On,THEME_ZONES:()=>Mh,VERSION:()=>xr,WEBMCP_TOOL_PREFIX:()=>Dn,WebMcpBridge:()=>na,accessibilityPlugin:()=>Pb,animationsPlugin:()=>Rb,applyFeaturePreferences:()=>of,applyThemeVariables:()=>Sr,attachHeaderToContainer:()=>kr,brandPlugin:()=>Ib,buildComposer:()=>Lr,buildDefaultHeader:()=>Du,buildHeader:()=>fo,buildHeaderWithLayout:()=>ya,buildMinimalHeader:()=>Fu,builtInClientToolsForDispatch:()=>sa,canonicalArtifactDisplayMode:()=>sn,collectEnrichedPageContext:()=>kb,componentRegistry:()=>Nn,createActionManager:()=>Fs,createAgentExperience:()=>Jl,createAskUserQuestionBubble:()=>Ug,createBestAvailableVoiceProvider:()=>Ui,createBubbleWithLayout:()=>py,createCSATFeedback:()=>Gl,createComboButton:()=>ul,createComponentMiddleware:()=>rb,createComponentStreamParser:()=>zl,createDefaultSanitizer:()=>jc,createDirectivePostprocessor:()=>pg,createDropdownMenu:()=>$o,createFlexibleJsonStreamParser:()=>$g,createIconButton:()=>Tt,createImagePart:()=>Yg,createJsonStreamParser:()=>Hi,createLabelButton:()=>po,createLocalStorageAdapter:()=>Vl,createMarkdownProcessor:()=>ns,createMarkdownProcessorFromConfig:()=>hr,createMessageActions:()=>qu,createNPSFeedback:()=>Kl,createPlainTextParser:()=>Ii,createPlugin:()=>Bb,createRegexJsonParser:()=>Wi,createSlashCommandsSource:()=>yb,createStandardBubble:()=>ba,createStaticMentionSource:()=>hb,createTextPart:()=>Oo,createTheme:()=>hs,createThemeObserver:()=>pa,createToggleGroup:()=>ma,createTypingIndicator:()=>Pr,createVoiceProvider:()=>No,createWidgetHostLayout:()=>Ns,createXmlParser:()=>Bi,defaultActionHandlers:()=>Dr,defaultJsonActionParser:()=>Ds,defaultMentionFilter:()=>Yl,defaultParseRules:()=>yf,detectColorScheme:()=>ys,directivePostprocessor:()=>ug,ensureAskUserQuestionSheet:()=>aa,escapeHtml:()=>Vn,extractComponentDirectiveFromMessage:()=>jl,fileToImagePart:()=>Zg,formatEnrichedContext:()=>Lb,generateAssistantMessageId:()=>Fo,generateMessageId:()=>Kg,generateStableSelector:()=>bf,generateUserMessageId:()=>ia,getActiveTheme:()=>Uo,getColorScheme:()=>ll,getDisplayText:()=>Jg,getHeaderLayout:()=>Ou,getImageParts:()=>Qg,getPreset:()=>Fb,hasComponentDirective:()=>Os,hasImages:()=>Oi,headerLayouts:()=>Tl,highContrastPlugin:()=>Hb,initAgentWidget:()=>mb,isAskUserQuestionMessage:()=>so,isComponentDirectiveType:()=>ob,isDockedMountMode:()=>St,isSuggestRepliesMessage:()=>br,isVoiceSupported:()=>us,isWebMcpToolName:()=>Lo,isWelcomeVisible:()=>Xo,latestAgentSuggestions:()=>Ei,listRegisteredStreamAnimations:()=>Lu,loadMarkdownParsers:()=>ts,markdownPostprocessor:()=>$c,mergeWithDefaults:()=>da,normalizeContent:()=>Xg,normalizeMediaType:()=>Po,onMarkdownParsersReady:()=>ea,parseAskUserQuestionPayload:()=>io,parseSuggestRepliesPayload:()=>ad,parseWidgetPreferenceSlice:()=>nf,pickBestVoice:()=>la,pluginRegistry:()=>Bs,reducedMotionPlugin:()=>Wb,registerStreamAnimationPlugin:()=>Er,removeAskUserQuestionSheet:()=>Wo,renderComponentDirective:()=>$l,renderLoadingIndicatorWithFallback:()=>Uu,renderLucideIcon:()=>ae,resolveArtifactDisplay:()=>Jc,resolveArtifactDisplayMode:()=>zn,resolveConfigPreferences:()=>Hs,resolveDockConfig:()=>ln,resolveSanitizer:()=>ta,resolveTokens:()=>sl,resolveWelcomeConfig:()=>mo,stripWebMcpPrefix:()=>xi,themeToCssVariables:()=>il,unregisterStreamAnimationPlugin:()=>ku,validateImageFile:()=>eh,validateTheme:()=>yu});var Zr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,a=null;return{setLoader:c=>{o=c,n&&(r=null,a=null)},load:()=>r?Promise.resolve(r):a||(a=(o??t)().then(f=>(r=f,f)).catch(f=>{throw a=null,f}),a),provide:c=>{r=c},getSync:()=>r}};var{setLoader:ov,load:rv,provide:M0,getSync:zc}=Zr({fallbackImport:()=>import("./markdown-parsers-entry")}),yi=new Set,av=()=>{let e=[...yi];yi.clear();for(let t of e)try{t()}catch{}},ig=ov,ts=()=>{let e=zc();return e?Promise.resolve(e):rv().then(t=>(av(),t))},ea=e=>zc()?()=>{}:(yi.add(e),ts().catch(()=>{}),()=>{yi.delete(e)});var ao=zc;var sv=e=>{if(e)return e},ns=e=>{let t=null;return n=>{let o=ao();if(!o)return Vn(n);if(!t){let{Marked:r}=o,a=e?.markedOptions;t=new r({gfm:a?.gfm??!0,breaks:a?.breaks??!0,pedantic:a?.pedantic,silent:a?.silent});let s=sv(e?.renderer);s&&t.use({renderer:s})}return t.parse(n)}},hr=e=>e?ns({markedOptions:e.options,renderer:e.renderer}):ns(),iv=ns(),$c=e=>iv(e),Vn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cg=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),lg=e=>`%%FORM_PLACEHOLDER_${e}%%`,dg=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let a=JSON.parse(r.trim());if(a&&typeof a=="object"&&a.component==="form"&&a.type){let s=lg(t.length);return t.push({token:s,type:String(a.type)}),s}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let a=lg(t.length);return t.push({token:a,type:r}),a}),n},pg=e=>{let t=hr(e);return n=>{let o=[],r=dg(n,o),a=t(r);return o.forEach(({token:s,type:l})=>{let p=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${cg(l)}"></div>`;a=a.replace(p,c)}),a}},ug=e=>{let t=[],n=dg(e,t),o=$c(n);return t.forEach(({token:r,type:a})=>{let s=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cg(a)}"></div>`;o=o.replace(s,p)}),o};var lv={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"]},cv=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,jc=()=>{let e=null;return t=>{let n=ao();if(!n)return Vn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,a)=>{if(a.attrName==="src"||a.attrName==="href"){let s=a.attrValue;s.toLowerCase().startsWith("data:")&&!cv.test(s)&&(a.attrValue="",a.keepAttr=!1)}})}return e.sanitize(t,lv)}},ta=e=>e===!1?null:typeof e=="function"?e:jc();var fg=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mg=e=>e.includes("|"),gg=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())},dv=e=>`| ${e.join(" | ")} |`,pv=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,uv=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),hg=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
3
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],a=t[o+1];if(!mg(r)||fg.test(r)||!fg.test(a))continue;let s=gg(r).length;if(s<1)continue;let l=pv(s);t[o+1]!==l&&(t[o+1]=l,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!mg(d))break;let c=dv(uv(gg(d),s));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
4
+ `):e};var yg="var(--persona-md-table-scroll-fade, 24px)",bg=new WeakSet;function vg(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 xg(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":yg),e.style.setProperty("--persona-fade-r",r<=1?"0px":yg)}function Gc(e){bg.has(e)||(bg.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&xg(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(xg)}var Dn="webmcp:",Kc=new Map,Cg=e=>{Kc.clear();for(let t of e){let n=t.title?.trim();n&&Kc.set(t.name,n)}},os=e=>Kc.get(xi(e)),bi={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Xc=null,Ag=e=>{Xc=e};function Sg(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}:${fv(t.join(""))}`}function wg(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let a=e.charCodeAt(r);n=Math.imul(n^a,2654435761),o=Math.imul(o^a,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 fv(e){let t=wg(e,0).toString(36),n=wg(e,2654435761).toString(36);return`${t}.${n}`}var na=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 bi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Cg(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let a={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},s=gv(r.inputSchema);return s&&(a.parametersSchema=s),a})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Bn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let b=typeof document<"u"&&!!document.modelContext;return Bn(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 a=xi(t),s;try{s=await r.getTools()}catch(b){let w=b instanceof Error?b.message:String(b);return Bn(`Failed to read WebMCP registry: ${w}`)}Cg(s);let l=s.find(b=>b.name===a);if(!l)return Bn(`WebMCP tool not registered on this page: ${a}`);if(!this.passesClientAllowlist(a))return Bn(`WebMCP tool not allowed by client allowlist: ${a}`);if(o?.aborted)return Bn("Aborted by cancel()");let p=os(a),d={toolName:a,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return Bn("User declined the tool call.");if(o?.aborted)return Bn("Aborted by cancel()");let c=new AbortController,f=!1,g=setTimeout(()=>{f=!0,c.abort()},this.timeoutMs),m=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",m,{once:!0}));try{let b=await r.executeTool(l,xv(n),{signal:c.signal});return hv(b)}catch(b){if(f)return Bn(`WebMCP tool '${a}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Bn("Aborted by cancel()");let w=b instanceof Error?b.message:String(b);return Bn(w)}finally{clearTimeout(g),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}(Xc?await Xc():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){bi.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,bi.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??yv;try{return await n(t)}catch(o){return bi.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=>mv(t,o))}},xi=e=>e.startsWith(Dn)?e.slice(Dn.length):e,Lo=e=>e.startsWith(Dn),mv=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},gv=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},hv=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:vv(t)}]}},Bn=e=>({isError:!0,content:[{type:"text",text:e}]}),yv=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=bv(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
5
5
 
6
6
  Arguments:
7
7
  ${t}`:"")+(e.description?`
8
8
 
9
- ${e.description}`:"");return window.confirm(n)},Pb=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)}},Rb=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ib=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function on(e){return e==="card"?"collapsed":e}function bo(e){return e.split(";",1)[0].trim().toLowerCase()}function Wb(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(bo(r)===t)return{mode:on(a),selector:bo(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(bo(r)===o)return{mode:on(a),selector:o}}function sd(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 l=t.file.mimeType?bo(t.file.mimeType):void 0,p=l?Wb(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,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 a=o.byType?.[t.artifactType];if(a)return{mode:on(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:on(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:on(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function Bn(e,t){return sd(e,t).mode}function Ra(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 Hb="agent_",Bb="flow_";function am(e){return e.startsWith(Hb)?{kind:"agentId",agentId:e}:e.startsWith(Bb)?{kind:"flowId",flowId:e}:null}function sm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let c=am(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=am(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(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 xo=ho(Ys(),1);var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var lm=()=>document.createDocumentFragment(),Be=(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[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},Kn=(...e)=>e.filter(Boolean).join(" ");var Wa="ask_user_question",Ia=8,Rr="data-persona-ask-sheet-for",_b="Other",Ub="Other\u2026",cm="Type your own answer here",pm="Send",qb="Next",Vb="Back",zb="Submit all",$b="Skip",jb=3,ld="data-ask-current-index",dd="data-ask-question-count",um="data-ask-answers",cd="data-ask-grouped",fm="data-ask-layout",Gb=e=>e.layout==="pills"?"pills":"rows",Kb=e=>e.getAttribute(fm)==="pills"?"pills":"rows",dm=!1,mm=e=>e.replace(/["\\]/g,"\\$&"),Xn=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Wa,Zs=e=>e?.features?.askUserQuestion??{},Jn=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(""),a=(0,xo.parse)(r,xo.STR|xo.OBJ|xo.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},Ha=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>Ia&&!dm&&(dm=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Ia}.`)),t.slice(0,Ia)},Xb=e=>Ha(e)[0]??null,Jb=(e,t)=>Ha(e)[t]??null,gm=(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))},hm=(e,t,n)=>{if(e!=="rows")return null;let o=b("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=b("span","persona-ask-row-check");o.appendChild(r)}else{let r=b("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Qb=(e,t,n,o)=>{let a=b("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),n==="rows"){let s=b("span","persona-ask-row-content"),l=b("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let c=b("span","persona-ask-row-description");c.textContent=e.description,s.appendChild(c)}a.appendChild(s);let p=hm(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Yb=e=>{let n=b("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},Zb=(e,t,n,o)=>{let a=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<jb;d++)a.appendChild(Yb(o));return a}if(p.forEach((d,u)=>{a.appendChild(Qb(d,u,o,s))}),e?.allowFreeText!==!1){let d=o==="rows"?_b:Ub;if(o==="rows"){let u=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let g=b("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??cm,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",t.freeTextLabel??d),g.appendChild(f),u.appendChild(g);let h=hm(o,s,p.length);h&&u.appendChild(h),a.appendChild(u)}else{let u=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=t.freeTextLabel??d,a.appendChild(u)}}return a},ym=(e,t)=>{let o=b("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??cm,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=b("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??pm,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},ex=e=>{let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??pm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},tx=(e,t,n)=>{let o=b("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=b("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Vb,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=b("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??$b,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=b("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??zb:n.nextLabel??qb,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},Yo=e=>{let t=e.getAttribute(um);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},bm=(e,t)=>{e.setAttribute(um,JSON.stringify(t))},xn=e=>{let t=Number(e.getAttribute(ld)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},nx=(e,t)=>{e.setAttribute(ld,String(Math.max(0,Math.floor(t))))},Ir=e=>{let t=Number(e.getAttribute(dd)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(cd)==="true",ox=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},rx=(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)))},ei=(e,t)=>{let{payload:n}=Jn(t),o=Ha(n),r=Yo(e),a={},s=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(s.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),s.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(a[c]=r[p]))}),a},xm=e=>{let t=Yo(e),n=xn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},vm=e=>{if(!vo(e))return;let t=Yo(e),n=xn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},pd=(e,t,n)=>{let o=Zs(n),r=Kb(e),{payload:a,complete:s}=Jn(t),l=vo(e),p=xn(e),c=Ir(e),d=l?Jb(a,p):Xb(a),u=!!d?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${c}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let M=typeof d?.question=="string"?d.question:"";h.textContent=M,h.classList.toggle("persona-ask-question-skeleton",!M&&!s)}let A=e.querySelector('[data-ask-pill-list="true"]');if(A){let M=Zb(d,o,s,r);A.replaceWith(M)}if(r!=="rows"){let M=e.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(ym(o,r))}let E=e.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!E?e.appendChild(ex(o)):(!u||l)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let k=e.querySelector('[data-ask-nav-row="true"]');if(l){let M=tx(p,c,o);k?k.replaceWith(M):e.appendChild(M)}else k&&k.remove();xm(e),vm(e)},ax=(e,t,n)=>{let o=Zs(t),r=Gb(o),a=e.toolCall.id,s=Ha(n),l=Math.max(1,s.length),p=l>1,c=ox(e,s),d=p?rx(e,l):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Rr,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(dd,String(l)),u.setAttribute(ld,String(d)),u.setAttribute(cd,p?"true":"false"),u.setAttribute(fm,r),bm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),gm(u,o);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=b("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=b("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let E=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),r!=="rows"&&u.appendChild(ym(o,r)),pd(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sx=(e,t,n)=>{let{payload:o}=Jn(t),r=Math.max(1,Ha(o).length);r>Ir(e)&&(e.setAttribute(dd,String(r)),r>1&&!vo(e)&&e.setAttribute(cd,"true")),pd(e,t,n)},Cm=(e,t)=>{let n=b("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=Zs(t);gm(n,o);let r=b("span","persona-ask-stub-label"),{complete:a}=Jn(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},Wr=(e,t,n)=>{if(!n||!Xn(e)||Zs(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${Rr}]`).forEach(c=>{c.getAttribute(Rr)!==r&&c.remove()});let s=n.querySelector(`[${Rr}="${mm(r)}"]`);if(s){sx(s,e,t);return}let{payload:l}=Jn(e),p=ax(e,t,l);n.appendChild(p)},Co=(e,t)=>{if(!e)return;let n=t?`[${Rr}="${mm(t)}"]`:`[${Rr}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},ud=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=Yo(e),o=xn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,bm(e,n),xm(e),vm(e)},ti=(e,t,n,o)=>{let r=Ir(e),a=Math.max(0,Math.min(r-1,o));nx(e,a),pd(e,t,n)};var kn="suggest_replies";var fd={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ni={name:kn,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:fd,origin:"sdk",annotations:{readOnlyHint:!0}},md=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ba=e=>e.variant==="tool"&&e.toolCall?.name===kn,gd=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.suggestions;if(!Array.isArray(n))return[];let o=n.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},oi=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!Ba(n))continue;let o=gd(n.toolCall?.args);return o.length>0?o:null}return null},wm=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var hd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ia,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},yd={name:Wa,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:hd,origin:"sdk",annotations:{readOnlyHint:!0}},Hr=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(yd),wm(e)&&t.push(ni),t};var Qn=ho(Ys(),1),ri=e=>e.replace(/\\n/g,`
10
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ao=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)}},ix=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`},Am=e=>e.status==="complete"?ix(e):e.status==="pending"?"Waiting":"",lx=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 Sm=e=>e.status==="complete"?lx(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Fa=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 ai(t)},si=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return ai(t)},bd=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=Fa(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ii=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&Da(o,n.slice(a,s.index),[]),s[1]!==void 0?Da(o,s[1],["bold"]):s[2]!==void 0?Da(o,s[2],["italic"]):s[3]!==void 0&&Da(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&Da(o,n.slice(a),[]),o},Da=(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})},dx=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
9
+ ${e.description}`:"");return window.confirm(n)},bv=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)}},xv=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},vv=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function sn(e){return e==="card"?"collapsed":e}function Po(e){return e.split(";",1)[0].trim().toLowerCase()}function Cv(e,t){if(!e)return;let n=Object.entries(e);for(let[r,a]of n)if(Po(r)===t)return{mode:sn(a),selector:Po(r)};let o=`${t.split("/",1)[0]}/*`;for(let[r,a]of n)if(Po(r)===o)return{mode:sn(a),selector:o}}function Jc(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:sn(o.files),matchedBy:{type:"files"}};let l=t.file.mimeType?Po(t.file.mimeType):void 0,p=l?Cv(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:sn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[t.artifactType];if(r)return{mode:sn(r),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let a=o.byType?.[t.artifactType];if(a)return{mode:sn(a),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let s=t.presentation?.preferredMode;return s?{mode:sn(s),matchedBy:{type:"preferredMode"}}:o.default?{mode:sn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function zn(e,t){return Jc(e,t).mode}function rs(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 wv="agent_",Av="flow_";function Mg(e){return e.startsWith(wv)?{kind:"agentId",agentId:e}:e.startsWith(Av)?{kind:"flowId",flowId:e}:null}function Tg(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let s=n.slice(0,o),l=n.slice(o+1);if(s==="runtype"){let d=Mg(l);if(d)return d;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[s];if(!p)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Mg(n);if(r)return r;let a=t?.default;if(a)return{kind:"payload",payload:a(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 Ro=ko(wi(),1);var v=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var kg=()=>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[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let l of Object.keys(s)){let p=s[l];p!=null&&(a[l]=p)}}let r=n.filter(a=>a!=null);return r.length>0&&o.append(...r),o},Fn=(...e)=>e.filter(Boolean).join(" ");var ss="ask_user_question",as=8,oa="data-persona-ask-sheet-for",kv="Other",Lv="Other\u2026",Pg="Type your own answer here",Rg="Send",Pv="Next",Rv="Back",Iv="Submit all",Wv="Skip",Hv=3,Yc="data-ask-current-index",Zc="data-ask-question-count",Ig="data-ask-answers",ed="data-ask-grouped",Wg="data-ask-layout",Bv=e=>e.layout==="pills"?"pills":"rows",Dv=e=>e.getAttribute(Wg)==="pills"?"pills":"rows",Lg=!1,Hg=e=>e.replace(/["\\]/g,"\\$&"),so=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ss,Ai=e=>e?.features?.askUserQuestion??{},io=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(""),a=(0,Ro.parse)(r,Ro.STR|Ro.OBJ|Ro.ARR);if(a&&typeof a=="object")return{payload:a,complete:n}}catch{}return{payload:null,complete:n}},is=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>as&&!Lg&&(Lg=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${as}.`)),t.slice(0,as)},Fv=e=>is(e)[0]??null,Ov=(e,t)=>is(e)[t]??null,Bg=(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))},Dg=(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},Nv=(e,t,n,o)=>{let a=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),n==="rows"){let s=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=e.label,s.appendChild(l),e.description){let d=v("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let p=Dg(n,o,t);p&&a.appendChild(p)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},_v=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},Uv=(e,t,n,o)=>{let a=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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!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<Hv;c++)a.appendChild(_v(o));return a}if(p.forEach((c,f)=>{a.appendChild(Nv(c,f,o,s))}),e?.allowFreeText!==!1){let c=o==="rows"?kv:Lv;if(o==="rows"){let f=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");f.setAttribute("data-ask-user-action","focus-free-text"),f.setAttribute("data-option-index",String(p.length)),f.setAttribute("data-ask-other-row","true");let g=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??Pg,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",t.freeTextLabel??c),g.appendChild(m),f.appendChild(g);let b=Dg(o,s,p.length);b&&f.appendChild(b),a.appendChild(f)}else{let f=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");f.type="button",f.setAttribute("data-ask-user-action","open-free-text"),f.textContent=t.freeTextLabel??c,a.appendChild(f)}}return a},Fg=(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??Pg,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let a=v("button","persona-ask-free-text-submit persona-pointer-events-auto");a.type="button",a.textContent=e.submitLabel??Rg,a.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(a)}return o},qv=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??Rg,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vv=(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??Rv,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let a=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=v("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=n.skipLabel??Wv,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=e===t-1;return l.textContent=p?n.submitAllLabel??Iv:n.nextLabel??Pv,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,a.appendChild(l),o.appendChild(a),o},yr=e=>{let t=e.getAttribute(Ig);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Og=(e,t)=>{e.setAttribute(Ig,JSON.stringify(t))},Sn=e=>{let t=Number(e.getAttribute(Yc)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},zv=(e,t)=>{e.setAttribute(Yc,String(Math.max(0,Math.floor(t))))},ra=e=>{let t=Number(e.getAttribute(Zc)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Io=e=>e.getAttribute(ed)==="true",$v=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,a)=>{let s=typeof r?.question=="string"?r.question:"";if(s&&Object.prototype.hasOwnProperty.call(n,s)){let l=n[s];(typeof l=="string"||Array.isArray(l))&&(o[a]=l)}}),o},jv=(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)))},Si=(e,t)=>{let{payload:n}=io(t),o=is(n),r=yr(e),a={},s=new Set;return o.forEach((l,p)=>{let d=typeof l?.question=="string"?l.question:"";d&&(s.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(a[d]=r[p]))}),a},Ng=e=>{let t=yr(e),n=Sn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.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 s=new Set(Array.from(a).map(p=>p.getAttribute("data-option-label")??"")),l=e.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!s.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},_g=e=>{if(!Io(e))return;let t=yr(e),n=Sn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!r);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let l=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=l.length===0}},td=(e,t,n)=>{let o=Ai(n),r=Dv(e),{payload:a,complete:s}=io(t),l=Io(e),p=Sn(e),d=ra(e),c=l?Ov(a,p):Fv(a),f=!!c?.multiSelect,g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=l?`${p+1}/${d}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let A=typeof c?.question=="string"?c.question:"";b.textContent=A,b.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let w=e.querySelector('[data-ask-pill-list="true"]');if(w){let A=Uv(c,o,s,r);w.replaceWith(A)}if(r!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Fg(o,r))}let T=e.querySelector('[data-ask-multi-actions="true"]');!l&&f&&!T?e.appendChild(qv(o)):(!f||l)&&T&&T.remove(),e.setAttribute("data-multi-select",f?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(l){let A=Vv(p,d,o);L?L.replaceWith(A):e.appendChild(A)}else L&&L.remove();Ng(e),_g(e)},Gv=(e,t,n)=>{let o=Ai(t),r=Bv(o),a=e.toolCall.id,s=is(n),l=Math.max(1,s.length),p=l>1,d=$v(e,s),c=p?jv(e,l):0,f=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(oa,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Zc,String(l)),f.setAttribute(Yc,String(c)),f.setAttribute(ed,p?"true":"false"),f.setAttribute(Wg,r),Og(f,d),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Bg(f,o);let g=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="",g.appendChild(m);let b=v("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",g.appendChild(b),f.appendChild(g);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"),f.appendChild(T),r!=="rows"&&f.appendChild(Fg(o,r)),td(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},Kv=(e,t,n)=>{let{payload:o}=io(t),r=Math.max(1,is(o).length);r>ra(e)&&(e.setAttribute(Zc,String(r)),r>1&&!Io(e)&&e.setAttribute(ed,"true")),td(e,t,n)},Ug=(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=Ai(t);Bg(n,o);let r=v("span","persona-ask-stub-label"),{complete:a}=io(e);return r.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},aa=(e,t,n)=>{if(!n||!so(e)||Ai(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${oa}]`).forEach(d=>{d.getAttribute(oa)!==r&&d.remove()});let s=n.querySelector(`[${oa}="${Hg(r)}"]`);if(s){Kv(s,e,t);return}let{payload:l}=io(e),p=Gv(e,t,l);n.appendChild(p)},Wo=(e,t)=>{if(!e)return;let n=t?`[${oa}="${Hg(t)}"]`:`[${oa}]`;e.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(a)?a:180)})},nd=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),Ho=(e,t)=>{let n=yr(e),o=Sn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,Og(e,n),Ng(e),_g(e)},Mi=(e,t,n,o)=>{let r=ra(e),a=Math.max(0,Math.min(r-1,o));zv(e,a),td(e,t,n)};var On="suggest_replies";var od={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},Ti={name:On,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:od,origin:"sdk",annotations:{readOnlyHint:!0}},rd=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),br=e=>e.variant==="tool"&&e.toolCall?.name===On,ad=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 a=r;if(typeof a.label!="string"||!a.label.trim())return[];let s={label:a.label.trim()};return typeof a.prompt=="string"&&a.prompt.trim()&&(s.prompt=a.prompt.trim()),typeof a.description=="string"&&a.description.trim()&&(s.description=a.description.trim()),[s]});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},Ei=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=ad(n.toolCall?.args);return o.length>0?o:null}return null},qg=new Set,Xv=(e,t,n)=>{let o=`${e}:${t}:${n}`;qg.has(o)||(qg.add(o),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},Bo=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,o=s=>{let l=t?.[s],p=n?.[s];l===void 0||p===void 0||l!==p&&Xv(s,p,l)};e&&(o("enabled"),o("expose"));let r=t?.enabled??n?.enabled??!0,a=r?t?.expose??n?.expose??!1:!1;return{enabled:r,expose:a}};var sd={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:as,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},id={name:ss,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:sd,origin:"sdk",annotations:{readOnlyHint:!0}},sa=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(id),Bo(e).expose&&t.push(Ti),t};var lo=ko(wi(),1),ki=e=>e.replace(/\\n/g,`
10
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Do=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)}},Jv=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`},Vg=e=>e.status==="complete"?Jv(e):e.status==="pending"?"Waiting":"",Qv=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 zg=e=>e.status==="complete"?Qv(e):"Using tool...",Li=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},cs=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 Li(t)},Pi=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return Li(t)},ld=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=cs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},Ri=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=r.exec(n))!==null;)s.index>a&&ls(o,n.slice(a,s.index),[]),s[1]!==void 0?ls(o,s[1],["bold"]):s[2]!==void 0?ls(o,s[2],["italic"]):s[3]!==void 0&&ls(o,s[3],["dim"]),a=s.index+s[0].length;return a<n.length&&ls(o,n.slice(a),[]),o},ls=(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})},Yv=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(r);if(a&&a[1])try{return a[1].replace(/\\n/g,`
11
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(s);if(l&&l[1])try{return l[1].replace(/\\n/g,`
12
- `).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 a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{let e=dx();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)}},ci=()=>{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,Qn.parse)(n,Qn.STR|Qn.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ri(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ri(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Mm=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ri(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ri(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,Qn.parse)(a,Qn.STR|Qn.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},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 Tm="4.14.0";var Zo=Tm;var px="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function ux(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 a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var xd=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 fx(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Em=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function mx(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=Em(n);if(!Em(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=Oa(e);return Oa(t)!==null&&s===null?t:e}var er=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??px,this.headers={"Content-Type":"application/json","X-Persona-Version":Zo,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??fx(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 Pr(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 a=sm(o,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ui}/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}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,"")||ui}/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}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(r)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.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 c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(t.messages),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(xd).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...s,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Zo},body:JSON.stringify(d),signal:t.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.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 s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.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 s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.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$/,"")||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?rm(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,c=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,d=!1,u;for(let g=0;;g++){if(u=await o({...a&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),u.status===409&&g===0&&a&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ui}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let c=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(s,c,g=>{let f={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(a,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),d}return fetch(a,{method:"POST",headers:l,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 a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));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(xd).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).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}},a=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(xd).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).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,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...Hr(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=d=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...d!==void 0&&{partId:d}};return o.current=u,r(u),u},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.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 a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,u=P=>{let U=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,x=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,H=P.tools?P.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...P,reasoning:U,toolCall:x,tools:H}},g=P=>{if(P.role!=="assistant"||P.variant)return!0;let U=Array.isArray(P.contentParts)&&P.contentParts.length>0,x=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||U||x||!!P.stopReason},f=P=>{g(P)&&n({type:"message",message:u(P)})},h=null,A=null,E={current:null},k={current:null},M=null,S="",C=new Map,T=new Map,W=new Map,w=new Map,D=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},O=P=>{if(P==null)return null;try{return String(P)}catch{return null}},q=P=>O(P.stepId??P.step_id??P.step??P.parentId??P.flowStepId??P.flow_step_id),Q=P=>O(P.callId??P.call_id??P.requestId??P.request_id??P.toolCallId??P.tool_call_id??P.stepId??P.step_id),de=o,be=!1,De=()=>{if(h)return h;let P,U="",x=M;return!be&&de?(P=de,be=!0,U=r??""):de&&x?P=`${de}_${x}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:P,role:"assistant",content:U,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(h),h},ie=(P,U)=>{F.lastId=U,P&&F.byStep.set(P,U)},ge=(P,U)=>{let x=P.reasoningId??P.id,H=q(P);if(x){let B=String(x);return ie(H,B),B}if(H){let B=F.byStep.get(H);if(B)return F.lastId=B,B}if(F.lastId&&!U)return F.lastId;if(!U)return null;let R=`reason-${d()}`;return ie(H,R),R},ne=P=>{let U=w.get(P);if(U)return U;let x={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:P,status:"streaming",chunks:[]}};return w.set(P,x),f(x),x},le=(P,U)=>{j.lastId=U,P&&j.byCall.set(P,U)},Z=new Set,me=new Map,Ae=new Set,we=new Map,Se=P=>{if(!P)return!1;let U=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return U==="emit_artifact_markdown"||U==="emit_artifact_component"},mt=(P,U)=>{let x=P.toolId??P.id,H=Q(P);if(x){let B=String(x);return le(H,B),B}if(H){let B=j.byCall.get(H);if(B)return j.lastId=B,B}if(j.lastId&&!U)return j.lastId;if(!U)return null;let R=`tool-${d()}`;return le(H,R),R},We=P=>{let U=D.get(P);if(U)return U;let x={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:P,status:"pending"}};return D.set(P,x),f(x),x},_e=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let U=Number(P);if(!Number.isNaN(U)&&Number.isFinite(U))return U;let x=Date.parse(P);if(!Number.isNaN(x))return x}return Date.now()},Xe=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},$e=new Map,Me=new Map,ke=new Map,Je=(P,U,x)=>{let H=ke.get(P);H||(H=[],ke.set(P,H));let R=0,B=H.length;for(;R<B;){let _=R+B>>>1;H[_].seq<U?R=_+1:B=_}H[R]?.seq===U?H[R]={seq:U,text:x}:H.splice(R,0,{seq:U,text:x});let K="";for(let _=0;_<H.length;_++)K+=H[_].text;return K},Dt=(P,U)=>{let x=Xe(U),H=Me.get(P.id),R=mx(H,x);P.rawContent=R;let B=$e.get(P.id),K=Re=>{let Qe=P.content??"";Re.trim()!==""&&(Qe.trim().length===0||Re.startsWith(Qe)||Re.trimStart().startsWith(Qe.trim()))&&(P.content=Re)},_=()=>{if(B){let Re=B.close?.();Re instanceof Promise&&Re.catch(()=>{})}$e.delete(P.id),Me.delete(P.id),P.streaming=!1,f(P)};if(!B){K(x),_();return}let $=Oa(R);if($!==null&&$.trim()!==""){K($),_();return}let Y=Re=>{let Qe=typeof Re=="string"?Re:Re?.text??null;if(Qe!==null&&Qe.trim()!=="")return Qe;let rt=B.getExtractedText();return rt!==null&&rt.trim()!==""?rt:x},je;try{je=B.processChunk(R)}catch{K(x),_();return}if(je instanceof Promise){je.then(Re=>{K(Y(Re)),_()}).catch(()=>{K(x),_()});return}K(Y(je)),_()},Wt=null,Kt=(P,U,x,H)=>{P.rawContent=U,$e.has(P.id)||$e.set(P.id,this.createStreamParser());let R=$e.get(P.id),B=U.trim().startsWith("{")||U.trim().startsWith("[");if(B&&Me.set(P.id,U),R.__isPlainTextParser===!0){P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P);return}let _=R.processChunk(U);if(_ instanceof Promise)_.then($=>{let Y=typeof $=="string"?$:$?.text??null;Y!==null&&Y.trim()!==""?(P.content=Y,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}).catch(()=>{P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P)});else{let $=typeof _=="string"?_:_?.text??null;$!==null&&$.trim()!==""?(P.content=$,f(P)):!B&&!U.trim().startsWith("<")&&(P.content=H!==void 0?U:P.content+x,Me.delete(P.id),$e.delete(P.id),P.rawContent=void 0,f(P))}},wt=(P,U)=>{let x=U??P.content;if(x==null||x===""){P.streaming=!1,f(P);return}let R=Me.get(P.id)??Xe(x);P.rawContent=R;let B=$e.get(P.id),K=null,_=!1;if(B&&(K=B.getExtractedText(),K===null&&(K=Oa(R)),K===null)){let $=B.processChunk(R);$ instanceof Promise?(_=!0,$.then(Y=>{let je=typeof Y=="string"?Y:Y?.text??null;je!==null&&(P.content=je,P.streaming=!1,$e.delete(P.id),Me.delete(P.id),f(P))}).catch(()=>{})):K=typeof $=="string"?$:$?.text??null}if(!_){K!==null&&K.trim()!==""?P.content=K:Me.has(P.id)||(P.content=Xe(x));let $=$e.get(P.id);if($){let Y=$.close?.();Y instanceof Promise&&Y.catch(()=>{}),$e.delete(P.id)}Me.delete(P.id),P.streaming=!1,f(P)}},He=(P,U,x)=>{let H=T.get(P);if(H)return H;let R={id:`nested-${U}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:U}};return T.set(P,R),f(R),R},ce=[],et,Pe=new Map,ue=0,ae="agent",Le=!1,it=null,pe=null,ve=new Map,ee=this.config.iterationDisplay??"separate";for(et=()=>{for(let P=0;P<ce.length;P++){let U=ce[P].payloadType,x=ce[P].payload;if(!Le&&ae!=="flow"&&typeof x.stepType=="string"&&(ae="flow"),U==="reasoning_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R),He(H,R,"reasoning");continue}let B=ge(x,!0)??`reason-${d()}`,K=ne(B);K.reasoning=K.reasoning??{id:B,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??_e(x.startedAt??x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",f(K)}else if(U==="reasoning_delta"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let _=T.get(H),$=x.reasoningText??x.text??x.delta??"";$&&x.hidden!==!0&&_.reasoning&&(_.reasoning.chunks.push(String($)),f(_));continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=ne(R);B.reasoning=B.reasoning??{id:R,status:"streaming",chunks:[]},B.reasoning.startedAt=B.reasoning.startedAt??_e(x.startedAt??x.timestamp);let K=x.reasoningText??x.text??x.delta??"";if(K&&x.hidden!==!0){let _=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(_!==void 0){let $=Je(R,_,String(K));B.reasoning.chunks=[$]}else B.reasoning.chunks.push(String(K))}if(B.reasoning.status=x.done?"complete":"streaming",x.done){B.reasoning.completedAt=_e(x.completedAt??x.timestamp);let _=B.reasoning.startedAt??Date.now();B.reasoning.durationMs=Math.max(0,(B.reasoning.completedAt??Date.now())-_)}B.streaming=B.reasoning.status!=="complete",f(B)}else if(U==="reasoning_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)&&T.has(H)){let $=T.get(H);if($.reasoning){let Y=typeof x.text=="string"?x.text:"";Y&&$.reasoning.chunks.length===0&&$.reasoning.chunks.push(Y),$.reasoning.status="complete",$.streaming=!1,f($)}C.delete(H),T.delete(H);continue}let R=ge(x,!1)??ge(x,!0)??`reason-${d()}`,B=typeof x.text=="string"?x.text:"";!w.get(R)&&(B||x.scope==="loop")&&ne(R);let K=w.get(R);if(K?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),B&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(B),K.reasoning.status="complete",K.reasoning.completedAt=_e(x.completedAt??x.timestamp);let $=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-$),K.streaming=!1,f(K)}let _=q(x);_&&F.byStep.delete(_)}else if(U==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof x.iteration=="number"&&(ue=x.iteration);let H=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??mt(x,!0)??`tool-${d()}`,R=x.toolName??x.name;if(Se(R)){Z.add(H);continue}le(Q(x),H);let B=We(H),K=B.toolCall??{id:H,status:"pending"};K.name=R??K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=K.startedAt??_e(x.startedAt??x.timestamp),K.completedAt=void 0,K.durationMs=void 0,B.toolCall=K,B.streaming=!0,x.executionId&&(B.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(B)}else if(U==="tool_output_delta"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H))continue;let R=We(H),B=R.toolCall??{id:H,status:"running"};B.startedAt=B.startedAt??_e(x.startedAt??x.timestamp);let K=x.text??x.delta??x.message??"";K&&(B.chunks=B.chunks??[],B.chunks.push(String(K))),B.status="running",R.toolCall=B,R.streaming=!0;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R)}else if(U==="tool_complete"){let H=mt(x,!1)??mt(x,!0)??`tool-${d()}`;if(Z.has(H)){Z.delete(H);continue}let R=We(H),B=R.toolCall??{id:H,status:"running"};B.status="complete",x.result!==void 0&&(B.result=x.result),typeof x.duration=="number"&&(B.duration=x.duration),B.completedAt=_e(x.completedAt??x.timestamp);let K=x.duration??x.executionTime;if(typeof K=="number")B.durationMs=K;else{let Y=B.startedAt??Date.now();B.durationMs=Math.max(0,(B.completedAt??Date.now())-Y)}R.toolCall=B,R.streaming=!1;let _=x.agentContext;(_||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:_?.executionId??x.executionId,iteration:_?.iteration??x.iteration}),f(R);let $=Q(x);$&&j.byCall.delete($)}else if(U==="await"&&x.toolName){let H=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,R=H??x.toolId??`local-${d()}`,B=We(R),K=x.toolName,_=x.origin==="webmcp"&&!yo(K)?`webmcp:${K}`:K,$=yo(_),Y=B.toolCall??{id:R,status:"pending"};Y.name=_,Y.args=x.parameters,Y.status=$?"running":"complete",Y.chunks=Y.chunks??[],Y.startedAt=Y.startedAt??_e(x.startedAt??x.timestamp??x.awaitedAt),$?(Y.completedAt=void 0,Y.duration=void 0,Y.durationMs=void 0):Y.completedAt=Y.completedAt??Y.startedAt,B.toolCall=Y,B.streaming=!1,B.agentMetadata={...B.agentMetadata,executionId:x.executionId??B.agentMetadata?.executionId,awaitingLocalTool:!0,...H?{webMcpToolCallId:H}:{}},f(B)}else if(U==="text_start"){let H=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(H&&R){C.set(H,R);continue}let B=h;B&&(ae==="flow"?(wt(B),Wt=B):(B.streaming=!1,f(B)),h=null),M=typeof x.id=="string"?x.id:M,S=""}else if(U==="text_delta"){let H=typeof x.id=="string"?x.id:null,R=H?C.get(H):void 0;if(H&&R){let K=typeof x.delta=="string"?x.delta:"",_=(W.get(H)??"")+K;if(W.set(H,_),_.trim()==="")continue;let $=He(H,R);$.agentMetadata={...$.agentMetadata,executionId:x.executionId,parentToolId:R},Kt($,_,K,void 0);continue}if(M=typeof x.id=="string"?x.id:M,ae==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(S+=K,S.trim()==="")continue;let _=De();_.agentMetadata={executionId:x.executionId,iteration:x.iteration},Kt(_,S,K,void 0),A=_;continue}let B=De();B.content+=x.delta??"",B.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:it??void 0,agentName:pe?.agentName},A=B,f(B)}else if(U==="text_complete"){let H=typeof x.id=="string"?x.id:null;if(H&&C.has(H)){let B=T.get(H);B&&wt(B),C.delete(H),W.delete(H),T.delete(H);continue}let R=h;R&&(ae==="flow"?(wt(R),Wt=R):((R.content??"")===""&&typeof x.text=="string"&&(R.content=x.text),R.streaming=!1,f(R)),h=null),M=null,S=""}else if(U==="step_complete"){let H=x.stepType,R=x.executionType;if(H==="tool"||R==="context")continue;if(x.success===!1){let B=x.error,K=typeof B=="string"&&B!==""?B:B!=null&&typeof B=="object"&&Reflect.has(B,"message")?String(B.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let _=h;_&&_.streaming&&(_.streaming=!1,f(_)),n({type:"status",status:"idle"});continue}{let B=Wt;Wt=null;let K=x.stopReason,_=x.result?.response;if(B)K&&(B.stopReason=K),_!=null?Dt(B,_):B.streaming!==!1&&($e.delete(B.id),Me.delete(B.id),B.streaming=!1,f(B));else{let $=_!=null&&_!=="";if($||K){let Y=De();K&&(Y.stopReason=K),$?wt(Y,_):(Y.streaming=!1,f(Y))}}continue}}else if(U==="execution_start")ae=x.kind==="flow"?"flow":"agent",Le=!0,ae==="agent"&&(pe={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:_e(x.startedAt)});else if(U==="turn_start"){let H=typeof x.iteration=="number"?x.iteration:ue;if(H!==ue){if(pe&&(pe.currentIteration=H),ee==="separate"&&H>1){let R=h;R&&(R.streaming=!1,f(R),ve.set(H-1,R),h=null)}ue=H}it=typeof x.id=="string"?x.id:null,A=null}else if(U==="tool_input_delta"){let H=x.toolCallId??j.lastId;if(H){let R=D.get(H);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(x.delta??""),f(R))}}else{if(U==="tool_input_complete")continue;if(U==="turn_complete"){let H=x.stopReason,R=h??A;if(H&&R!==null){let B=x.id;(!B||R.agentMetadata?.turnId===B)&&(R.stopReason=H,f(R))}it===x.id&&(it=null)}else if(U==="media_start"){let H=String(x.id);Pe.set(H,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(U==="media_delta"){let H=Pe.get(String(x.id));H&&typeof x.delta=="string"&&H.parts.push(x.delta)}else if(U==="media_complete"){let H=String(x.id),R=Pe.get(H);Pe.delete(H);let B=(typeof x.mediaType=="string"?x.mediaType:void 0)??R?.mediaType??"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,_=typeof x.url=="string"?x.url:R&&R.parts.length>0?R.parts.join(""):void 0,$=null;if(K)$={type:"media",data:K,mediaType:B};else if(_){let Qe=B.toLowerCase();$={type:Qe==="image"||Qe.startsWith("image/")?"image-url":"file-url",url:_,mediaType:B}}let Y=x.toolCallId??R?.toolCallId,je=$?[$]:[],Re=[];for(let Qe of je){if(!Qe||typeof Qe!="object")continue;let rt=Qe,G=typeof rt.type=="string"?rt.type:void 0,Ue=typeof rt.mediaType=="string"?rt.mediaType.toLowerCase():"",he=null,qe="";if(G==="media"){let Fe=typeof rt.data=="string"?rt.data:void 0;if(!Fe)continue;qe=Ue.length>0?Ue:"application/octet-stream",he=`data:${qe};base64,${Fe}`}else if(G==="image-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else if(G==="file-url"){let Fe=typeof rt.url=="string"?rt.url:void 0;if(!Fe)continue;qe=Ue,he=Fe}else continue;if(he)if(G==="image-url"||qe.startsWith("image/"))Re.push({type:"image",image:he,...qe.includes("/")?{mimeType:qe}:{}});else if(qe.startsWith("audio/"))Re.push({type:"audio",audio:he,mimeType:qe});else if(qe.startsWith("video/"))Re.push({type:"video",video:he,mimeType:qe});else{let Fe=qe||"application/octet-stream";Re.push({type:"file",data:he,mimeType:Fe,filename:ux(Fe)})}}if(Re.length>0){let Qe=d(),rt=Y,Ue={id:`agent-media-${typeof rt=="string"&&rt.length>0?`${rt}-${Qe}`:String(Qe)}`,role:"assistant",content:"",contentParts:Re,createdAt:new Date().toISOString(),streaming:!1,sequence:Qe,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ue}};f(Ue);let he=h;he&&(he.streaming=!1,f(he)),h=null,E.current=null}}else if(U==="execution_complete"){let H=x.kind??ae;H==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=_e(x.completedAt),pe.stopReason=x.stopReason);let R=h;R&&(H==="flow"&&R.streaming!==!1?wt(R):(R.streaming=!1,f(R)),h=null),M=null,S="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(U==="execution_error"){let H=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(H)})}else if(U!=="ping"){if(U==="approval_start"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="step_await"&&x.awaitReason==="approval_required"){let H=x.approvalId??`approval-${d()}`,R={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:"pending",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(U==="approval_complete"){let H=x.approvalId;if(H){let B={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:H,status:x.decision??"approved",agentId:pe?.agentId??"virtual",executionId:x.executionId??pe?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(B)}}else if(U==="artifact_start"||U==="artifact_delta"||U==="artifact_update"||U==="artifact_complete"){if(U==="artifact_start"){let H=x.artifactType,R=String(x.id),B=typeof x.title=="string"?x.title:void 0,K=x.file,_;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(_={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:R,artifactType:H,title:B,component:typeof x.component=="string"?x.component:void 0,..._?{file:_}:{}});let $=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(we.set(R,{markdown:"",title:B,file:_,...$?{props:$}:{}}),!Ae.has(R)){Ae.add(R);let Y=Bn(this.config.features?.artifacts,{artifactType:H,..._?{file:_}:{}}),je=typeof x.component=="string"?x.component:void 0,Re={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ra(Y,{artifactId:R,title:B,artifactType:H,status:"streaming",..._?{file:_}:{},...je?{component:je}:{}})};me.set(R,Re),f(Re)}}else if(U==="artifact_delta"){let H=String(x.id),R=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:H,artDelta:R});let B=we.get(H);B&&(B.markdown+=R)}else if(U==="artifact_update"){let H=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:H,component:typeof x.component=="string"?x.component:void 0});let R=we.get(String(x.id));R&&(R.props={...R.props??{},...H})}else if(U==="artifact_complete"){let H=String(x.id);n({type:"artifact_complete",id:H});let R=me.get(H);if(R){R.streaming=!1;try{let B=JSON.parse(R.rawContent??"{}");if(B.props){B.props.status="complete";let K=we.get(H);K?.markdown&&(B.props.markdown=K.markdown),K?.file&&(B.props.file=K.file),B.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(B.props.componentProps=K.props)}R.rawContent=JSON.stringify(B)}catch{}we.delete(H),f(R),me.delete(H)}}}else if(U==="transcript_insert"){let H=x.message;if(!H||typeof H!="object")continue;let R=String(H.id??`msg-${d()}`),B=H.role,_={id:R,role:B==="user"?"user":B==="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:d()};if(f(_),_.rawContent)try{let Y=JSON.parse(_.rawContent)?.props?.artifactId;typeof Y=="string"&&Ae.add(Y)}catch{}h=null,E.current=null,$e.delete(R),Me.delete(R)}else if(U==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let H=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(H)});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(U==="step_error"||U==="dispatch_error"||U==="flow_error"){let H=null;if(x.error instanceof Error)H=x.error;else if(U==="dispatch_error"){let R=x.message??x.error;R!=null&&R!==""&&(H=new Error(String(R)))}else{let R=x.error;typeof R=="string"&&R!==""?H=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(H=new Error(String(R.message??R)))}if(H){n({type:"error",error:H});let R=h;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ce.length=0};;){let{done:P,value:U}=await a.read();if(P)break;l+=s.decode(U,{stream:!0});let x=l.split(`
12
+ `).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 a=n(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ds=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Ii=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Wi=()=>{let e=Yv();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)}},Hi=()=>{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,lo.parse)(n,lo.STR|lo.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?ki(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=ki(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},$g=e=>{let t=null,n=0,r=e||(a=>{if(!a||typeof a!="object")return null;let s=l=>typeof l=="string"?ki(l):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ki(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=n)return t!==null?{text:t,raw:a}:null;try{let l=(0,lo.parse)(a,lo.STR|lo.OBJ),p=r(l);p!==null&&(t=p)}catch{}return n=a.length,{text:t||"",raw:a}},close:()=>{}}},Bi=()=>{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.16.0";var xr=jg;var eC="https://api.runtype.com/v1/dispatch",Di="https://api.runtype.com";function tC(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 a=t.slice(r+1).split(";")[0]?.trim()??"";if(a&&a!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(a))return`attachment.${a}`}return"attachment"}var cd=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 nC(e){switch(e){case"json":return Hi;case"regex-json":return Wi;case"xml":return Bi;default:return Ii}}var Gg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function oC(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=Gg(n);if(!Gg(o))return e;if(!r||o===n||o.startsWith(n))return t;let s=ds(e);return ds(t)!==null&&s===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??eC,this.headers={"Content-Type":"application/json","X-Persona-Version":xr,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??nC(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 na(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 a=Tg(o,r);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Di}/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}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":xr},body:JSON.stringify(r)});if(!a.ok){let l=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):a.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,"")||Di}/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}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":xr},body:JSON.stringify(r)});if(!a.ok){let s=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(s.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),a=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,s={sessionId:o.sessionId,messages:t.messages.filter(cd).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...a&&Object.keys(a).length>0&&{metadata:a},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...s,...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":xr},body:JSON.stringify(c),signal:t.signal})});if(!l.ok){let d=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let f=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:f}),f}if(l.status===429){let f=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:f}),f}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!l.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,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 s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.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 s=await this.getHeaders();r={...r,...s}}catch(s){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",s)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(s){let l=s instanceof Error?s:new Error(String(s));throw n({type:"error",error:l}),l}else a=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!a.ok||!a.body){let s=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:s}),s}n({type:"status",status:"connected"});try{await this.streamResponse(a.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$/,"")||Di}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(r,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let a=!!(n&&n.length>0),s=a?Sg(n):void 0,l=this.clientToolsFingerprintSessionId===t,p=a&&l&&this.lastSentClientToolsFingerprint===s,d=!a&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,f;for(let g=0;;g++){if(f=await o({...a&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...s?{clientToolsFingerprint:s}:{}}),f.status===409&&g===0&&a&&(await f.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:f,commit:()=>{this.lastSentClientToolsFingerprint=s??null,this.clientToolsFingerprintSessionId=t,a?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),a=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Di}/resume`,s;r&&(s=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(s&&(p.sessionId=s),r&&s){let d=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:f}=await this.sendWithClientToolsDiff(s,d,g=>{let m={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(a,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&f(),c}return fetch(a,{method:"POST",headers:l,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 a=await r({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(n,a)}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",a)}}));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(cd).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).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}},a=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);return s&&(r.context=s),r}async buildPayload(t){let n=t.slice().filter(cd).sort((l,p)=>{let d=new Date(l.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).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,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let a=[...sa(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];a.length>0&&(r.clientTools=a);let s=await this.buildContextAggregate(t);if(s&&(r.context=s),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(t,n,o,r,a,s){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(t);if(l===null)return!1;let p=c=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...c!==void 0&&{partId:c}};return o.current=f,r(f),f},d=c=>o.current?o.current:p(c);if(l.text!==void 0){l.partId!==void 0&&s.current!==null&&l.partId!==s.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(s.current=l.partId);let c=d(l.partId);l.partId!==void 0&&!c.partId&&(c.partId=l.partId),c.content+=l.text,r(c)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),s.current=null,n({type:"status",status:"idle"})),l.error&&(s.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 a=t.getReader(),s=new TextDecoder,l="",p=Date.now(),d=0,c=()=>p+d++,f=I=>{let B=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,y=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,D=I.tools?I.tools.map(H=>({...H,chunks:H.chunks?[...H.chunks]:void 0})):void 0;return{...I,reasoning:B,toolCall:y,tools:D}},g=I=>{if(I.role!=="assistant"||I.variant)return!0;let B=Array.isArray(I.contentParts)&&I.contentParts.length>0,y=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||B||y||!!I.stopReason},m=I=>{g(I)&&n({type:"message",message:f(I)})},b=null,w=null,T={current:null},L={current:null},A=null,S="",C=new Map,M=new Map,P=new Map,R=new Map,F=new Map,O={lastId:null,byStep:new Map},$={lastId:null,byCall:new Map},E=I=>{if(I==null)return null;try{return String(I)}catch{return null}},G=I=>E(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),Q=I=>E(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),Z=o,J=!1,fe=()=>{if(b)return b;let I,B="",y=A;return!J&&Z?(I=Z,J=!0,B=r??""):Z&&y?I=`${Z}_${y}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:I,role:"assistant",content:B,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},m(b),b},ne=(I,B)=>{O.lastId=B,I&&O.byStep.set(I,B)},ge=(I,B)=>{let y=I.reasoningId??I.id,D=G(I);if(y){let N=String(y);return ne(D,N),N}if(D){let N=O.byStep.get(D);if(N)return O.lastId=N,N}if(O.lastId&&!B)return O.lastId;if(!B)return null;let H=`reason-${c()}`;return ne(D,H),H},ie=I=>{let B=R.get(I);if(B)return B;let y={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"streaming",chunks:[]}};return R.set(I,y),m(y),y},ue=(I,B)=>{$.lastId=B,I&&$.byCall.set(I,B)},oe=new Set,me=new Map,Se=new Set,Ce=new Map,Be=I=>{if(!I)return!1;let B=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return B==="emit_artifact_markdown"||B==="emit_artifact_component"},ut=(I,B)=>{let y=I.toolId??I.id,D=Q(I);if(y){let N=String(y);return ue(D,N),N}if(D){let N=$.byCall.get(D);if(N)return $.lastId=N,N}if($.lastId&&!B)return $.lastId;if(!B)return null;let H=`tool-${c()}`;return ue(D,H),H},Je=I=>{let B=F.get(I);if(B)return B;let y={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:I,status:"pending"}};return F.set(I,y),m(y),y},Qe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let B=Number(I);if(!Number.isNaN(B)&&Number.isFinite(B))return B;let y=Date.parse(I);if(!Number.isNaN(y))return y}return Date.now()},Ne=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},_e=new Map,Ae=new Map,Me=new Map,qe=(I,B,y)=>{let D=Me.get(I);D||(D=[],Me.set(I,D));let H=0,N=D.length;for(;H<N;){let V=H+N>>>1;D[V].seq<B?H=V+1:N=V}D[H]?.seq===B?D[H]={seq:B,text:y}:D.splice(H,0,{seq:B,text:y});let K="";for(let V=0;V<D.length;V++)K+=D[V].text;return K},Jt=(I,B)=>{let y=Ne(B),D=Ae.get(I.id),H=oC(D,y);I.rawContent=H;let N=_e.get(I.id),K=de=>{let Pe=I.content??"";de.trim()!==""&&(Pe.trim().length===0||de.startsWith(Pe)||de.trimStart().startsWith(Pe.trim()))&&(I.content=de)},V=()=>{if(N){let de=N.close?.();de instanceof Promise&&de.catch(()=>{})}_e.delete(I.id),Ae.delete(I.id),I.streaming=!1,m(I)};if(!N){K(y),V();return}let X=ds(H);if(X!==null&&X.trim()!==""){K(X),V();return}let ce=de=>{let Pe=typeof de=="string"?de:de?.text??null;if(Pe!==null&&Pe.trim()!=="")return Pe;let ze=N.getExtractedText();return ze!==null&&ze.trim()!==""?ze:y},Ve;try{Ve=N.processChunk(H)}catch{K(y),V();return}if(Ve instanceof Promise){Ve.then(de=>{K(ce(de)),V()}).catch(()=>{K(y),V()});return}K(ce(Ve)),V()},gt=null,Bt=(I,B,y,D)=>{I.rawContent=B,_e.has(I.id)||_e.set(I.id,this.createStreamParser());let H=_e.get(I.id),N=B.trim().startsWith("{")||B.trim().startsWith("[");if(N&&Ae.set(I.id,B),H.__isPlainTextParser===!0){I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I);return}let V=H.processChunk(B);if(V instanceof Promise)V.then(X=>{let ce=typeof X=="string"?X:X?.text??null;ce!==null&&ce.trim()!==""?(I.content=ce,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}).catch(()=>{I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I)});else{let X=typeof V=="string"?V:V?.text??null;X!==null&&X.trim()!==""?(I.content=X,m(I)):!N&&!B.trim().startsWith("<")&&(I.content=D!==void 0?B:I.content+y,Ae.delete(I.id),_e.delete(I.id),I.rawContent=void 0,m(I))}},Tn=(I,B)=>{let y=B??I.content;if(y==null||y===""){I.streaming=!1,m(I);return}let H=Ae.get(I.id)??Ne(y);I.rawContent=H;let N=_e.get(I.id),K=null,V=!1;if(N&&(K=N.getExtractedText(),K===null&&(K=ds(H)),K===null)){let X=N.processChunk(H);X instanceof Promise?(V=!0,X.then(ce=>{let Ve=typeof ce=="string"?ce:ce?.text??null;Ve!==null&&(I.content=Ve,I.streaming=!1,_e.delete(I.id),Ae.delete(I.id),m(I))}).catch(()=>{})):K=typeof X=="string"?X:X?.text??null}if(!V){K!==null&&K.trim()!==""?I.content=K:Ae.has(I.id)||(I.content=Ne(y));let X=_e.get(I.id);if(X){let ce=X.close?.();ce instanceof Promise&&ce.catch(()=>{}),_e.delete(I.id)}Ae.delete(I.id),I.streaming=!1,m(I)}},En=(I,B,y)=>{let D=M.get(I);if(D)return D;let H={id:`nested-${B}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...y?{variant:y}:{},...y==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:B}};return M.set(I,H),m(H),H},et=[],Le,he=new Map,tt=0,Te="agent",be=!1,re=null,xe=null,kn=new Map,ee=this.config.iterationDisplay??"separate";for(Le=()=>{for(let I=0;I<et.length;I++){let B=et[I].payloadType,y=et[I].payload;if(!be&&Te!=="flow"&&typeof y.stepType=="string"&&(Te="flow"),B==="reasoning_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H),En(D,H,"reasoning");continue}let N=ge(y,!0)??`reason-${c()}`,K=ie(N);K.reasoning=K.reasoning??{id:N,status:"streaming",chunks:[]},K.reasoning.startedAt=K.reasoning.startedAt??Qe(y.startedAt??y.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(B==="reasoning_delta"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let V=M.get(D),X=y.reasoningText??y.text??y.delta??"";X&&y.hidden!==!0&&V.reasoning&&(V.reasoning.chunks.push(String(X)),m(V));continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=ie(H);N.reasoning=N.reasoning??{id:H,status:"streaming",chunks:[]},N.reasoning.startedAt=N.reasoning.startedAt??Qe(y.startedAt??y.timestamp);let K=y.reasoningText??y.text??y.delta??"";if(K&&y.hidden!==!0){let V=typeof y.sequenceIndex=="number"?y.sequenceIndex:void 0;if(V!==void 0){let X=qe(H,V,String(K));N.reasoning.chunks=[X]}else N.reasoning.chunks.push(String(K))}if(N.reasoning.status=y.done?"complete":"streaming",y.done){N.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let V=N.reasoning.startedAt??Date.now();N.reasoning.durationMs=Math.max(0,(N.reasoning.completedAt??Date.now())-V)}N.streaming=N.reasoning.status!=="complete",m(N)}else if(B==="reasoning_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)&&M.has(D)){let X=M.get(D);if(X.reasoning){let ce=typeof y.text=="string"?y.text:"";ce&&X.reasoning.chunks.length===0&&X.reasoning.chunks.push(ce),X.reasoning.status="complete",X.streaming=!1,m(X)}C.delete(D),M.delete(D);continue}let H=ge(y,!1)??ge(y,!0)??`reason-${c()}`,N=typeof y.text=="string"?y.text:"";!R.get(H)&&(N||y.scope==="loop")&&ie(H);let K=R.get(H);if(K?.reasoning){(y.scope==="loop"||y.scope==="turn")&&(K.reasoning.scope=y.scope),N&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(N),K.reasoning.status="complete",K.reasoning.completedAt=Qe(y.completedAt??y.timestamp);let X=K.reasoning.startedAt??Date.now();K.reasoning.durationMs=Math.max(0,(K.reasoning.completedAt??Date.now())-X),K.streaming=!1,m(K)}let V=G(y);V&&O.byStep.delete(V)}else if(B==="tool_start"){b&&(b.streaming=!1,m(b),b=null),typeof y.iteration=="number"&&(tt=y.iteration);let D=(typeof y.toolCallId=="string"?y.toolCallId:void 0)??ut(y,!0)??`tool-${c()}`,H=y.toolName??y.name;if(Be(H)){oe.add(D);continue}ue(Q(y),D);let N=Je(D),K=N.toolCall??{id:D,status:"pending"};K.name=H??K.name,K.status="running",y.parameters!==void 0?K.args=y.parameters:y.args!==void 0&&(K.args=y.args),K.startedAt=K.startedAt??Qe(y.startedAt??y.timestamp),K.completedAt=void 0,K.durationMs=void 0,N.toolCall=K,N.streaming=!0,y.executionId&&(N.agentMetadata={executionId:y.executionId,iteration:y.iteration}),m(N)}else if(B==="tool_output_delta"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D))continue;let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.startedAt=N.startedAt??Qe(y.startedAt??y.timestamp);let K=y.text??y.delta??y.message??"";K&&(N.chunks=N.chunks??[],N.chunks.push(String(K))),N.status="running",H.toolCall=N,H.streaming=!0;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H)}else if(B==="tool_complete"){let D=ut(y,!1)??ut(y,!0)??`tool-${c()}`;if(oe.has(D)){oe.delete(D);continue}let H=Je(D),N=H.toolCall??{id:D,status:"running"};N.status="complete",y.result!==void 0&&(N.result=y.result),typeof y.duration=="number"&&(N.duration=y.duration),N.completedAt=Qe(y.completedAt??y.timestamp);let K=y.duration??y.executionTime;if(typeof K=="number")N.durationMs=K;else{let ce=N.startedAt??Date.now();N.durationMs=Math.max(0,(N.completedAt??Date.now())-ce)}H.toolCall=N,H.streaming=!1;let V=y.agentContext;(V||y.executionId)&&(H.agentMetadata=H.agentMetadata??{executionId:V?.executionId??y.executionId,iteration:V?.iteration??y.iteration}),m(H);let X=Q(y);X&&$.byCall.delete(X)}else if(B==="await"&&y.toolName){let D=typeof y.toolCallId=="string"&&y.toolCallId.length>0?y.toolCallId:void 0,H=D??y.toolId??`local-${c()}`,N=Je(H),K=y.toolName,V=y.origin==="webmcp"&&!Lo(K)?`webmcp:${K}`:K,X=Lo(V),ce=N.toolCall??{id:H,status:"pending"};ce.name=V,ce.args=y.parameters,ce.status=X?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??Qe(y.startedAt??y.timestamp??y.awaitedAt),X?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,N.toolCall=ce,N.streaming=!1,N.agentMetadata={...N.agentMetadata,executionId:y.executionId??N.agentMetadata?.executionId,awaitingLocalTool:!0,...D?{webMcpToolCallId:D}:{}},m(N)}else if(B==="text_start"){let D=typeof y.id=="string"?y.id:null,H=typeof y.parentToolCallId=="string"&&y.parentToolCallId?y.parentToolCallId:null;if(D&&H){C.set(D,H);continue}let N=b;N&&(Te==="flow"?(Tn(N),gt=N):(N.streaming=!1,m(N)),b=null),A=typeof y.id=="string"?y.id:A,S=""}else if(B==="text_delta"){let D=typeof y.id=="string"?y.id:null,H=D?C.get(D):void 0;if(D&&H){let K=typeof y.delta=="string"?y.delta:"",V=(P.get(D)??"")+K;if(P.set(D,V),V.trim()==="")continue;let X=En(D,H);X.agentMetadata={...X.agentMetadata,executionId:y.executionId,parentToolId:H},Bt(X,V,K,void 0);continue}if(A=typeof y.id=="string"?y.id:A,Te==="flow"){let K=typeof y.delta=="string"?y.delta:"";if(S+=K,S.trim()==="")continue;let V=fe();V.agentMetadata={executionId:y.executionId,iteration:y.iteration},Bt(V,S,K,void 0),w=V;continue}let N=fe();N.content+=y.delta??"",N.agentMetadata={executionId:y.executionId,iteration:y.iteration,turnId:re??void 0,agentName:xe?.agentName},w=N,m(N)}else if(B==="text_complete"){let D=typeof y.id=="string"?y.id:null;if(D&&C.has(D)){let N=M.get(D);N&&Tn(N),C.delete(D),P.delete(D),M.delete(D);continue}let H=b;H&&(Te==="flow"?(Tn(H),gt=H):((H.content??"")===""&&typeof y.text=="string"&&(H.content=y.text),H.streaming=!1,m(H)),b=null),A=null,S=""}else if(B==="step_complete"){let D=y.stepType,H=y.executionType;if(D==="tool"||H==="context")continue;if(y.success===!1){let N=y.error,K=typeof N=="string"&&N!==""?N:N!=null&&typeof N=="object"&&Reflect.has(N,"message")?String(N.message??"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let V=b;V&&V.streaming&&(V.streaming=!1,m(V)),n({type:"status",status:"idle"});continue}{let N=gt;gt=null;let K=y.stopReason,V=y.result?.response;if(N)K&&(N.stopReason=K),V!=null?Jt(N,V):N.streaming!==!1&&(_e.delete(N.id),Ae.delete(N.id),N.streaming=!1,m(N));else{let X=V!=null&&V!=="";if(X||K){let ce=fe();K&&(ce.stopReason=K),X?Tn(ce,V):(ce.streaming=!1,m(ce))}}continue}}else if(B==="execution_start")Te=y.kind==="flow"?"flow":"agent",be=!0,Te==="agent"&&(xe={executionId:y.executionId,agentId:y.agentId??"virtual",agentName:y.agentName??"",status:"running",currentIteration:0,maxTurns:y.maxTurns??1,startedAt:Qe(y.startedAt)});else if(B==="turn_start"){let D=typeof y.iteration=="number"?y.iteration:tt;if(D!==tt){if(xe&&(xe.currentIteration=D),ee==="separate"&&D>1){let H=b;H&&(H.streaming=!1,m(H),kn.set(D-1,H),b=null)}tt=D}re=typeof y.id=="string"?y.id:null,w=null}else if(B==="tool_input_delta"){let D=y.toolCallId??$.lastId;if(D){let H=F.get(D);H?.toolCall&&(H.toolCall.chunks=H.toolCall.chunks??[],H.toolCall.chunks.push(y.delta??""),m(H))}}else{if(B==="tool_input_complete")continue;if(B==="turn_complete"){let D=y.stopReason,H=b??w;if(D&&H!==null){let N=y.id;(!N||H.agentMetadata?.turnId===N)&&(H.stopReason=D,m(H))}re===y.id&&(re=null)}else if(B==="media_start"){let D=String(y.id);he.set(D,{mediaType:typeof y.mediaType=="string"?y.mediaType:void 0,role:typeof y.role=="string"?y.role:void 0,toolCallId:y.toolCallId,parts:[]})}else if(B==="media_delta"){let D=he.get(String(y.id));D&&typeof y.delta=="string"&&D.parts.push(y.delta)}else if(B==="media_complete"){let D=String(y.id),H=he.get(D);he.delete(D);let N=(typeof y.mediaType=="string"?y.mediaType:void 0)??H?.mediaType??"application/octet-stream",K=typeof y.data=="string"?y.data:void 0,V=typeof y.url=="string"?y.url:H&&H.parts.length>0?H.parts.join(""):void 0,X=null;if(K)X={type:"media",data:K,mediaType:N};else if(V){let Pe=N.toLowerCase();X={type:Pe==="image"||Pe.startsWith("image/")?"image-url":"file-url",url:V,mediaType:N}}let ce=y.toolCallId??H?.toolCallId,Ve=X?[X]:[],de=[];for(let Pe of Ve){if(!Pe||typeof Pe!="object")continue;let ze=Pe,Ue=typeof ze.type=="string"?ze.type:void 0,We=typeof ze.mediaType=="string"?ze.mediaType.toLowerCase():"",we=null,nt="";if(Ue==="media"){let wt=typeof ze.data=="string"?ze.data:void 0;if(!wt)continue;nt=We.length>0?We:"application/octet-stream",we=`data:${nt};base64,${wt}`}else if(Ue==="image-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else if(Ue==="file-url"){let wt=typeof ze.url=="string"?ze.url:void 0;if(!wt)continue;nt=We,we=wt}else continue;if(we)if(Ue==="image-url"||nt.startsWith("image/"))de.push({type:"image",image:we,...nt.includes("/")?{mimeType:nt}:{}});else if(nt.startsWith("audio/"))de.push({type:"audio",audio:we,mimeType:nt});else if(nt.startsWith("video/"))de.push({type:"video",video:we,mimeType:nt});else{let wt=nt||"application/octet-stream";de.push({type:"file",data:we,mimeType:wt,filename:tC(wt)})}}if(de.length>0){let Pe=c(),ze=ce,We={id:`agent-media-${typeof ze=="string"&&ze.length>0?`${ze}-${Pe}`:String(Pe)}`,role:"assistant",content:"",contentParts:de,createdAt:new Date().toISOString(),streaming:!1,sequence:Pe,agentMetadata:{executionId:y.executionId,iteration:typeof y.iteration=="number"?y.iteration:tt}};m(We);let we=b;we&&(we.streaming=!1,m(we)),b=null,T.current=null}}else if(B==="execution_complete"){let D=y.kind??Te;D==="agent"&&xe&&(xe.status=y.success?"complete":"error",xe.completedAt=Qe(y.completedAt),xe.stopReason=y.stopReason);let H=b;H&&(D==="flow"&&H.streaming!==!1?Tn(H):(H.streaming=!1,m(H)),b=null),A=null,S="",gt=null,n({type:"status",status:"idle",terminal:!0})}else if(B==="execution_error"){let D=typeof y.error=="string"?y.error:y.error?.message??"Execution error";n({type:"error",error:new Error(D)})}else if(B!=="ping"){if(B==="approval_start"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="step_await"&&y.awaitReason==="approval_required"){let D=y.approvalId??`approval-${c()}`,H={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",toolType:y.toolType,description:y.description??`Execute ${y.toolName??"tool"}`,...typeof y.reason=="string"&&y.reason?{reason:y.reason}:{},parameters:y.parameters}};m(H)}else if(B==="approval_complete"){let D=y.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:y.decision??"approved",agentId:xe?.agentId??"virtual",executionId:y.executionId??xe?.executionId??"",toolName:y.toolName??"",description:y.description??"",resolvedAt:Date.now()}};m(N)}}else if(B==="artifact_start"||B==="artifact_delta"||B==="artifact_update"||B==="artifact_complete"){if(B==="artifact_start"){let D=y.artifactType,H=String(y.id),N=typeof y.title=="string"?y.title:void 0,K=y.file,V;K&&typeof K=="object"&&!Array.isArray(K)&&typeof K.path=="string"&&typeof K.mimeType=="string"&&(V={path:K.path,mimeType:K.mimeType,...typeof K.language=="string"?{language:K.language}:{}}),n({type:"artifact_start",id:H,artifactType:D,title:N,component:typeof y.component=="string"?y.component:void 0,...V?{file:V}:{}});let X=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?{...y.props}:void 0;if(Ce.set(H,{markdown:"",title:N,file:V,...X?{props:X}:{}}),!Se.has(H)){Se.add(H);let ce=zn(this.config.features?.artifacts,{artifactType:D,...V?{file:V}:{}}),Ve=typeof y.component=="string"?y.component:void 0,de={id:`artifact-ref-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:rs(ce,{artifactId:H,title:N,artifactType:D,status:"streaming",...V?{file:V}:{},...Ve?{component:Ve}:{}})};me.set(H,de),m(de)}}else if(B==="artifact_delta"){let D=String(y.id),H=typeof y.delta=="string"?y.delta:String(y.delta??"");n({type:"artifact_delta",id:D,artDelta:H});let N=Ce.get(D);N&&(N.markdown+=H)}else if(B==="artifact_update"){let D=y.props&&typeof y.props=="object"&&!Array.isArray(y.props)?y.props:{};n({type:"artifact_update",id:String(y.id),props:D,component:typeof y.component=="string"?y.component:void 0});let H=Ce.get(String(y.id));H&&(H.props={...H.props??{},...D})}else if(B==="artifact_complete"){let D=String(y.id);n({type:"artifact_complete",id:D});let H=me.get(D);if(H){H.streaming=!1;try{let N=JSON.parse(H.rawContent??"{}");if(N.props){N.props.status="complete";let K=Ce.get(D);K?.markdown&&(N.props.markdown=K.markdown),K?.file&&(N.props.file=K.file),N.component==="PersonaArtifactInline"&&K?.props&&Object.keys(K.props).length>0&&(N.props.componentProps=K.props)}H.rawContent=JSON.stringify(N)}catch{}Ce.delete(D),m(H),me.delete(D)}}}else if(B==="transcript_insert"){let D=y.message;if(!D||typeof D!="object")continue;let H=String(D.id??`msg-${c()}`),N=D.role,V={id:H,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(m(V),V.rawContent)try{let ce=JSON.parse(V.rawContent)?.props?.artifactId;typeof ce=="string"&&Se.add(ce)}catch{}b=null,T.current=null,_e.delete(H),Ae.delete(H)}else if(B==="error"){if(y.recoverable===!1&&y.error!=null&&y.error!==""){let D=typeof y.error=="string"?y.error:y.error?.message!=null?String(y.error.message):"Execution error";n({type:"error",error:new Error(D)});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}else if(B==="step_error"||B==="dispatch_error"||B==="flow_error"){let D=null;if(y.error instanceof Error)D=y.error;else if(B==="dispatch_error"){let H=y.message??y.error;H!=null&&H!==""&&(D=new Error(String(H)))}else{let H=y.error;typeof H=="string"&&H!==""?D=new Error(H):H!=null&&typeof H=="object"&&Reflect.has(H,"message")&&(D=new Error(String(H.message??H)))}if(D){n({type:"error",error:D});let H=b;H&&H.streaming&&(H.streaming=!1,m(H)),n({type:"status",status:"idle"})}}}}}et.length=0};;){let{done:I,value:B}=await a.read();if(I)break;l+=s.decode(B,{stream:!0});let y=l.split(`
13
13
 
14
- `);l=x.pop()??"";for(let H of x){let R=H.split(`
15
- `),B="message",K="",_=null;for(let Re of R)Re.startsWith("event:")?B=Re.replace("event:","").trim():Re.startsWith("data:")?K+=Re.replace("data:","").trim():Re.startsWith("id:")&&(_=Re.slice(3).trim());let $=()=>{_!==null&&_!==""&&n({type:"cursor",id:_})};if(!K){$();continue}let Y;try{Y=JSON.parse(K)}catch(Re){n({type:"error",error:Re instanceof Error?Re:new Error("Failed to parse chat stream payload")});continue}let je=B!=="message"?B:Y.type??"message";if(this.onSSEEvent?.(je,Y),this.parseSSEEvent){E.current=h;let Re=await this.handleCustomSSEEvent(Y,n,E,f,d,k);if(E.current&&E.current!==h&&(h=E.current),Re){$();continue}}ce.push({payloadType:je,payload:Y}),et(),$()}}et()}};function km(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Br(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function So(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Lm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Pm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function mi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Rm(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Mo(e){return{type:"text",text:e}}function Im(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Wm(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 Hm(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 Bm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],gx=["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"],Yn=[...Bm,...gx];function hx(e){return Bm.includes(e)||e.startsWith("image/")}function gi(e){return hx(e.type)}async function Dm(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;gi(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 Fm(e,t=Yn,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 yx(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Om(e,t){let n=yx(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 hi=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 a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,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 s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,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 a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var Nm=16e3,bx=24e3,xx=4096,vx=1380533830;function Cx(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vx?new Uint8Array(e,44):new Uint8Array(e)}function wx(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 Na=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 a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Nm,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(u=>u.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:Nm});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new hi(bx);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(u=>u.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${wx(o)}/ws/agents/${encodeURIComponent(t)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,a,d,r))},d.onmessage=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let g=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}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 a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor(xx,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*32767}o.send(c.buffer)},a.connect(s),s.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=Cx(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 tr=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(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({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 To(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Na(e.runtype);case"browser":if(!tr.isSupported())throw new Error("Browser speech recognition not supported");return new tr(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 yi(e){if(e?.type==="custom"&&e.custom)return To({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return To({type:"runtype",runtype:e.runtype});if(tr.isSupported())return To({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function _a(e){try{return yi(e),!0}catch{return!1}}function Dr(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 Eo=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),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):Dr(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.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 nr=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 vd(e){if(!e)return"";let t=Ax(e);return _m(t!==null?t:e)}function Ax(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 _m(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,`
14
+ `);l=y.pop()??"";for(let D of y){let H=D.split(`
15
+ `),N="message",K="",V=null;for(let de of H)de.startsWith("event:")?N=de.replace("event:","").trim():de.startsWith("data:")?K+=de.replace("data:","").trim():de.startsWith("id:")&&(V=de.slice(3).trim());let X=()=>{V!==null&&V!==""&&n({type:"cursor",id:V})};if(!K){X();continue}let ce;try{ce=JSON.parse(K)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let Ve=N!=="message"?N:ce.type??"message";if(this.onSSEEvent?.(Ve,ce),this.parseSSEEvent){T.current=b;let de=await this.handleCustomSSEEvent(ce,n,T,m,c,L);if(T.current&&T.current!==b&&(b=T.current),de){X();continue}}et.push({payloadType:Ve,payload:ce}),Le(),X()}}Le()}};function Kg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function ia(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Fo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Fi="[Image]";function Xg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Jg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Oi(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Qg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Oo(e){return{type:"text",text:e}}function Yg(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function Zg(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 eh(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 th=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],rC=["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"],co=[...th,...rC];function aC(e){return th.includes(e)||e.startsWith("image/")}function Ni(e){return aC(e.type)}async function nh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ni(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 oh(e,t=co,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 sC(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function rh(e,t){let n=sC(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 _i=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 a=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,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 s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of s)l()}r.onended=()=>{let s=this.activeSources.indexOf(r);s!==-1&&this.activeSources.splice(s,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 a=0;a<n;a++){let s=r.getInt16(a*2,!0);o[a]=s/32768}return o}};var ah=16e3,iC=24e3,lC=4096,cC=1380533830;function dC(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===cC?new Uint8Array(e,44):new Uint8Array(e)}function pC(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 ps=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 a=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:ah,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){a.getTracks().forEach(f=>f.stop());return}this.mediaStream=a;let s=window.AudioContext||window.webkitAudioContext,l=new s({sampleRate:ah});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new _i(iC);if(r!==this.callGeneration){p.destroy(),a.getTracks().forEach(f=>f.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let d=`${pC(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(l,a,c,r))},c.onmessage=f=>this.handleMessage(f,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.onclose=f=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(f.code!==1e3){let g=f.code?` (code ${f.code})`:"";this.emitError(new Error(`Voice connection closed${g}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(a){throw this.cleanup(),this.emitError(a),this.emitStatus("error"),a}}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 a=t.createMediaStreamSource(n);this.sourceNode=a;let s=t.createScriptProcessor(lC,1,1);this.processor=s,s.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let f=Math.max(-1,Math.min(1,p[c]));d[c]=f<0?f*32768:f*32767}o.send(d.buffer)},a.connect(s),s.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=dC(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 Cr=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(a=>a[0]).map(a=>a.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(a=>a({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 ps(e.runtype);case"browser":if(!Cr.isSupported())throw new Error("Browser speech recognition not supported");return new Cr(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 Ui(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(Cr.isSupported())return No({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function us(e){try{return Ui(e),!0}catch{return!1}}function la(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 _o=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),a=o.getVoices();if(t.voice){let s=a.find(l=>l.name===t.voice);s&&(r.voice=s)}else a.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(a):la(a));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=s=>{let l=s.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 wr=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 dd(e){if(!e)return"";let t=uC(e);return sh(t!==null?t:e)}function uC(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 sh(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,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
- `),t.trim()}var Cd=null,Um=e=>{Cd=e},wd=()=>Cd?Cd():import("./runtype-tts-entry");var Tx=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Ex(e,t){return Tx.some(n=>e[n]!==t[n])}function Ad(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
+ `),t.trim()}var pd=null,ih=e=>{pd=e},ud=()=>pd?pd():import("./runtype-tts-entry");var gC=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function hC(e,t){return gC.some(n=>e[n]!==t[n])}function fd(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}
18
18
 
19
- _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]}),zm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,$m=e=>yo(e)||e===kn,Fr=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 nr(()=>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&&(yo(n.name)||n.name===kn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new er(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||wd().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 _a(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=Eo.isSupported()?new Eo({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,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return wd().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(s&&n)return a&&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=To(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),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(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),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(!Ex(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=o,this.client=new er(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}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:a,id:s,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=t,f={id:s??(n==="user"?Br():n==="assistant"?So():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,A={id:p??(r==="user"?Br():r==="assistant"?So():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(A)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
19
+ _Details: ${n.message}_`:o}var fs=e=>({isError:!0,content:[{type:"text",text:e}]}),dh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ph=e=>Lo(e)||e===On,ca=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 wr(()=>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&&(Lo(n.name)||n.name===On&&Bo(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||ud().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 us(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=_o.isSupported()?new _o({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,a=this.config.clientToken,s=t.browserFallback!==!1;if(o&&r&&a)return ud().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let d=new l({host:o,agentId:r,clientToken:a,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return s&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(s&&n)return a&&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(a=>{a.provider!=="runtype"&&a.text&&a.text.trim()&&this.sendMessage(a.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((a,s,l)=>{if(a==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:s,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:s,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(a=>{this.config.voiceRecognition?.onMetrics?.(a)}),this.voiceProvider.onError(a=>{console.error("Voice error:",a),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(a=>{this.voiceStatus=a,this.voiceActive=a==="listening",this.callbacks.onVoiceStatusChanged?.(a)}),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(!hC(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let a=this.client.getSSEEventCallback();this.config=o,this.client=new vr(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),a&&this.client.setSSEEventCallback(a)}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:a,id:s,createdAt:l,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:f}=t,m={id:s??(n==="user"?ia():n==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...a!==void 0&&{contentParts:a},...c!==void 0&&{voiceProcessing:c},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:a,llmContent:s,contentParts:l,id:p,createdAt:d,sequence:c,streaming:f=!1,voiceProcessing:g,rawContent:m}=o,w={id:p??(r==="user"?ia():r==="assistant"?Fo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:a,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...l!==void 0&&{contentParts:l},...g!==void 0&&{voiceProcessing:g},...m!==void 0&&{rawContent:m}};n.push(w)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:a,id:s,createdAt:l,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let a=r.blocks.join(`
20
20
 
21
21
  `),s=[a,n].filter(Boolean).join(`
22
22
 
23
- `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];a&&c.push(Mo(a)),c.push(...r.contentParts),c.push(...t.contentParts),t.contentParts=c}else if(p){let c=[];s&&c.push(Mo(s)),c.push(...r.contentParts),t.contentParts=c}else a&&(t.llmContent=s);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=Br(),a=So();this.activeAssistantMessageId=null;let s=n?.contentParts&&mi(n.contentParts)?fi:"",l={id:r,role:"user",content:o||s,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 p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(u=>u.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:a},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let g=Ad(d,this.config.errorMessage);if(g){let f={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=So();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 a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let s=Ad(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(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 a of this.messages)a.streaming&&a.id!==o&&(a.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(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}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(a=>a.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}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),d){let u=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}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(d=>d.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let d=t.toolCall?.args,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let g=typeof u[0]?.question=="string"?u[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=t.toolCall.id,p=t.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,g])=>`${u}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=s??{};c.forEach((u,g)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let h=d[f],A=Array.isArray(h)?h.join(", "):typeof h=="string"?h:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:A||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[a]:n});if(!d.ok){let u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let a=this.webMcpEpoch;queueMicrotask(()=>{a===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!==kn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},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=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let u=`${t}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let g=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===kn)return{dedupeKey:u,resumeKey:f,output:md(),toolMessage:p,startedAt:g,completedAt:Date.now()};let h=new AbortController;this.webMcpResolveControllers.add(h),r.push(h);let A=this.client.executeWebMcpToolCall(c,p.toolCall?.args,h.signal),E;if(!A)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await A}catch(k){let M=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));return M||this.callbacks.onError?.(k instanceof Error?k:new Error(String(k))),this.markWebMcpToolComplete(p,Ua(M?"Aborted by cancel()":zm(k)),g),this.webMcpInflightKeys.delete(u),null}return h.signal.aborted?(this.markWebMcpToolComplete(p,Ua("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:E,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(t,p,{signal:a.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===kn?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.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 d of l)this.markWebMcpToolComplete(d.toolMessage,Ua("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(a),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 h=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(h)||this.webMcpResolvedKeys.has(h))return;this.webMcpInflightKeys.add(h);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(h)}catch(A){this.callbacks.onError?.(A instanceof Error?A:new Error(String(A)))}finally{this.webMcpInflightKeys.delete(h)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===kn,d=t.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),g="execute",f=s;try{let h;if(c?h=md():u?h=await u:h={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(t,Ua("Aborted by cancel()"),s);return}let A=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,A,h,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,h,s,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(h){let A=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));(g==="execute"||A||p.aborted)&&this.markWebMcpToolComplete(t,Ua(A||p.aborted?"Aborted by cancel()":zm(h)),s),A||this.callbacks.onError?.(h instanceof Error?h:new Error(String(h)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.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=Bn(this.config.features?.artifacts,t),r=Ra(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}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.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(s=>s.id===`artifact-ref-${n.id}`);if(!o)continue;let r=Bn(this.config.features?.artifacts,n),a=Ra(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!==a&&(o.rawContent=a,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(()=>(Vm(),qm)).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=>Ad(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=So(),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(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=vd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Dr(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=vd(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,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,u=n.approval;s.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&$m(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),g=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,h=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&$m(f)&&r.toolCall?.status==="complete";(u||g||h)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.streaming)}return s}),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(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var Sd=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var Md=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var Td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Ed=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var kd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Ld=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Pd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Rd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Id=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Wd=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Hd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Bd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Dd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Fd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var Od=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var Nd=[["path",{d:"M20 6 9 17l-5-5"}]];var _d=[["path",{d:"m6 9 6 6 6-6"}]];var Ud=[["path",{d:"m15 18-6-6 6-6"}]];var qd=[["path",{d:"m9 18 6-6-6-6"}]];var Vd=[["path",{d:"m18 15-6-6-6 6"}]];var bi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var zd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var $d=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var vi=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Gd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Kd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Xd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Jd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var wi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Qd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Yd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Zd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var ec=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var tc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var nc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var oc=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var rc=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var ac=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var sc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var ic=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var lc=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Ai=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var dc=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var cc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var pc=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var uc=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var fc=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var mc=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Si=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var gc=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var hc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var yc=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var bc=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var xc=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var Mi=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var vc=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Cc=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var wc=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Ac=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Sc=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var Mc=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var Tc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Ec=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var kc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Lc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Pc=[["path",{d:"M5 12h14"}]];var Rc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Ic=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Wc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Hc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Bc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Dc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var Fc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Oc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Nc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var _c=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Uc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var qc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Vc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var zc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var $c=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var jc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Gc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Kc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Xc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Jc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Ti=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Qc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Yc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var Zc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var ep=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Ei=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var tp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var np=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var op=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var rp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var ap=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var sp=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var ip=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var lp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var dp=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var cp=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var ki=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var pp=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var up=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var fp=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var mp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var gp=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var hp=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var yp=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var bp=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var kx={activity:Sd,"arrow-down":Md,"arrow-up":Ld,"arrow-up-right":kd,bot:Hd,"chevron-down":_d,"chevron-up":Vd,"chevron-right":qd,"chevron-left":Ud,check:Nd,clipboard:$d,"clipboard-copy":zd,"code-xml":vi,copy:Gd,file:oc,"file-code":ec,"file-spreadsheet":tc,"file-text":nc,"image-plus":gc,loader:vc,"loader-circle":Mi,mic:kc,paperclip:Hc,"refresh-cw":qc,search:$c,send:jc,"shield-alert":Xc,"shield-check":Jc,"shield-x":Ti,square:tp,"thumbs-down":sp,"thumbs-up":ip,upload:up,"volume-2":mp,x:yp,user:fp,mail:wc,phone:Oc,calendar:Fd,clock:jd,building:Bd,"map-pin":Ac,lock:Cc,key:bc,"credit-card":Kd,"at-sign":Pd,hash:pc,globe:cc,link:xc,"circle-check":bi,"circle-x":xi,"triangle-alert":ki,info:yc,ban:Rd,shield:Qc,"arrow-left":Td,"arrow-right":Ed,"external-link":Yd,ellipsis:wi,"ellipsis-vertical":Ci,menu:Mc,house:Si,plus:_c,minus:Pc,pencil:Dc,trash:cp,"trash-2":dp,save:zc,download:Jd,share:Kc,funnel:Ai,settings:Gc,"rotate-cw":Vc,maximize:Sc,minimize:Lc,"shopping-cart":Zc,"shopping-bag":Yc,package:Wc,truck:pp,tag:ap,gift:dc,receipt:Uc,wallet:hp,store:op,"dollar-sign":Xd,percent:Fc,play:Nc,pause:Bc,"volume-x":gp,camera:Od,image:hc,film:ac,headphones:uc,"message-circle":Tc,"message-square":Ec,bell:Id,heart:fc,star:np,eye:Zd,"eye-off":Qd,bookmark:Wd,"calendar-days":Dd,history:mc,timer:lp,folder:lc,"folder-open":ic,files:rc,sparkles:Ei,zap:bp,sun:rp,moon:Ic,flag:sc,monitor:Rc,smartphone:ep},oe=(e,t=24,n="currentColor",o=2)=>{let r=kx[e];return r?Lx(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 Lx(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(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var Li={allowedTypes:Yn,maxFileSize:10*1024*1024,maxFiles:4};function Px(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Rx(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 or=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??Li.allowedTypes,maxFileSize:t.maxFileSize??Li.maxFileSize,maxFiles:t.maxFiles??Li.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Li.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=Fm(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 Dm(n),a=gi(n)?URL.createObjectURL(n):null,s={id:Px(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.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=gi(t.file),o=b("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 s=b("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=b("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=Rx(t.file.type),p=oe(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let c=b("span");c.textContent=Om(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",s.appendChild(c),o.appendChild(s)}let r=b("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 a=oe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.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 jm=/\s/;function Ix(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
24
- `:o===""||jm.test(o)}function Wx(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let s=e[a];if(s===n)return Ix(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
25
- `||s==="\uFFFC"||!r&&jm.test(s))return null;a--}return null}function Gm(e,t,n){for(let o of n){let r=Wx(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Km(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Xm(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 It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Gt=1e5,Pi=Gt+1;var Hx=8,Bx=8,xp=10,vp=new WeakMap,Jm=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Dx=e=>{let t=e.getRootNode?.();return Jm(t)?t:e.ownerDocument.body},Cp=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Ut(e){vp.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=Hx,viewportPadding:s=Bx}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,g=!1,f=!1,h=!1,A=()=>(typeof o=="function"?o():o).trim(),E=()=>{u?.(),u=null,c?.remove(),c=null,d=null},k=()=>{if(!c)return;let j=l(),O=p(),q=t.getBoundingClientRect(),Q=c.getBoundingClientRect(),de=j.documentElement.clientWidth||O.innerWidth,be=j.documentElement.clientHeight||O.innerHeight,De=de-s-Q.width,ie=q.left+q.width/2-Q.width/2,ge=Cp(ie,s,De),ne=q.top-s,le=be-s-q.bottom,Z=Q.height+a,me=ne>=Z||ne>=le?"top":"bottom",Ae=me==="top"?q.top-a-Q.height:q.bottom+a,we=be-s-Q.height,Se=Cp(Ae,s,we),mt=q.left+q.width/2,We=Math.max(xp,Q.width-xp),_e=Cp(mt-ge,xp,We);c.dataset.placement=me,c.style.left=`${ge}px`,c.style.top=`${Se}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${_e}px`)},M=()=>{if(h||!r||c||!t.isConnected)return;let j=A(),O=Dx(t);if(!j||!O)return;let q=l(),Q=p();c=q.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Pi),d=q.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=j,c.appendChild(d);let de=q.createElement("span");de.className="persona-control-tooltip__arrow",c.appendChild(de),O.appendChild(c),k(),c.dataset.state="open";let be=()=>{if(!t.isConnected){E();return}d&&(d.textContent=A()),k()};Q.addEventListener("scroll",be,!0),Q.addEventListener("resize",be);let De=t.getRootNode(),ie=Jm(De)?De:q.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||E()});ge?.observe(ie,{childList:!0,subtree:!0}),u=()=>{Q.removeEventListener("scroll",be,!0),Q.removeEventListener("resize",be),ge?.disconnect()}},S=()=>{g||f?M():E()},C=()=>{let j=p();(!j.matchMedia||!j.matchMedia("(hover: none)").matches)&&(g=!0,S())},T=()=>{g=!1,S()},W=()=>{f=!0,S()},w=()=>{f=!1,S()},D=j=>{j.key==="Escape"&&(g=!1,f=!1,E())};n.addEventListener("mouseenter",C),n.addEventListener("mouseleave",T),t.addEventListener("focus",W),t.addEventListener("blur",w),t.addEventListener("keydown",D);let F={get isOpen(){return c!==null},show:M,hide:E,reposition:k,destroy:()=>{h||(h=!0,E(),n.removeEventListener("mouseenter",C),n.removeEventListener("mouseleave",T),t.removeEventListener("focus",W),t.removeEventListener("blur",w),t.removeEventListener("keydown",D),vp.delete(t))}};return vp.set(t,F),F}function Qm(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,a=Math.round(r*.6),s=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=b("div","persona-send-button-wrapper"),c=Be("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"}}),d=oe(s,a,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),Ut({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:Fx,load:Ox}=Er({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),Ym=Fx,wp=Ox;var{setLoader:Nx,load:_x}=Er({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),Zm=Nx,eg=_x;function qa(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Be("span",{className:Kn("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=oe(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=b("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Be("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function tg(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Xm(t).filter(S=>S.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(S=>S.sources.some(C=>typeof C.matchCommand=="function")),r=S=>o.some(C=>C.trigger?C.position==="line-start"?S.split(`
26
- `).some(W=>W.startsWith(C.trigger)):(C.position==="anywhere"?S:S.split(`
27
- `)[0]).startsWith(C.trigger):!1),a=(S,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:C}))}catch{}},s=Be("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=e.textarea,d=null,u=null,g=null,f=null,h=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=wp().then(C=>(l=C.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:d??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:M,emit:a}),l)).catch(C=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",C),p===S&&(p=null),null));return p=S,S},A=()=>{eg().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:W=>qa(W,{render:t.renderMentionToken}),onMentionRemoved:W=>l?.untrackMention(W)});d=C.input,u=C.destroy;let T=c;T.replaceWith(C.element),c=C.element,f={next:C.element,prev:T},g?.(C.element,T),l?l.rebindComposer(C.input):p&&p.then(W=>W?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&A();let E=[],k=new Map;for(let S of n){if(!S.showButton)continue;let C=Qm({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{h().then(T=>T?.openMenu(S.trigger))}});E.push(C),k.set(S.trigger,C.button)}let M=(S,C,T)=>{let W=k.get(C);W&&(W.setAttribute("aria-expanded",S?"true":"false"),S?W.setAttribute("aria-controls",T):W.removeAttribute("aria-controls"))};return{affordanceButtons:E.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!Km(S))return;let C=c,T=C.selectionStart??0;Gm(C.value,T,n)&&h().then(W=>W?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!f){let C=c,T=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||T)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await h())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{wp().catch(()=>{})},onComposerSwap:S=>{g=S,f&&S(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let S of E)S.wrapper.remove();s.remove()}}}var ng=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Va(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];ng(a)&&ng(r)?n[o]=Va(a,r):n[o]=r}return n}var pn="min(440px, calc(100vw - 24px))",Ri="440px",Ux={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:Ux,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function og(e,t){if(!(!e&&!t))return e?t?Va(e,t):e:t}function Or(e){return e?{...st,...e,theme:og(st.theme,e.theme),darkTheme:og(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,a=st.features?.scrollBehavior,s=e.features?.scrollBehavior,l=st.features?.streamAnimation,p=e.features?.streamAnimation,c=st.features?.askUserQuestion,d=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},f=a===void 0&&s===void 0?void 0:{...a,...s},h=l===void 0&&p===void 0?void 0:{...l,...p},A=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...st.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...h!==void 0?{streamAnimation:h}:{},...A!==void 0?{askUserQuestion:A}:{}}})(),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 Ii="16px",Wi="transparent",Ap={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"}},Sp={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"}},Mp={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:Ri,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ii,canvasBackground:Wi},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"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function 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 Hi(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=Qt(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Tp(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 rg(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=rg(a,r):n[o]=r}return n}function qx(e,t){return t?rg(e,t):e}function za(e,t={}){let n={palette:Ap,semantic:Sp,components:Mp},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:qx(n.components,e?.components)};if(t.validate!==!1){let r=Tp(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Bi(e){let t=Hi(e),n={};for(let[w,D]of Object.entries(t)){let F=w.replace(/\./g,"-");n[`--persona-${F}`]=D.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"]??Ii,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Wi,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=e.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"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-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let c=e.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.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 g=c?.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let f=c?.artifact;if(f?.toolbar){let w=f.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Qt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(f?.tab){let w=f.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(f?.pane){let w=f.pane;if(w.toolbarBackground){let D=Qt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=D}}if(f?.card){let w=f.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Qt(e,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=Qt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let h=c?.code;h&&(h.keywordColor&&(n["--persona-code-keyword-color"]=h.keywordColor),h.stringColor&&(n["--persona-code-string-color"]=h.stringColor),h.commentColor&&(n["--persona-code-comment-color"]=h.commentColor),h.numberColor&&(n["--persona-code-number-color"]=h.numberColor),h.tagColor&&(n["--persona-code-tag-color"]=h.tagColor),h.attrColor&&(n["--persona-code-attr-color"]=h.attrColor),h.propertyColor&&(n["--persona-code-property-color"]=h.propertyColor),h.lineNumberColor&&(n["--persona-code-line-number-color"]=h.lineNumberColor),h.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=h.gutterBorderColor),h.background&&(n["--persona-code-bg"]=Qt(e,h.background)??h.background));let A=n["--persona-surface"],E=n["--persona-container"],k=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",C=!E||E===A,T=C?k:E,W=C?M:E;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??T,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??W,C&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??T,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??T,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??T,n}var ag={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 Vx={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"}}},sg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$a=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",zx=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":$a()},Di=e=>zx(e),$x=e=>za(e),jx=e=>za({...e,palette:{...e?.palette,colors:{...Vx.colors,...e?.palette?.colors}}},{validate:!1}),ko=e=>{let t=Di(e),n=sg(e?.theme),o=sg(e?.darkTheme);return t==="dark"?jx(Va(n??{},o??{})):$x(n)},Gx=e=>Bi(e),rr=(e,t)=>{let n=ko(t),o=Gx(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",Di(t))},Nr=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e($a())});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($a());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Dn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function ig(e){let t=Dn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Fi(e){if(typeof e!="string")return"";let t=e.indexOf(`
23
+ `),l=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(l){let d=[];a&&d.push(Oo(a)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];s&&d.push(Oo(s)),d.push(...r.contentParts),t.contentParts=d}else a&&(t.llmContent=s);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=ia(),a=Fo();this.activeAssistantMessageId=null;let s=n?.contentParts&&Oi(n.contentParts)?Fi:"",l={id:r,role:"user",content:o||s,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 p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(f=>f.id===r)??l;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:a},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!f){let g=fd(c,this.config.errorMessage);if(g){let m={id:a,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,f||(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=Fo();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 a=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!a){let s=fd(r,this.config.errorMessage);if(s){let l={id:t,role:"assistant",createdAt:new Date().toISOString(),content:s,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,a||(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 a of this.messages)a.streaming&&a.id!==o&&(a.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(a){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(a instanceof Error?a:new Error(String(a)))}}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(a=>a.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}`,a={...t,status:n,resolvedAt:Date.now()},s=this.messages.find(c=>c.id===r),l={id:r,role:"assistant",content:"",createdAt:s?.createdAt??new Date().toISOString(),...s?.sequence!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId: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 f=null;if(c instanceof Response){if(!c.ok){let g=await c.json().catch(()=>null);throw new Error(g?.error??`Approval request failed: ${c.status}`)}f=c.body}else c instanceof ReadableStream&&(f=c);f?await this.connectStream(f,{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 f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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,a=t.toolCall?.name;if(!r||!a){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof n=="string"?void 0:n;if(s===void 0&&typeof n=="string"){let c=t.toolCall?.args,f=Array.isArray(c?.questions)?c.questions:[];if(f.length===1){let g=typeof f[0]?.question=="string"?f[0].question:"";g&&(s={[g]:n})}}this.markAskUserQuestionResolved(t,s),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=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(([f,g])=>`${f}: ${Array.isArray(g)?g.join(", "):g}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=s??{};d.forEach((f,g)=>{let m=typeof f?.question=="string"?f.question:"";if(!m)return;let b=c[m],w=Array.isArray(b)?b.join(", "):typeof b=="string"?b:"";this.appendMessage({id:`ask-user-q-${l}-${g}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${g}`,role:"user",content:w||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[a]:n});if(!c.ok){let f=await c.json().catch(()=>null);throw new Error(f?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let f=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,f||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 a=this.webMcpEpoch;queueMicrotask(()=>{a===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!==On?!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(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},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=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let f=`${t}:${c}`;if(this.webMcpInflightKeys.has(f)||this.webMcpResolvedKeys.has(f)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(f),o.push(f);let g=this.markWebMcpToolRunning(p),m=p.agentMetadata?.webMcpToolCallId??d;if(d===On)return{dedupeKey:f,resumeKey:m,output:rd(),toolMessage:p,startedAt:g,completedAt:Date.now()};let b=new AbortController;this.webMcpResolveControllers.add(b),r.push(b);let w=this.client.executeWebMcpToolCall(d,p.toolCall?.args,b.signal),T;if(!w)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await w}catch(L){let A=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return A||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,fs(A?"Aborted by cancel()":dh(L)),g),this.webMcpInflightKeys.delete(f),null}return b.signal.aborted?(this.markWebMcpToolComplete(p,fs("Aborted by cancel()"),g),this.webMcpInflightKeys.delete(f),null):{dedupeKey:f,resumeKey:m,output:T,toolMessage:p,startedAt:g,completedAt:Date.now()}})),l=[];try{if(l=s.filter(c=>c!==null),l.length===0)return;let p={};for(let c of l)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:a.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of l)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===On?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let c of l)this.markWebMcpToolComplete(c.toolMessage,fs("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(a),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(w){this.callbacks.onError?.(w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(b)}return}let a=`${n}:${r}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let d=o===On,c=t.toolCall?.args,f=d?null:this.client.executeWebMcpToolCall(o,c,p),g="execute",m=s;try{let b;if(d?b=rd():f?b=await f:b={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),p.aborted){this.markWebMcpToolComplete(t,fs("Aborted by cancel()"),s);return}let w=t.agentMetadata?.webMcpToolCallId??o;g="resume",await this.resumeWithToolOutput(n,w,b,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,b,s,m,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(b){let w=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));(g==="execute"||w||p.aborted)&&this.markWebMcpToolComplete(t,fs(w||p.aborted?"Aborted by cancel()":dh(b)),s),w||this.callbacks.onError?.(b instanceof Error?b:new Error(String(b)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let a=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!a.ok){let s=await a.json().catch(()=>null);throw new Error(s?.error??`Resume failed: ${a.status}`)}r?.onHttpOk?.(),a.body?await this.connectStream(a.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=zn(this.config.features?.artifacts,t),r=rs(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}:{}}),a=this.messages.find(s=>s.id===n);if(a){a.rawContent=r,a.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(s=>s.id===`artifact-ref-${n.id}`);if(!o)continue;let r=zn(this.config.features?.artifacts,n),a=rs(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!==a&&(o.rawContent=a,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(()=>(ch(),lh)).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=>fd(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=Fo(),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(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=dd(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(a=>a.id===t);if(!n||n.role!=="assistant")return;let o=dd(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,a)=>{if(a!==o)return r;let s={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(s.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(s.agentMetadata={...s.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,f=n.approval;s.approval={...c,...f,executionId:f.executionId||c.executionId,toolName:f.toolName||c.toolName,description:f.description||c.description,toolType:f.toolType??c.toolType,reason:f.reason??c.reason,parameters:f.parameters??c.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(l&&ph(l)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,f=this.webMcpInflightKeys.has(c),g=this.webMcpResolvedKeys.has(c),m=r.toolCall?.name,b=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&m!==void 0&&ph(m)&&r.toolCall?.status==="complete";(f||g||b)&&(s.agentMetadata={...s.agentMetadata??{},awaitingLocalTool:!1},s.toolCall=r.toolCall,s.streaming=r.streaming)}return s}),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(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(a)&&r!==a)return r-a;let s=n.sequence??0,l=o.sequence??0;return s!==l?s-l:n.id.localeCompare(o.id)})}};var md=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var gd=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var hd=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var yd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var bd=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var xd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var vd=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Cd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var wd=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Ad=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var Sd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var Md=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var Td=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var Ed=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var kd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var qi=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}],["path",{d:"M18 17V9"}],["path",{d:"M13 17V5"}],["path",{d:"M8 17v-3"}]];var Ld=[["path",{d:"M20 6 9 17l-5-5"}]];var Pd=[["path",{d:"m6 9 6 6 6-6"}]];var Rd=[["path",{d:"m15 18-6-6 6-6"}]];var Id=[["path",{d:"m9 18 6-6-6-6"}]];var Wd=[["path",{d:"m18 15-6-6-6 6"}]];var Vi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var zi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var Hd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var Bd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var Dd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var $i=[["path",{d:"m18 16 4-4-4-4"}],["path",{d:"m6 8-4 4 4 4"}],["path",{d:"m14.5 4-5 16"}]];var Fd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Od=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Nd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var _d=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var ji=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Gi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Ud=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var qd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var Vd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var zd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var $d=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var jd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Gd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Kd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Xd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Jd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Qd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Yd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Ki=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Zd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var ep=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var tp=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var np=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var op=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var rp=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Xi=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var ap=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var sp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var ip=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var lp=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var cp=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}],["path",{d:"M9 18h6"}],["path",{d:"M10 22h4"}]];var dp=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var Ji=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var pp=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var up=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var fp=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var mp=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var gp=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var hp=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var yp=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var bp=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var xp=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var vp=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Cp=[["path",{d:"M5 12h14"}]];var wp=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Ap=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Sp=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var Mp=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var Tp=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var Qi=[["path",{d:"M13 21h8"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}]];var Ep=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var kp=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var Lp=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var Pp=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var Rp=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var Ip=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var Wp=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var Hp=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var Bp=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var Dp=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var Fp=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Op=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Np=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var _p=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Up=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Yi=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var qp=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Vp=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var zp=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var $p=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Zi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var jp=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Gp=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Kp=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Xp=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Jp=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Qp=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Yp=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Zp=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var eu=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var tu=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var el=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var nu=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var ou=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var ru=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var au=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var su=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var iu=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var lu=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var cu=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var yC={activity:md,"arrow-down":gd,"arrow-up":xd,"arrow-up-right":bd,bot:Sd,"chevron-down":Pd,"chevron-up":Wd,"chevron-right":Id,"chevron-left":Rd,check:Ld,clipboard:Bd,"clipboard-copy":Hd,"code-xml":$i,copy:Fd,file:Gd,"file-code":zd,"file-spreadsheet":$d,"file-text":jd,"image-plus":ap,loader:pp,"loader-circle":Ji,mic:xp,paperclip:Mp,"refresh-cw":Wp,search:Dp,send:Fp,"shield-alert":_p,"shield-check":Up,"shield-x":Yi,square:jp,"thumbs-down":Qp,"thumbs-up":Yp,upload:ou,"volume-2":au,x:lu,user:ru,mail:fp,phone:Lp,calendar:Ed,clock:Dd,building:Md,"map-pin":mp,lock:up,key:lp,"credit-card":Od,"at-sign":vd,hash:tp,globe:ep,link:dp,"circle-check":Vi,"circle-x":zi,"triangle-alert":el,info:ip,ban:Cd,shield:qp,"arrow-left":hd,"arrow-right":yd,"external-link":qd,ellipsis:Gi,"ellipsis-vertical":ji,menu:hp,house:Xi,plus:Rp,minus:Cp,pencil:Ep,"pen-line":Qi,trash:tu,"trash-2":eu,save:Bp,download:_d,share:Np,funnel:Ki,settings:Op,"rotate-cw":Hp,maximize:gp,minimize:vp,"shopping-cart":zp,"shopping-bag":Vp,package:Sp,truck:nu,tag:Jp,gift:Zd,receipt:Ip,wallet:iu,store:Kp,"dollar-sign":Nd,percent:kp,play:Pp,pause:Tp,"volume-x":su,camera:kd,image:sp,film:Xd,headphones:np,"message-circle":yp,"message-square":bp,bell:wd,heart:op,star:Gp,eye:Vd,"eye-off":Ud,bookmark:Ad,"calendar-days":Td,history:rp,timer:Zp,folder:Yd,"folder-open":Qd,files:Kd,"chart-column":qi,sparkles:Zi,zap:cu,sun:Xp,moon:Ap,flag:Jd,lightbulb:cp,monitor:wp,smartphone:$p},ae=(e,t=24,n="currentColor",o=2)=>{let r=yC[e];return r?bC(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 bC(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(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],l=a[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(l).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var tl={allowedTypes:co,maxFileSize:10*1024*1024,maxFiles:4};function xC(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function vC(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 Ar=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??tl.allowedTypes,maxFileSize:t.maxFileSize??tl.maxFileSize,maxFiles:t.maxFiles??tl.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:tl.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=oh(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 nh(n),a=Ni(n)?URL.createObjectURL(n):null,s={id:xC(),file:n,previewUrl:a,contentPart:r};this.attachments.push(s),this.renderPreview(s)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(a=>a.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=Ni(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 s=v("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=v("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let l=vC(t.file.type),p=ae(l,20,"var(--persona-muted, #6b7280)",1.5);p&&s.appendChild(p);let d=v("span");d.textContent=rh(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",s.appendChild(d),o.appendChild(s)}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 a=ae("x",10,"var(--persona-text-inverse, #ffffff)",2);a?r.appendChild(a):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",s=>{s.preventDefault(),s.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 uh=/\s/;function CC(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
24
+ `:o===""||uh.test(o)}function wC(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let a=t-1;for(;a>=0;){let s=e[a];if(s===n)return CC(e,a,o)?{triggerIndex:a,query:e.slice(a+1,t)}:null;if(s===`
25
+ `||s==="\uFFFC"||!r&&uh.test(s))return null;a--}return null}function fh(e,t,n){for(let o of n){let r=wC(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function mh(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function gh(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 Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,nl=Ut+1;var AC=8,SC=8,du=10,pu=new WeakMap,hh=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,MC=e=>{let t=e.getRootNode?.();return hh(t)?t:e.ownerDocument.body},uu=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function qt(e){pu.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:a=AC,viewportPadding:s=SC}=e,l=()=>t.ownerDocument,p=()=>l().defaultView??window,d=null,c=null,f=null,g=!1,m=!1,b=!1,w=()=>(typeof o=="function"?o():o).trim(),T=()=>{f?.(),f=null,d?.remove(),d=null,c=null},L=()=>{if(!d)return;let $=l(),E=p(),G=t.getBoundingClientRect(),Q=d.getBoundingClientRect(),Z=$.documentElement.clientWidth||E.innerWidth,J=$.documentElement.clientHeight||E.innerHeight,fe=Z-s-Q.width,ne=G.left+G.width/2-Q.width/2,ge=uu(ne,s,fe),ie=G.top-s,ue=J-s-G.bottom,oe=Q.height+a,me=ie>=oe||ie>=ue?"top":"bottom",Se=me==="top"?G.top-a-Q.height:G.bottom+a,Ce=J-s-Q.height,Be=uu(Se,s,Ce),ut=G.left+G.width/2,Je=Math.max(du,Q.width-du),Qe=uu(ut-ge,du,Je);d.dataset.placement=me,d.style.left=`${ge}px`,d.style.top=`${Be}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${Qe}px`)},A=()=>{if(b||!r||d||!t.isConnected)return;let $=w(),E=MC(t);if(!$||!E)return;let G=l(),Q=p();d=G.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(nl),c=G.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=$,d.appendChild(c);let Z=G.createElement("span");Z.className="persona-control-tooltip__arrow",d.appendChild(Z),E.appendChild(d),L(),d.dataset.state="open";let J=()=>{if(!t.isConnected){T();return}c&&(c.textContent=w()),L()};Q.addEventListener("scroll",J,!0),Q.addEventListener("resize",J);let fe=t.getRootNode(),ne=hh(fe)?fe:G.documentElement,ge=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||T()});ge?.observe(ne,{childList:!0,subtree:!0}),f=()=>{Q.removeEventListener("scroll",J,!0),Q.removeEventListener("resize",J),ge?.disconnect()}},S=()=>{g||m?A():T()},C=()=>{let $=p();(!$.matchMedia||!$.matchMedia("(hover: none)").matches)&&(g=!0,S())},M=()=>{g=!1,S()},P=()=>{m=!0,S()},R=()=>{m=!1,S()},F=$=>{$.key==="Escape"&&(g=!1,m=!1,T())};n.addEventListener("mouseenter",C),n.addEventListener("mouseleave",M),t.addEventListener("focus",P),t.addEventListener("blur",R),t.addEventListener("keydown",F);let O={get isOpen(){return d!==null},show:A,hide:T,reposition:L,destroy:()=>{b||(b=!0,T(),n.removeEventListener("mouseenter",C),n.removeEventListener("mouseleave",M),t.removeEventListener("focus",P),t.removeEventListener("blur",R),t.removeEventListener("keydown",F),pu.delete(t))}};return pu.set(t,O),O}function yh(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,a=Math.round(r*.6),s=t.buttonIconName??"plus",l=t.buttonTooltipText??"Add context",p=v("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":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=ae(s,a,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),n()}),p.appendChild(d),qt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??l}),{button:d,wrapper:p}}var{setLoader:TC,load:EC}=Zr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")}),bh=TC,fu=EC;var{setLoader:kC,load:LC}=Zr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0}),xh=kC,vh=LC;function ms(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=ke("span",{className:Fn("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=ae(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(ke("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Ch(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=gh(t).filter(S=>S.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(S=>S.sources.some(C=>typeof C.matchCommand=="function")),r=S=>o.some(C=>C.trigger?C.position==="line-start"?S.split(`
26
+ `).some(P=>P.startsWith(C.trigger)):(C.position==="anywhere"?S:S.split(`
27
+ `)[0]).startsWith(C.trigger):!1),a=(S,C)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:C}))}catch{}},s=ke("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,d=e.textarea,c=null,f=null,g=null,m=null,b=()=>{if(l)return Promise.resolve(l);if(p)return p;let S=fu().then(C=>(l=C.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:s,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:A,emit:a}),l)).catch(C=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",C),p===S&&(p=null),null));return p=S,S},w=()=>{vh().then(S=>{let C=S.mountInlineComposer({textarea:e.textarea,renderToken:P=>ms(P,{render:t.renderMentionToken}),onMentionRemoved:P=>l?.untrackMention(P)});c=C.input,f=C.destroy;let M=d;M.replaceWith(C.element),d=C.element,m={next:C.element,prev:M},g?.(C.element,M),l?l.rebindComposer(C.input):p&&p.then(P=>P?.rebindComposer(C.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&w();let T=[],L=new Map;for(let S of n){if(!S.showButton)continue;let C=yh({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{b().then(M=>M?.openMenu(S.trigger))}});T.push(C),L.set(S.trigger,C.button)}let A=(S,C,M)=>{let P=L.get(C);P&&(P.setAttribute("aria-expanded",S?"true":"false"),S?P.setAttribute("aria-controls",M):P.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(S=>S.wrapper),contextRow:s,handleInput:S=>{if(l){l.handleInput();return}if(!mh(S))return;let C=d,M=C.selectionStart??0;fh(C.value,M,n)&&b().then(P=>P?.handleInput())},handleKeydown:S=>{if(l?.isMenuOpen())return l.handleKeydown(S);if(S.key==="Backspace"&&l?.hasMentions()&&!m){let C=d,M=C.selectionStart===0&&C.selectionEnd===0;if((C.value.length===0||M)&&l.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(l??await b())?.dispatchInlineCommand(S)??null:null,clear:()=>l?.clear(),prefetch:()=>{fu().catch(()=>{})},onComposerSwap:S=>{g=S,m&&S(m.next,m.prev)},destroy:()=>{l?.destroy(),f?.();for(let S of T)S.wrapper.remove();s.remove()}}}var wh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function gs(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];wh(a)&&wh(r)?n[o]=gs(a,r):n[o]=r}return n}var mn="min(440px, calc(100vw - 24px))",ol="440px",PC={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:mn,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)"},rt={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:PC,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 Ah(e,t){if(!(!e&&!t))return e?t?gs(e,t):e:t}function da(e){return e?{...rt,...e,theme:Ah(rt.theme,e.theme),darkTheme:Ah(rt.darkTheme,e.darkTheme),launcher:{...rt.launcher,...e.launcher,dock:{...rt.launcher?.dock,...e.launcher?.dock},clearChat:{...rt.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...rt.copy,...e.copy},sendButton:{...rt.sendButton,...e.sendButton},statusIndicator:{...rt.statusIndicator,...e.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=rt.features?.artifacts,n=e.features?.artifacts,o=rt.features?.scrollToBottom,r=e.features?.scrollToBottom,a=rt.features?.scrollBehavior,s=e.features?.scrollBehavior,l=rt.features?.streamAnimation,p=e.features?.streamAnimation,d=rt.features?.askUserQuestion,c=e.features?.askUserQuestion,f=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},g=o===void 0&&r===void 0?void 0:{...o,...r},m=a===void 0&&s===void 0?void 0:{...a,...s},b=l===void 0&&p===void 0?void 0:{...l,...p},w=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...rt.features,...e.features,...g!==void 0?{scrollToBottom:g}:{},...m!==void 0?{scrollBehavior:m}:{},...f!==void 0?{artifacts:f}:{},...b!==void 0?{streamAnimation:b}:{},...w!==void 0?{askUserQuestion:w}:{}}})(),suggestionChips:e.suggestionChips??rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...rt.layout,...e.layout,header:{...rt.layout?.header,...e.layout?.header},messages:{...rt.layout?.messages,...e.layout?.messages,avatar:{...rt.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...rt.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...rt.layout?.slots,...e.layout?.slots}},markdown:{...rt.markdown,...e.markdown,options:{...rt.markdown?.options,...e.markdown?.options}},messageActions:{...rt.messageActions,...e.messageActions}}:rt}var rl="16px",al="transparent",mu={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"}},gu={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"}},hu={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:mn,maxWidth:ol,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:rl,canvasBackground:al},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 en(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."))?en(e,o):o}function sl(e){let t={};function n(o,r){for(let[a,s]of Object.entries(o)){let l=`${r}.${a}`;if(typeof s=="string"){let p=en(e,s);p!==void 0&&(t[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&n(s,l)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function yu(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 Sh(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];a&&typeof a=="object"&&!Array.isArray(a)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Sh(a,r):n[o]=r}return n}function RC(e,t){return t?Sh(e,t):e}function hs(e,t={}){let n={palette:mu,semantic:gu,components:hu},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:RC(n.components,e?.components)};if(t.validate!==!1){let r=yu(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(a=>a.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function il(e){let t=sl(e),n={};for(let[E,G]of Object.entries(t)){let Q=E.replace(/\./g,"-");n[`--persona-${Q}`]=G.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"]??rl,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??al,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"],a=n["--persona-components-introCard-shadow"],s=(!r||r==="transparent"||r==="none")&&(!a||a==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=s&&l==="1.5rem"?"1.5rem 0":l,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 f=n["--persona-components-markdown-heading-h2-fontWeight"];f&&(n["--persona-md-h2-weight"]=f);let g=n["--persona-components-markdown-prose-fontFamily"];g&&g!=="inherit"&&(n["--persona-md-prose-font-family"]=g),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 m=e.components,b=m?.iconButton;b&&(b.background&&(n["--persona-icon-btn-bg"]=b.background),b.border&&(n["--persona-icon-btn-border"]=b.border),b.color&&(n["--persona-icon-btn-color"]=b.color),b.padding&&(n["--persona-icon-btn-padding"]=b.padding),b.borderRadius&&(n["--persona-icon-btn-radius"]=b.borderRadius),b.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=b.hoverBackground),b.hoverColor&&(n["--persona-icon-btn-hover-color"]=b.hoverColor),b.activeBackground&&(n["--persona-icon-btn-active-bg"]=b.activeBackground),b.activeBorder&&(n["--persona-icon-btn-active-border"]=b.activeBorder));let w=m?.labelButton;w&&(w.background&&(n["--persona-label-btn-bg"]=w.background),w.border&&(n["--persona-label-btn-border"]=w.border),w.color&&(n["--persona-label-btn-color"]=w.color),w.padding&&(n["--persona-label-btn-padding"]=w.padding),w.borderRadius&&(n["--persona-label-btn-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-label-btn-hover-bg"]=w.hoverBackground),w.fontSize&&(n["--persona-label-btn-font-size"]=w.fontSize),w.gap&&(n["--persona-label-btn-gap"]=w.gap));let T=m?.toggleGroup;T&&(T.gap&&(n["--persona-toggle-group-gap"]=T.gap),T.borderRadius&&(n["--persona-toggle-group-radius"]=T.borderRadius));let L=m?.artifact;if(L?.toolbar){let E=L.toolbar;E.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=E.iconHoverColor),E.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=E.iconHoverBackground),E.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=E.iconPadding),E.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=E.iconBorderRadius),E.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=E.iconBorder),E.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=E.toggleGroupGap),E.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=E.toggleBorderRadius),E.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=E.toggleGroupPadding),E.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=E.toggleGroupBorder),E.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=E.toggleGroupBorderRadius),E.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=en(e,E.toggleGroupBackground)??E.toggleGroupBackground),E.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=E.copyBackground),E.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=E.copyBorder),E.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=E.copyColor),E.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=E.copyBorderRadius),E.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=E.copyPadding),E.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=E.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??E.copyMenuBackground),E.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=E.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??E.copyMenuBorder),E.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=E.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??E.copyMenuShadow),E.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=E.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??E.copyMenuBorderRadius),E.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=E.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??E.copyMenuItemHoverBackground),E.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=E.iconBackground),E.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=E.toolbarBorder)}if(L?.tab){let E=L.tab;E.background&&(n["--persona-artifact-tab-bg"]=E.background),E.activeBackground&&(n["--persona-artifact-tab-active-bg"]=E.activeBackground),E.activeBorder&&(n["--persona-artifact-tab-active-border"]=E.activeBorder),E.borderRadius&&(n["--persona-artifact-tab-radius"]=E.borderRadius),E.textColor&&(n["--persona-artifact-tab-color"]=E.textColor),E.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=E.hoverBackground),E.listBackground&&(n["--persona-artifact-tab-list-bg"]=E.listBackground),E.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=E.listBorderColor),E.listPadding&&(n["--persona-artifact-tab-list-padding"]=E.listPadding)}if(L?.pane){let E=L.pane;if(E.toolbarBackground){let G=en(e,E.toolbarBackground)??E.toolbarBackground;n["--persona-artifact-toolbar-bg"]=G}}if(L?.card){let E=L.card;E.background&&(n["--persona-artifact-card-bg"]=E.background),E.border&&(n["--persona-artifact-card-border"]=E.border),E.borderRadius&&(n["--persona-artifact-card-radius"]=E.borderRadius),E.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=E.hoverBackground),E.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=E.hoverBorderColor)}if(L?.inline){let E=L.inline;E.background&&(n["--persona-artifact-inline-bg"]=en(e,E.background)??E.background),E.border&&(n["--persona-artifact-inline-border"]=E.border),E.borderRadius&&(n["--persona-artifact-inline-radius"]=E.borderRadius),E.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=en(e,E.chromeBackground)??E.chromeBackground),E.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=en(e,E.chromeBorder)??E.chromeBorder),E.titleColor&&(n["--persona-artifact-inline-title-color"]=en(e,E.titleColor)??E.titleColor),E.mutedColor&&(n["--persona-artifact-inline-muted-color"]=en(e,E.mutedColor)??E.mutedColor),E.frameHeight&&(n["--persona-artifact-inline-frame-height"]=E.frameHeight)}let A=m?.code;A&&(A.keywordColor&&(n["--persona-code-keyword-color"]=A.keywordColor),A.stringColor&&(n["--persona-code-string-color"]=A.stringColor),A.commentColor&&(n["--persona-code-comment-color"]=A.commentColor),A.numberColor&&(n["--persona-code-number-color"]=A.numberColor),A.tagColor&&(n["--persona-code-tag-color"]=A.tagColor),A.attrColor&&(n["--persona-code-attr-color"]=A.attrColor),A.propertyColor&&(n["--persona-code-property-color"]=A.propertyColor),A.lineNumberColor&&(n["--persona-code-line-number-color"]=A.lineNumberColor),A.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=A.gutterBorderColor),A.background&&(n["--persona-code-bg"]=en(e,A.background)??A.background));let S=n["--persona-surface"],C=n["--persona-container"],M=n["--persona-palette-colors-gray-100"]??"#f3f4f6",P=n["--persona-palette-colors-gray-200"]??"#e5e7eb",R=n["--persona-palette-colors-gray-300"]??"#d1d5db",F=!C||C===S,O=F?M:C,$=F?P:C;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??O,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??$,F&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??R),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??O,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??O,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??O,n}var Mh={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 IC={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"}}},Th=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ys=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",WC=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":ys()},ll=e=>WC(e),HC=e=>hs(e),BC=e=>hs({...e,palette:{...e?.palette,colors:{...IC.colors,...e?.palette?.colors}}},{validate:!1}),Uo=e=>{let t=ll(e),n=Th(e?.theme),o=Th(e?.darkTheme);return t==="dark"?BC(gs(n??{},o??{})):HC(n)},DC=e=>il(e),Sr=(e,t)=>{let n=Uo(t),o=DC(n);for(let[r,a]of Object.entries(o))e.style.setProperty(r,a);e.setAttribute("data-persona-color-scheme",ll(t))},pa=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(ys())});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(ys());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 qo=(e,t)=>e?.layout?.contentMaxWidth??(t?e?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function $n(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function Eh(e){let t=$n(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function cl(e){if(typeof e!="string")return"";let t=e.indexOf(`
28
28
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
29
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ja(e){let t=ig(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 Lo(e){switch(ja(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=ig(e.path);return t?t.toUpperCase():"File"}}}function lg(e){let t=e.markdown??"";return e.file?{filename:Dn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Fi(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Ep="http://www.w3.org/2000/svg";function dg(e){let t=document.createElementNS(Ep,"svg");t.setAttribute("class",Kn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Ep,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Ep,"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 Po=(e,t,n)=>{let o=n;for(let r of t){let a=b("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function cg(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)),Po(e,t,0)}var kp="persona-artifact-status-label",pg="persona-artifact-status-detail",ug="data-artifact-status-label",Lp=new Map,fg=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function _r(e){e&&Lp.delete(e)}function Kx(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Lo(t):e.artifactType==="component"?"Component":"Document"}function Ur(e,t,n){let o=Kx(e),r=`Generating ${o.toLowerCase()}...`,a=t?.statusLabel;if(typeof a=="string")return{label:a};if(typeof a!="function")return{label:r};let s=e.id,l=Lp.get(s);e.status!=="complete"&&l===void 0&&(l=fg(),Lp.set(s,l));let p=l===void 0?0:Math.max(0,fg()-l),c=e.artifactType==="component",d=!c&&typeof e.markdown=="string"?e.markdown:"",u=c?0:d.length,g=c||d===""?0:d.split(`
30
- `).length,f=e.artifactType==="markdown"?e.file:void 0,h={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:f,chars:u,lines:g,elapsedMs:p,content:()=>c?"":d,surface:n};try{let A=a(h);return typeof A=="string"?{label:A}:A&&typeof A=="object"&&typeof A.label=="string"?{label:A.label,detail:typeof A.detail=="string"?A.detail:void 0}:{label:r}}catch{return{label:r}}}function Xx(e){e.className=kp,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 ar(e,t,n){let o=e.querySelector(`:scope > .${kp}`);o||(o=b("span",kp),e.appendChild(o)),o.getAttribute(ug)!==t.label&&(Xx(o),cg(o,t.label,n),o.setAttribute(ug,t.label));let r=e.querySelector(`:scope > .${pg}`),a=t.detail;a?(r||(r=b("span",pg),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var Jx={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"},Qx=15e4,Oi={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 Yx(e,t){let n=(e||"").trim().toLowerCase();if(n&&Oi[n])return Oi[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Oi[r])return Oi[r]}}return null}function Ni(e,t){let n=[],o=0,r=0,a=s=>{s>r&&n.push({type:"plain",value:e.slice(r,s)})};for(;o<e.length;){let s=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);if(p&&p.index===o&&p[0].length>0){a(o);let c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var Zx=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"]),ev=[{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=>Zx.has(e)?"keyword":"plain"}];function mg(e){return Ni(e,ev)}var tv=[{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 nv(e){let t=Ni(e,tv);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 ov=[{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 gg(e){let t=Ni(e,ov),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 s=o+1;for(;s<t.length&&t[s].value.trim()==="";)s+=1;let l=t[s];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let a=r.value.replace(/\s+$/,"");a&&(n=a[a.length-1])}return t}var rv=[{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 av(e){let t=[],n=(a,s)=>{s&&t.push({type:a,value:s})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let s=e.indexOf("-->",r+4),l=s===-1?o:s+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let s=e.indexOf(">",r),l=s===-1?o:s+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let s=e.indexOf(">",r),l=s===-1?o:s+1,p=e.slice(r,l);for(let d of Ni(p,rv))t.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),g=new RegExp("</\\s*"+d+"\\s*>","i").exec(e.slice(r)),f=g?r+g.index:o,h=e.slice(r,f),A=d==="script"?mg(h):gg(h);for(let E of A)t.push(E);r=f}continue}let a=e.indexOf("<",r);if(a===r)n("plain",e[r]),r+=1;else{let s=a===-1?o:a;n("plain",e.slice(r,s)),r=s}}return t}function sv(e,t){switch(t){case"html":return av(e);case"css":return gg(e);case"js":return mg(e);case"json":return nv(e)}}function iv(e){let t=lm(),n=b("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=Jx[r];if(s){let l=b("span",s);l.textContent=a,n.appendChild(l)}else n.appendChild(document.createTextNode(a))};for(let r of e){let a=r.value.split(`
29
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Mr(e){let t=Eh(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 Vo(e){switch(Mr(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=Eh(e.path);return t?t.toUpperCase():"File"}}}function kh(e){let t=e.markdown??"";return e.file?{filename:$n(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:cl(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var bu="http://www.w3.org/2000/svg";function Lh(e){let t=document.createElementNS(bu,"svg");t.setAttribute("class",Fn("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(bu,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(bu,"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 zo=(e,t,n)=>{let o=n;for(let r of t){let a=v("span","persona-tool-char");a.style.setProperty("--char-index",String(o)),a.textContent=r===" "?"\xA0":r,e.appendChild(a),o++}return o};function Ph(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)),zo(e,t,0)}var xu="persona-artifact-status-label",Rh="persona-artifact-status-detail",Ih="data-artifact-status-label",vu=new Map,Wh=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function ua(e){e&&vu.delete(e)}function FC(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?Vo(t):e.artifactType==="component"?"Component":"Document"}function fa(e,t,n){let o=FC(e),r=`Generating ${o.toLowerCase()}...`,a=t?.statusLabel;if(typeof a=="string")return{label:a};if(typeof a!="function")return{label:r};let s=e.id,l=vu.get(s);e.status!=="complete"&&l===void 0&&(l=Wh(),vu.set(s,l));let p=l===void 0?0:Math.max(0,Wh()-l),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",f=d?0:c.length,g=d||c===""?0:c.split(`
30
+ `).length,m=e.artifactType==="markdown"?e.file:void 0,b={artifactId:s,artifactType:e.artifactType,title:e.title,typeLabel:o,file:m,chars:f,lines:g,elapsedMs:p,content:()=>d?"":c,surface:n};try{let w=a(b);return typeof w=="string"?{label:w}:w&&typeof w=="object"&&typeof w.label=="string"?{label:w.label,detail:typeof w.detail=="string"?w.detail:void 0}:{label:r}}catch{return{label:r}}}function OC(e){e.className=xu,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 > .${xu}`);o||(o=v("span",xu),e.appendChild(o)),o.getAttribute(Ih)!==t.label&&(OC(o),Ph(o,t.label,n),o.setAttribute(Ih,t.label));let r=e.querySelector(`:scope > .${Rh}`),a=t.detail;a?(r||(r=v("span",Rh),e.appendChild(r)),r.textContent!==a&&(r.textContent=a)):r&&r.remove()}var NC={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"},_C=15e4,dl={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 UC(e,t){let n=(e||"").trim().toLowerCase();if(n&&dl[n])return dl[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(dl[r])return dl[r]}}return null}function pl(e,t){let n=[],o=0,r=0,a=s=>{s>r&&n.push({type:"plain",value:e.slice(r,s)})};for(;o<e.length;){let s=!1;for(let l of t){l.re.lastIndex=o;let p=l.re.exec(e);if(p&&p.index===o&&p[0].length>0){a(o);let d=l.map?l.map(p[0]):l.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,s=!0;break}}s||(o+=1)}return a(e.length),n}var qC=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"]),VC=[{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=>qC.has(e)?"keyword":"plain"}];function Hh(e){return pl(e,VC)}var zC=[{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 $C(e){let t=pl(e,zC);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 jC=[{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 Bh(e){let t=pl(e,jC),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 s=o+1;for(;s<t.length&&t[s].value.trim()==="";)s+=1;let l=t[s];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let a=r.value.replace(/\s+$/,"");a&&(n=a[a.length-1])}return t}var GC=[{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 KC(e){let t=[],n=(a,s)=>{s&&t.push({type:a,value:s})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let s=e.indexOf("-->",r+4),l=s===-1?o:s+3;n("comment",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&e[r+1]==="!"){let s=e.indexOf(">",r),l=s===-1?o:s+1;n("tag",e.slice(r,l)),r=l;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let s=e.indexOf(">",r),l=s===-1?o:s+1,p=e.slice(r,l);for(let c of pl(p,GC))t.push(c);r=l;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),g=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),m=g?r+g.index:o,b=e.slice(r,m),w=c==="script"?Hh(b):Bh(b);for(let T of w)t.push(T);r=m}continue}let a=e.indexOf("<",r);if(a===r)n("plain",e[r]),r+=1;else{let s=a===-1?o:a;n("plain",e.slice(r,s)),r=s}}return t}function XC(e,t){switch(t){case"html":return KC(e);case"css":return Bh(e);case"js":return Hh(e);case"json":return $C(e)}}function JC(e){let t=kg(),n=v("span","persona-code-line"),o=(r,a)=>{if(!a)return;let s=NC[r];if(s){let l=v("span",s);l.textContent=a,n.appendChild(l)}else n.appendChild(document.createTextNode(a))};for(let r of e){let a=r.value.split(`
31
31
  `);for(let s=0;s<a.length;s+=1)s>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
32
- `)),n=b("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function hg(e,t,n){let o=e.length<=Qx?Yx(t,n):null,r=o?sv(e,o):[{type:"plain",value:e}];return iv(r)}function Ro(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=b("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Pi)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");s.appendChild(E)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let E=oe(f.icon,16,"currentColor",1.5);E&&h.appendChild(E)}let A=document.createElement("span");A.textContent=f.label,h.appendChild(A),h.addEventListener("click",E=>{E.stopPropagation(),d(),n(f.id)}),s.appendChild(h)}let l=null;function p(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function c(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){s.classList.add("persona-hidden"),l?.(),l=null}function u(){s.classList.contains("persona-hidden")?c():d()}function g(){d(),s.remove()}return a&&a.appendChild(s),{element:s,show:c,hide:d,toggle:u,destroy:g}}function Mt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=b("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=oe(t,o??16,"currentColor",r??2);if(c&&p.appendChild(c),s&&p.addEventListener("click",s),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Zn(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,s&&(c+=" "+s);let d=b("button",c);if(d.type="button",d.setAttribute("aria-label",n),t){let g=oe(t,a??14,"currentColor",2);g&&d.appendChild(g)}let u=b("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[g,f]of Object.entries(p))d.setAttribute(g,f);return d}function qr(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=b("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===s?"true":"false")}for(let d of t){let u;d.icon?u=Mt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{s=d.id,p(),o(d.id)}}):(u=b("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{s=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===s?"true":"false"),l.push({id:d.id,btn:u}),a.appendChild(u)}function c(d){s=d,p()}return{element:a,setSelected:c}}function _i(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,c=b("div","persona-combo-btn"+(l?" "+l:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let d=b("span","persona-combo-btn-label");d.textContent=t,c.appendChild(d);let u=oe(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=Ro({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:a,portal:s});return s||c.appendChild(g.element),c.addEventListener("click",f=>{f.stopPropagation();let h=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",h?"false":"true"),g.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let f=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var Ui="persona-artifact-custom-action-btn";function Vr(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 "+Ui+(n?" persona-artifact-doc-copy-btn":"");o=b("button",r)}else{let r="persona-icon-btn "+Ui+(n?" persona-artifact-doc-icon-btn":"");o=b("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=b("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=Zn({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-copy-btn":"")}):o=Mt({icon:e.icon,label:e.label,className:Ui+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function Ga(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 yg(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?Dn(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,c=n?Lo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),a&&d.setAttribute("data-open-artifact",a);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 g=document.createElement("div");g.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 h=document.createElement("div");if(h.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",h.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let A=t?.config?.features?.artifacts,E={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},k=Ur(E,A,"card");ar(h,k,A)}else a&&_r(a),h.textContent=c;if(g.append(f,h),d.append(u,g),s==="complete"){let A=t?.config?.features?.artifacts?.cardActions;if(A&&A.length>0){let k={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let M of A)try{if(M.visible===void 0||M.visible(k)){let S=Vr(M);S.setAttribute("data-artifact-custom-action",M.id),S.className=`${S.className} persona-flex-shrink-0`,d.append(S)}}catch{}}let E=Zn({label:"Download",className:"persona-flex-shrink-0"});E.title=`Download ${r}`,E.setAttribute("data-download-artifact",a),d.append(E)}return d}var qi=(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:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>yg(e,t)});if(l)return l}return yg(e,t)};var Io=new WeakMap;function Pp(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 a=Io.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function wg(e){return Io.has(e)}function lv(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 s=e.componentProps,l=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let a=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:"",...a?{file:a}:{},...r?{presentation:r}:{}}}function bg(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Dn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function dv(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 xg=180,cv=240,pv=.8,uv=300,fv=500,mv="cubic-bezier(0.2, 0, 0, 1)",vg=240,gv=.35;function hv(e,t,n){let{swap:o,onSettled:r}=n,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:xg,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let k of s)k.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let c=Math.abs(t-p),d=Math.round(Math.min(fv,Math.max(uv,cv+c*pv))),u=Math.round(d*gv),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,f=g?g.animate([{opacity:0},{opacity:1}],{duration:vg,delay:u,easing:"ease-out",fill:"backwards"}):null,h=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:d,easing:mv});e.style.height=`${p}px`;let A=!1,E=()=>{A||(A=!0,l(),r())};Promise.allSettled([h.finished,f?.finished].filter(Boolean)).then(E),window.setTimeout(E,Math.max(d,u+vg)+120)},xg)}function yv(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 Ka="--persona-artifact-inline-body-height";function bv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,c,d,u=t?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let g=t?.transition==="none"?"none":"auto",f=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:g,completeDisplay:f}}function Cg(e,t){let n=lv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=yv(o),p=o?.inlineActions??[],c=bv(o),d=c.completeDisplay==="card",u=null,g=n,f=b("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 h=ne=>qi(dv(ne),t),A=ne=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Ka),f.replaceChildren(h(ne)),Io.set(f,le=>{f.replaceChildren(h(le))})};if(d&&n.status==="complete")return A(n),f;let E=Vi(n,{config:t.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),k=b("div","persona-artifact-inline-body");k.appendChild(E.el);let M=ne=>{let le=ne.status!=="complete",Z=le?c.streamingHeight:c.completeHeight,me=typeof Z=="number";me?f.style.setProperty(Ka,`${Z}px`):f.style.removeProperty(Ka);let Ae=!!E.el.querySelector(".persona-code-pre"),we=!!E.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");k.classList.toggle("persona-artifact-content-flush",Ae),k.classList.toggle("persona-artifact-inline-body--sized",me&&we),k.classList.toggle("persona-artifact-inline-body--cap",!le&&!we&&typeof c.completeHeight=="number")},S=n.status,C=(ne,le)=>{S!=="complete"&&ne.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Ka,`${c.completeHeight}px`):f.style.removeProperty(Ka),Sg(k,le?.suppressTransition?"none":c.transition,ne.id,()=>{E.update(ne),M(ne)})):E.update(ne),M(ne),S=ne.status};M(n);let T=c.overflow==="clip"&&s&&!!n.id;if(T&&(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 ${bg(n).title} in panel`)),!r)return f.appendChild(k),Io.set(f,C),f;let W=b("div","persona-artifact-inline-chrome");W.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=b("div","persona-artifact-inline-chrome-lead"),D=b("span","persona-flex persona-items-center persona-flex-shrink-0"),F=oe("file-text",16,"currentColor",2);F&&D.appendChild(F);let j=b("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=b("span","persona-artifact-inline-type");w.append(D,j,O);let q=b("div","persona-artifact-inline-chrome-actions"),Q=b("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,be=l?qr({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:de(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ne=>{let le=ne==="source"?"source":"rendered";le!==de()&&(u=le,E.update(g),M(g))}}):null,De=a?Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;De&&n.id&&De.setAttribute("data-copy-artifact",n.id);let ie=s?Mt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ie&&n.id&&ie.setAttribute("data-expand-artifact-inline",n.id),q.appendChild(Q),be&&q.appendChild(be.element),De&&q.appendChild(De),ie&&q.appendChild(ie),W.append(w,q),f.append(W,k);let ge=ne=>{let{title:le,typeLabel:Z}=bg(ne);j.textContent=le,j.title=le,T&&k.setAttribute("aria-label",`Open ${le} in panel`);let me=ne.status!=="complete";if(me){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let Ae=Ur(ne,o,"inline-chrome");ar(O,Ae,o)}else _r(ne.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(De&&De.classList.toggle("persona-hidden",me),be){let Ae=ne.artifactType==="markdown"?ne.file:void 0,we=!1;if(!me&&Ae&&c.viewMode!=="source"){let Se=ja(Ae);Se==="markdown"?we=!0:(Se==="html"||Se==="svg")&&(we=o?.filePreview?.enabled!==!1)}be.element.classList.toggle("persona-hidden",!we),be.setSelected(de())}if(Q.replaceChildren(),!me&&p.length>0){let Ae=Ga(ne);if(Ae)for(let we of p)try{if(we.visible===void 0||we.visible(Ae)){let Se=Vr(we,{documentChrome:!0});Se.setAttribute("data-artifact-custom-action",we.id),Se.classList.add("persona-flex-shrink-0"),Q.appendChild(Se)}}catch{}}};return ge(n),Io.set(f,(ne,le)=>{if(d&&S!=="complete"&&ne.status==="complete"){let Z=f.isConnected?f.getBoundingClientRect().height:0;S="complete";let me=ne,Ae=!1,we=Se=>{me=Se,Ae=!0};Io.set(f,we),hv(f,Z,{swap:()=>{A(me),Ae=!1,Io.set(f,we)},onSettled:()=>{Ae?A(me):Io.set(f,Se=>{f.replaceChildren(h(Se))})}});return}(ne.status!=="complete"||ne.id!==g.id)&&(u=null),g=ne,C(ne,le),ge(ne)}),f}var Ag=(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:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Cg(e,t)});if(l)return l}return Cg(e,t)};var Rp=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)})}},Ln=new Rp;Ln.register("PersonaArtifactCard",qi,{bubbleChrome:!1});Ln.register("PersonaArtifactInline",Ag,{bubbleChrome:!1});function Xa(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Fi(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Ip=!1;function xv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Sg(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof r!="function"||Ip||a){o();return}Ip=!0;let s=xv(n);e.style.setProperty("view-transition-name",s);let l=()=>{Ip=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var vv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Cv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function wv(e){let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=b("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 Av(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 Sv=220;function Mv(){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 Tv(e){return`
33
- <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 Ev(e,t,n){let o=b("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=b("div","persona-artifact-frame-loading-indicator");r.appendChild(dg());let a=null;return n.label!==!1&&(a=b("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function kv(e,t,n,o,r,a){let s=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(S=>clearTimeout(S)),c.clear()},u=(S,C)=>{let T=setTimeout(()=>{c.delete(T),S()},C);c.add(T)},g=()=>{s&&s.parentElement&&s.remove(),s=null},f=()=>{if(s||p)return;let S=Ev(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},h=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),u(g,Sv))},A=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",k):t.removeEventListener("load",M)},E=()=>{if(p||(p=!0,A(),d(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?u(h,S):h()};function k(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&E()}function M(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>E()))}return u(f,o.delayMs),u(E,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",k):t.addEventListener("load",M),()=>{p=!0,d(),A(),g()}}function Vi(e,t){let{config:n}=t,o=t.registry??Ln,r=t.bodyLayout,a=n.markdown?Qo(n.markdown):null,s=Lr(n.sanitize),l=e,p=!1,c=ie=>{let ge=Gn()!==null;a&&!ge&&!p&&(p=!0,kr(()=>De(l)));let ne=a?a(ie):Hn(ie);return a&&ge&&s?s(ne):ne},d=b("div","persona-artifact-preview-body"),u=null,g=null,f=null,h=()=>{f&&(f(),f=null),u=null,g=null},A=null,E=null,k=null,M=!1,S=()=>{A=null,E=null,k=null,M=!1},C=null,T=null,W=()=>{C=null,T=null},w=40,D=0,F=ie=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ie()):setTimeout(ie,0),j=ie=>ie.scrollHeight-ie.clientHeight-ie.scrollTop<=w,O=ie=>{if(!r)return;let ge=ie.scrollHeight-ie.clientHeight>1,ne=ie.scrollHeight-ie.clientHeight-ie.scrollTop;ie.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ie.scrollTop>1),ie.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ne>1)},q=ie=>{D||(D=F(()=>{D=0,ie.scrollTop=ie.scrollHeight,O(ie)}))},Q=(ie,ge,ne,le)=>{let Z=!!r,me=ne.id+"|"+(Z?"w":"p");if(!A||k!==me||A.parentElement!==d){h(),W(),d.replaceChildren();let Se=b("pre",vv+" persona-code-pre"),mt=b("code","persona-code");if(Se.appendChild(mt),Z){let We=b("div","persona-artifact-source-window");if(We.appendChild(Se),d.appendChild(We),!(r?.overflow==="clip")&&typeof We.addEventListener=="function"){let Xe=()=>We.scrollHeight-We.clientHeight>1;We.addEventListener("scroll",()=>{j(We)&&(M=!1),O(We)},{passive:!0}),We.addEventListener("wheel",$e=>{Xe()&&$e.deltaY<0&&(M=!0)},{passive:!0}),We.addEventListener("touchmove",()=>{Xe()&&(M=!0)},{passive:!0})}A=We}else d.appendChild(Se),A=Se;E=mt,k=me}let Ae=Z?A:null;Ae&&(Ae.classList.toggle("persona-artifact-source-window--fixed",le),Ae.classList.toggle("persona-artifact-source-window--clip",le&&r?.overflow==="clip"));let we=Ae?j(Ae):!0;if(E.replaceChildren(hg(ie,ge?.language,ge?.path)),Ae){let Se=ne.status!=="complete";le&&Se&&r?.followOutput&&!M&&we?q(Ae):Se||(M=!1),O(Ae)}},de=ie=>{h(),S(),W(),d.replaceChildren();let ge=b("div",Cv);ge.innerHTML=c(ie),d.appendChild(ge)},be=ie=>{let ge=ie.id,ne=n.features?.artifacts,le=Ur(ie,ne,"status-body");if(C&&T===ge&&C.parentElement===d){let Ae=C.querySelector(".persona-artifact-status-view-text");Ae&&ar(Ae,le,ne);return}h(),S(),d.replaceChildren();let Z=b("div","persona-artifact-status-view"),me=b("div","persona-artifact-status-view-text");ar(me,le,ne),Z.appendChild(me),d.appendChild(Z),C=Z,T=ge},De=ie=>{l=ie;let ge=t.resolveViewMode?.(ie)??r?.viewMode??"rendered",ne=ie.artifactType==="markdown"?ie.file:void 0,le=ie.status!=="complete";le||_r(ie.id);let Z=le?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&le){be(ie);return}if(ne){let we=Fi(ie.markdown??""),Se=ja(ne),mt=n.features?.artifacts?.filePreview?.enabled!==!1;if(!le&&ge==="rendered"&&mt&&(Se==="html"||Se==="svg")){let _e=ie.id+"\0"+we;if(u&&g===_e&&u.parentElement===d)return;S(),W(),h(),d.replaceChildren();let Xe=n.features?.artifacts?.filePreview,$e=Xe?.iframeSandbox??"allow-scripts";!Xe?.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(Wt=>Wt&&Wt!=="allow-same-origin").join(" "));let Me=Av(Xe?.loading),ke=b("div","persona-artifact-frame"),Je=b("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",$e),Je.setAttribute("data-artifact-id",ie.id);let Dt=null;Me.enabled&&Me.injectReadySignal?(Dt=Mv(),Je.srcdoc=we+Tv(Dt)):Je.srcdoc=we,ke.appendChild(Je),d.appendChild(ke),Me.enabled&&(f=kv(ke,Je,Dt,Me,ie.id,n)),u=ke,g=_e;return}if(h(),!le&&Se==="markdown"&&ge==="rendered"){de(we);return}Q(we,{language:ne.language,path:ne.path},ie,me);return}if(ie.artifactType==="markdown"){if(ge==="source"){h(),Q(ie.markdown??"",void 0,ie,me);return}de(ie.markdown??"");return}h(),S(),W(),d.replaceChildren();let Ae=ie.component?o.get(ie.component):void 0;if(Ae){let Se={message:{id:ie.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let mt=Ae(ie.props??{},Se);if(mt){d.appendChild(mt);return}}catch{}}d.appendChild(wv(ie))};return De(e),{el:d,update(ie){De(ie)}}}var Mg=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,f,h={}){g=d(g);let A=u(f),E=c(g,A,h),k=r(E,()=>l(E,g,A,M=>M.morphStyle==="innerHTML"?(a(M,g,A),Array.from(g.childNodes)):o(M,g,A)));return E.pantry.remove(),k}function o(g,f,h){let A=u(f);return a(g,A,h,f,f.nextSibling),Array.from(A.childNodes)}function r(g,f){if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:A,selectionStart:E,selectionEnd:k}=h,M=f();return A&&A!==document.activeElement?.getAttribute("id")&&(h=g.target.querySelector(`[id="${A}"]`),h?.focus()),h&&!h.selectionEnd&&k&&h.setSelectionRange(E,k),M}let a=(function(){function g(C,T,W,w=null,D=null){T instanceof HTMLTemplateElement&&W instanceof HTMLTemplateElement&&(T=T.content,W=W.content),w||(w=T.firstChild);for(let F of W.childNodes){if(w&&w!=D){let O=h(C,F,w,D);if(O){O!==w&&E(C,w,O),s(O,F,C),w=O.nextSibling;continue}}if(F instanceof Element){let O=F.getAttribute("id");if(C.persistentIds.has(O)){let q=k(T,O,w,C);s(q,F,C),w=q.nextSibling;continue}}let j=f(T,F,w,C);j&&(w=j.nextSibling)}for(;w&&w!=D;){let F=w;w=w.nextSibling,A(C,F)}}function f(C,T,W,w){if(w.callbacks.beforeNodeAdded(T)===!1)return null;if(w.idMap.has(T)){let D=document.createElement(T.tagName);return C.insertBefore(D,W),s(D,T,w),w.callbacks.afterNodeAdded(D),D}else{let D=document.importNode(T,!0);return C.insertBefore(D,W),w.callbacks.afterNodeAdded(D),D}}let h=(function(){function C(w,D,F,j){let O=null,q=D.nextSibling,Q=0,de=F;for(;de&&de!=j;){if(W(de,D)){if(T(w,de,D))return de;O===null&&(w.idMap.has(de)||(O=de))}if(O===null&&q&&W(de,q)&&(Q++,q=q.nextSibling,Q>=2&&(O=void 0)),w.activeElementAndParents.includes(de))break;de=de.nextSibling}return O||null}function T(w,D,F){let j=w.idMap.get(D),O=w.idMap.get(F);if(!O||!j)return!1;for(let q of j)if(O.has(q))return!0;return!1}function W(w,D){let F=w,j=D;return F.nodeType===j.nodeType&&F.tagName===j.tagName&&(!F.getAttribute?.("id")||F.getAttribute?.("id")===j.getAttribute?.("id"))}return C})();function A(C,T){if(C.idMap.has(T))S(C.pantry,T,null);else{if(C.callbacks.beforeNodeRemoved(T)===!1)return;T.parentNode?.removeChild(T),C.callbacks.afterNodeRemoved(T)}}function E(C,T,W){let w=T;for(;w&&w!==W;){let D=w;w=w.nextSibling,A(C,D)}return w}function k(C,T,W,w){let D=w.target.getAttribute?.("id")===T&&w.target||w.target.querySelector(`[id="${T}"]`)||w.pantry.querySelector(`[id="${T}"]`);return M(D,w),S(C,D,W),D}function M(C,T){let W=C.getAttribute("id");for(;C=C.parentNode;){let w=T.idMap.get(C);w&&(w.delete(W),w.size||T.idMap.delete(C))}}function S(C,T,W){if(C.moveBefore)try{C.moveBefore(T,W)}catch{C.insertBefore(T,W)}else C.insertBefore(T,W)}return g})(),s=(function(){function g(M,S,C){return C.ignoreActive&&M===document.activeElement?null:(C.callbacks.beforeNodeMorphed(M,S)===!1||(M instanceof HTMLHeadElement&&C.head.ignore||(M instanceof HTMLHeadElement&&C.head.style!=="morph"?p(M,S,C):(f(M,S,C),k(M,C)||a(C,M,S))),C.callbacks.afterNodeMorphed(M,S)),M)}function f(M,S,C){let T=S.nodeType;if(T===1){let W=M,w=S,D=W.attributes,F=w.attributes;for(let j of F)E(j.name,W,"update",C)||W.getAttribute(j.name)!==j.value&&W.setAttribute(j.name,j.value);for(let j=D.length-1;0<=j;j--){let O=D[j];if(O&&!w.hasAttribute(O.name)){if(E(O.name,W,"remove",C))continue;W.removeAttribute(O.name)}}k(W,C)||h(W,w,C)}(T===8||T===3)&&M.nodeValue!==S.nodeValue&&(M.nodeValue=S.nodeValue)}function h(M,S,C){if(M instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let T=S.value,W=M.value;A(M,S,"checked",C),A(M,S,"disabled",C),S.hasAttribute("value")?W!==T&&(E("value",M,"update",C)||(M.setAttribute("value",T),M.value=T)):E("value",M,"remove",C)||(M.value="",M.removeAttribute("value"))}else if(M instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)A(M,S,"selected",C);else if(M instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let T=S.value,W=M.value;if(E("value",M,"update",C))return;T!==W&&(M.value=T),M.firstChild&&M.firstChild.nodeValue!==T&&(M.firstChild.nodeValue=T)}}function A(M,S,C,T){let W=S[C],w=M[C];if(W!==w){let D=E(C,M,"update",T);D||(M[C]=S[C]),W?D||M.setAttribute(C,""):E(C,M,"remove",T)||M.removeAttribute(C)}}function E(M,S,C,T){return M==="value"&&T.ignoreActiveValue&&S===document.activeElement?!0:T.callbacks.beforeAttributeUpdated(M,S,C)===!1}function k(M,S){return!!S.ignoreActiveValue&&M===document.activeElement&&M!==document.body}return g})();function l(g,f,h,A){if(g.head.block){let E=f.querySelector("head"),k=h.querySelector("head");if(E&&k){let M=p(E,k,g);return Promise.all(M).then(()=>{let S=Object.assign(g,{head:{block:!1,ignore:!0}});return A(S)})}}return A(g)}function p(g,f,h){let A=[],E=[],k=[],M=[],S=new Map;for(let T of f.children)S.set(T.outerHTML,T);for(let T of g.children){let W=S.has(T.outerHTML),w=h.head.shouldReAppend(T),D=h.head.shouldPreserve(T);W||D?w?E.push(T):(S.delete(T.outerHTML),k.push(T)):h.head.style==="append"?w&&(E.push(T),M.push(T)):h.head.shouldRemove(T)!==!1&&E.push(T)}M.push(...S.values());let C=[];for(let T of M){let W=document.createRange().createContextualFragment(T.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(W)!==!1){if("href"in W&&W.href||"src"in W&&W.src){let w,D=new Promise(function(F){w=F});W.addEventListener("load",function(){w()}),C.push(D)}g.appendChild(W),h.callbacks.afterNodeAdded(W),A.push(W)}}for(let T of E)h.callbacks.beforeNodeRemoved(T)!==!1&&(g.removeChild(T),h.callbacks.afterNodeRemoved(T));return h.head.afterHeadMorphed(g,{added:A,kept:k,removed:E}),C}let c=(function(){function g(C,T,W){let{persistentIds:w,idMap:D}=M(C,T),F=f(W),j=F.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(j))throw`Do not understand how to morph style ${j}`;return{target:C,newContent:T,config:F,morphStyle:j,ignoreActive:F.ignoreActive,ignoreActiveValue:F.ignoreActiveValue,restoreFocus:F.restoreFocus,idMap:D,persistentIds:w,pantry:h(),activeElementAndParents:A(C),callbacks:F.callbacks,head:F.head}}function f(C){let T=Object.assign({},t);return Object.assign(T,C),T.callbacks=Object.assign({},t.callbacks,C.callbacks),T.head=Object.assign({},t.head,C.head),T}function h(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function A(C){let T=[],W=document.activeElement;if(W?.tagName!=="BODY"&&C.contains(W))for(;W&&(T.push(W),W!==C);)W=W.parentElement;return T}function E(C){let T=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&T.push(C),T}function k(C,T,W,w){for(let D of w){let F=D.getAttribute("id");if(T.has(F)){let j=D;for(;j;){let O=C.get(j);if(O==null&&(O=new Set,C.set(j,O)),O.add(F),j===W)break;j=j.parentElement}}}}function M(C,T){let W=E(C),w=E(T),D=S(W,w),F=new Map;k(F,D,C,W);let j=T.__idiomorphRoot||T;return k(F,D,j,w),{persistentIds:D,idMap:F}}function S(C,T){let W=new Set,w=new Map;for(let{id:F,tagName:j}of C)w.has(F)?W.add(F):w.set(F,j);let D=new Set;for(let{id:F,tagName:j}of T)D.has(F)?W.add(F):w.get(F)===j&&D.add(F);for(let F of W)D.delete(F);return D}return g})(),{normalizeElement:d,normalizeParent:u}=(function(){let g=new WeakSet;function f(k){return k instanceof Document?k.documentElement:k}function h(k){if(k==null)return document.createElement("div");if(typeof k=="string")return h(E(k));if(g.has(k))return k;if(k instanceof Node){if(k.parentNode)return new A(k);{let M=document.createElement("div");return M.append(k),M}}else{let M=document.createElement("div");for(let S of[...k])M.append(S);return M}}class A{constructor(M){this.originalNode=M,this.realParentNode=M.parentNode,this.previousSibling=M.previousSibling,this.nextSibling=M.nextSibling}get childNodes(){let M=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)M.push(S),S=S.nextSibling;return M}querySelectorAll(M){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(M)&&S.push(C);let T=C.querySelectorAll(M);for(let W=0;W<T.length;W++)S.push(T[W])}return S},[])}insertBefore(M,S){return this.realParentNode.insertBefore(M,S)}moveBefore(M,S){return this.realParentNode.moveBefore(M,S)}get __idiomorphRoot(){return this.originalNode}}function E(k){let M=new DOMParser,S=k.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=M.parseFromString(k,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let T=C.firstChild;return T&&g.add(T),T}}else{let T=M.parseFromString("<body><template>"+k+"</template></body>","text/html").body.querySelector("template").content;return g.add(T),T}}return{normalizeElement:f,normalizeParent:h}})();return{morph:n,defaults:t}})();var zi=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Mg.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){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 a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let s=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var Tg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Wp={index:-1,draft:""};function Eg(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function kg(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 Lg(){return new Map}function Pg(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Rg(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Ig(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Wg(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 $i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Fn(e)-e.scrollTop<=t}function ji(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=e,d=n-o;return s||Math.abs(d)<a?{action:"none",delta:d,nextLastScrollTop:n}:!t&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:t&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Gi(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 Hg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Bg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Dg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ja={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Lv=["pre","code","a","script","style"],Ki=e=>({type:e?.type??Ja.type,placeholder:e?.placeholder??Ja.placeholder,speed:e?.speed??Ja.speed,duration:e?.duration??Ja.duration,buffer:e?.buffer??Ja.buffer}),Og=[{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"}],Qa=new Map;for(let e of Og)Qa.set(e.name,e);var sr=e=>{Qa.set(e.name,e)},Dp=e=>{Og.some(t=>t.name===e)||Qa.delete(e)},Fp=()=>Array.from(Qa.keys()),zr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:Qa.get(e)??null,Xi=(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 a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
34
- `);return a<0?"":e.slice(0,a)}return e},Pv=(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},Rv=(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},Hp=/\s/,Iv=(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},Wv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(Hp.test(a[l])){let p=l;for(;p<a.length&&Hp.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<a.length&&!Hp.test(a[c]);)p.appendChild(Pv(o,a[c],t,n.value)),n.value+=1,c+=1;s.appendChild(p),l=c}r.replaceChild(s,e)},Hv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(Rv(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},Ya=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??Lv).map(u=>u.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Iv(p,a)||l.push(p),p=s.nextNode();let c={value:o?.startIndex??0},d=t==="char"?Wv:Hv;for(let u of l)d(u,n,c);return r.innerHTML},Ji=(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},Za=(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},Fg=new WeakMap,Bv=(e,t)=>{if(!e.styles)return;let n=Fg.get(t);if(n||(n=new Set,Fg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let 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)},Bp=new WeakMap,Dv=(e,t)=>{if(!e.onAttach)return;let n=Bp.get(t);if(n||(n=new Map,Bp.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Ng=e=>{let t=Bp.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Qi=(e,t)=>{Bv(e,t),Dv(e,t)};function Op(e,t=Gt){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var es=0,Ho=null;function Np(e=document){if(es++,es===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Ho={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,es=Math.max(0,es-1),es===0&&Ho)){let n=e.body,o=e.defaultView??window;n.style.overflow=Ho.originalOverflow,n.style.position=Ho.originalPosition,n.style.top=Ho.originalTop,n.style.width=Ho.originalWidth,o.scrollTo(0,Ho.scrollY),Ho=null}}}var ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Et=e=>(e?.launcher?.mountMode??"floating")==="docked",Bo=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",rn=e=>{let t=e?.launcher?.dock;return{side:t?.side??ts.side,width:t?.width??ts.width,animate:t?.animate??ts.animate,reveal:t?.reveal??ts.reveal,maxHeight:t?.maxHeight??ts.maxHeight}};var Pn={"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 Fv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Yi=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Fv,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=b("div",o),c=s.closeButtonTooltipText??"Close chat",d=s.closeButtonShowTooltip??!0,u=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Be("button",{className:Kn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Yt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),A=oe(u,a,"currentColor",1);return A?(A.style.display="block",h.appendChild(A)):h.textContent=g,p.appendChild(h),Ut({anchor:h,trigger:p,text:()=>h.getAttribute("aria-label")??c,enabled:d}),{button:h,wrapper:p}},Ov="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Zi=(e,t={})=>{let{wrapperClassName:n=Ov,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",c=s.iconColor??"",d=s.backgroundColor??"",u=s.borderWidth??"",g=s.borderColor??"",f=s.borderRadius??"",h=s.paddingX??"",A=s.paddingY??"",E=s.tooltipText??"Clear chat",k=s.showTooltip??!0,M=b("div",n),S=!!(u||g),C=Be("button",{className:Kn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:l,width:l,color:c||Yt.actionIconColor,backgroundColor:d||void 0,border:S?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:A||void 0,paddingBottom:A||void 0}}),T=oe(p,r,"currentColor",1);return T&&(T.style.display="block",C.appendChild(T)),M.appendChild(C),Ut({anchor:C,trigger:M,text:()=>C.getAttribute("aria-label")??E,enabled:k}),{button:C,wrapper:M}};var Yt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},eo=e=>{let{config:t,showClose:n=!0}=e,o=Be("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??{},a=r.headerIconSize??"48px",s=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=Be("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let T=parseFloat(a)||24,W=oe(p,T*.6,"currentColor",1);W?c.replaceChildren(W):c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let T=b("img");T.src=t.launcher.iconUrl,T.alt="",T.className="persona-rounded-xl persona-object-cover",T.style.height=a,T.style.width=a,c.replaceChildren(T)}else c.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let d=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Be("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Yt.titleColor}}),g=Be("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Yt.subtitleColor}});d.append(u,g),l?o.append(d):o.append(c,d);let f=r.clearChat??{},h=f.enabled??!0,A=f.placement??"inline",E=null,k=null;if(h){let W=Zi(t,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=W.button,k=W.wrapper,A==="top-right"&&(k.style.right="48px"),A==="inline"&&o.appendChild(k)}let M=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&A==="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:S,wrapper:C}=Yi(t,{showClose:n,wrapperClassName:M});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:E,clearChatButtonWrapper:k}},ir=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var _p=e=>{let t=eo({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 Nv(e,t,n){if(t?.length)for(let o of t){let r=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=oe(o.icon,14,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=b("div","persona-relative");a.appendChild(r);let s=Ro({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-left"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Up=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=t?.launcher??{},l=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=_i({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Yt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=b("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Yt.titleColor,d.textContent=s.title??"Chat Assistant",c.appendChild(d),Nv(c,r?.trailingActions,r?.onAction??a),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let S=r.onTitleClick;c.addEventListener("click",C=>{C.target.closest("button")||S()}),c.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),S())})}let M=r?.titleRowHover;M&&(c.style.borderRadius=M.borderRadius??"10px",c.style.padding=M.padding??"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{c.style.backgroundColor=M.background??"",c.style.borderColor=M.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=s.closeButtonSize??"32px",g=b("div",""),f=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=s.closeButtonColor||Yt.actionIconColor;let h=s.closeButtonIconName??"x",A=oe(h,"28px","currentColor",1);A?f.appendChild(A):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),l.appendChild(g);let E=b("div");E.style.display="none";let k=b("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:d,headerSubtitle:k,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},el={default:_p,minimal:Up},qp=e=>el[e]??el.default,$r=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=b("div");l.style.display="none";let p=b("span"),c=b("span"),d=b("button");d.style.display="none";let u=b("div");return u.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=qp(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&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var tl=e=>{let t=b("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;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let s=parseFloat(t.style.maxHeight);return Number.isFinite(s)&&s>0?s:n*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let s=Math.min(t.scrollHeight,r());t.style.height=`${s}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:a}},nl=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",c=e?.copy?.stopButtonLabel??"Stop",d=t.showTooltip??!1,u=t.size??"40px",g=t.backgroundColor,f=t.textColor,h=b("div","persona-send-button-wrapper"),A=Be("button",{className:Kn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,k=null;if(n){let C=parseFloat(u)||24,T=f?.trim()||"currentColor";r?(E=oe(r,C,T,2),E?A.appendChild(E):A.textContent=o):A.textContent=o,k=oe(a,C,T,2)}else A.textContent=p;A.setAttribute("aria-label",s),h.appendChild(A),Ut({anchor:A,trigger:h,text:()=>A.getAttribute("aria-label")??"",enabled:d});let M="send";return{button:A,wrapper:h,setMode:C=>{if(C===M)return;M=C;let T=C==="stop"?l:s;if(A.setAttribute("aria-label",T),n){if(E&&k){let W=C==="stop"?k:E;A.replaceChildren(W)}}else A.textContent=C==="stop"?c:p}}},ol=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 s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,c=parseFloat(p)||24,d=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,g=b("div","persona-send-button-wrapper"),f=Be("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:u||"var(--persona-text, #111827)",backgroundColor:d||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}}),A=oe(l,c,u||"currentColor",1.5);A?f.appendChild(A):f.textContent="\u{1F3A4}",g.appendChild(f);let E=t.tooltipText??"Start voice recognition",k=t.showTooltip??!1;return Ut({anchor:f,trigger:g,text:()=>f.getAttribute("aria-label")??E,enabled:k}),{button:f,wrapper:g}},rl=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=b("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=b("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??Yn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),c=b("div","persona-send-button-wrapper"),d=Be("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:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1"}}),u=oe(a,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",f=>{f.preventDefault(),r.click()}),c.appendChild(d);let g=t.buttonTooltipText??"Attach file";return Ut({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??g}),{button:d,wrapper:c,input:r,previewsContainer:o}},al=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=b("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 a=t.idleText??"Online";if(t.idleLink){let s=b("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},sl=()=>Be("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var jr=e=>{let{config:t}=e,n=Be("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=sl(),r=Be("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:a,attachAutoResize:s}=tl(t);s();let l=nl(t),p=ol(t),c=rl(t),d=al(t);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(a);let u=Be("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(g,f),r.append(u),r.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:l.setMode}};var _g=()=>{let e=Be("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=oe("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=b("span","persona-pill-peek__text"),r=b("span","persona-pill-peek__caret"),a=oe("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Ug=e=>{let{config:t}=e,n=Be("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=sl(),r=al(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=tl(t);a.style.maxHeight="100px",s();let l=nl(t),p=ol(t),c=rl(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Be("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),d.addEventListener("click",h=>{h.target!==l.button&&h.target!==l.wrapper&&h.target!==p?.button&&h.target!==p?.wrapper&&h.target!==c?.button&&h.target!==c?.wrapper&&a.focus()}),c&&d.append(c.input),d.append(u,a,g),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:l.setMode}};var qg=e=>{let t=e?.launcher?.enabled??!0,n=Et(e);if(Bo(e)){let d=e?.launcher?.composerBar??{},u=b("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Gt);let g=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",u.appendChild(g);let f=b("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Gt),{wrapper:u,panel:g,pillRoot:f}}if(n){let d=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!t){let d=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return d.style.width=g,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=e?.launcher??{},a=r.position&&Pn[r.position]?Pn[r.position]:Pn["bottom-right"],s=b("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Gt);let l=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=e?.launcher?.width??e?.launcherWidth??pn;return l.style.width=c,l.style.maxWidth=c,s.appendChild(l),{wrapper:s,panel:l}},_v=(e,t)=>{let n=b("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}=Yi(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 a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let C=Zi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=C.button,l=C.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=Be("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Be("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let d=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),g=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),f=b("div","persona-flex persona-flex-col persona-gap-3"),h=e?.layout?.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let E=Be("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"}}),k=Ug({config:e}),{root:M,textNode:S}=_g();return n.append(p,r,c,E),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:E,suggestions:k.suggestions,textarea:k.textarea,sendButton:k.sendButton,sendButtonWrapper:k.sendButtonWrapper,micButton:k.micButton,micButtonWrapper:k.micButtonWrapper,composerForm:k.composerForm,statusText:k.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:p,footer:k.footer,attachmentButton:k.attachmentButton,attachmentButtonWrapper:k.attachmentButtonWrapper,attachmentInput:k.attachmentInput,attachmentPreviewsContainer:k.attachmentPreviewsContainer,actionsRow:k.actionsRow,leftActions:k.leftActions,rightActions:k.rightActions,setSendButtonMode:k.setSendButtonMode,peekBanner:M,peekTextNode:S}},Vg=(e,t=!0)=>{if(Bo(e))return _v(e,t);let n=Be("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,a=o?$r(e,o,{showClose:t}):eo({config:e,showClose:t}),s=Be("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"}});s.style.setProperty("scrollbar-gutter","stable");let l=Be("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Be("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Be("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Et(e)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=b("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(c.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(c,d);let f=jr({config:e}),h=e?.layout?.showFooter!==!1;r?ir(n,a,e):(a.header.style.display="none",ir(n,a,e)),n.append(s);let A=Be("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||(f.footer.style.display="none"),n.append(f.footer),n.append(A),{container:n,body:s,messagesWrapper:d,composerOverlay:A,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:l,introSubtitle:p,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var Vp=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
32
+ `)),n=v("span","persona-code-line")),o(r.type,a[s])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function Dh(e,t,n){let o=e.length<=_C?UC(t,n):null,r=o?XC(e,o):[{type:"plain",value:e}];return JC(r)}function $o(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:a}=e,s=v("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(nl)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",r==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let T=document.createElement("hr");s.appendChild(T)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",m.id),m.destructive&&b.setAttribute("data-destructive",""),m.icon){let T=ae(m.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,b.appendChild(w),b.addEventListener("click",T=>{T.stopPropagation(),c(),n(m.id)}),s.appendChild(b)}let l=null;function p(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,r==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function d(){p(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=b=>{!s.contains(b.target)&&!o.contains(b.target)&&c()};document.addEventListener("click",m,!0),l=()=>document.removeEventListener("click",m,!0)})}function c(){s.classList.add("persona-hidden"),l?.(),l=null}function f(){s.classList.contains("persona-hidden")?d():c()}function g(){c(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:c,toggle:f,destroy:g}}function Tt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:a,onClick:s,aria:l}=e,p=v("button","persona-icon-btn"+(a?" "+a:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=ae(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),s&&p.addEventListener("click",s),l)for(let[c,f]of Object.entries(l))p.setAttribute(c,f);return p}function po(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:a,className:s,onClick:l,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,s&&(d+=" "+s);let c=v("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let g=ae(t,a??14,"currentColor",2);g&&c.appendChild(g)}let f=v("span");if(f.textContent=n,c.appendChild(f),l&&c.addEventListener("click",l),p)for(let[g,m]of Object.entries(p))c.setAttribute(g,m);return c}function ma(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,a=v("div","persona-toggle-group"+(r?" "+r:""));a.setAttribute("role","group");let s=n,l=[];function p(){for(let c of l)c.btn.setAttribute("aria-pressed",c.id===s?"true":"false")}for(let c of t){let f;c.icon?f=Tt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{s=c.id,p(),o(c.id)}}):(f=v("button","persona-icon-btn"+(c.className?" "+c.className:"")),f.type="button",f.setAttribute("aria-label",c.label),f.title=c.label,f.textContent=c.label,f.addEventListener("click",()=>{s=c.id,p(),o(c.id)})),f.setAttribute("aria-pressed",c.id===s?"true":"false"),l.push({id:c.id,btn:f}),a.appendChild(f)}function d(c){s=c,p()}return{element:a,setSelected:d}}function ul(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:a="bottom-left",portal:s,className:l,hover:p}=e,d=v("div","persona-combo-btn"+(l?" "+l:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=v("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let f=ae(n,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",d.appendChild(f)),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 g=$o({items:o,onSelect:m=>{d.setAttribute("aria-expanded","false"),r(m)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",m=>{m.stopPropagation();let b=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),g.toggle()}),d.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),d.click())}),{element:d,setLabel:m=>{c.textContent=m,d.setAttribute("aria-label",m)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let m=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",m?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var fl="persona-artifact-custom-action-btn";function ga(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 "+fl+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+fl+(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=po({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-copy-btn":"")}):o=Tt({icon:e.icon,label:e.label,className:fl+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function bs(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 Fh(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?$n(n.path):o,a=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=e.presentation&&typeof e.presentation=="object"&&!Array.isArray(e.presentation)?e.presentation:void 0,d=n?Vo(n):l==="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`),a&&c.setAttribute("data-open-artifact",a);let f=document.createElement("div");f.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-muted, #9ca3af)",f.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 g=document.createElement("div");g.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)",s==="streaming"){let w=t?.config?.features?.artifacts,T={id:a,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},L=fa(T,w,"card");Tr(b,L,w)}else a&&ua(a),b.textContent=d;if(g.append(m,b),c.append(f,g),s==="complete"){let w=t?.config?.features?.artifacts?.cardActions;if(w&&w.length>0){let L={artifactId:a||null,title:r,artifactType:l,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let A of w)try{if(A.visible===void 0||A.visible(L)){let S=ga(A);S.setAttribute("data-artifact-custom-action",A.id),S.className=`${S.className} persona-flex-shrink-0`,c.append(S)}}catch{}}let T=po({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",a),c.append(T)}return c}var ml=(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:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Fh(e,t)});if(l)return l}return Fh(e,t)};var jo=new WeakMap;function Cu(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 a=jo.get(r);if(!a)return;let s=o.get(r.getAttribute("data-artifact-inline")??"");s&&a(s,n)})}function qh(e){return jo.has(e)}function QC(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 s=e.componentProps,l=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:l,...r?{presentation:r}:{}}}let a=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:"",...a?{file:a}:{},...r?{presentation:r}:{}}}function Oh(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?$n(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?Vo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function YC(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 Nh=180,ZC=240,ew=.8,tw=300,nw=500,ow="cubic-bezier(0.2, 0, 0, 1)",_h=240,rw=.35;function aw(e,t,n){let{swap:o,onSettled:r}=n,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(!t||!e.isConnected||a||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let s=[];for(let l of Array.from(e.children))l instanceof HTMLElement&&s.push(l.animate([{opacity:1},{opacity:0}],{duration:Nh,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of s)L.cancel();o();let l=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){l(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){l(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(nw,Math.max(tw,ZC+d*ew))),f=Math.round(c*rw),g=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,m=g?g.animate([{opacity:0},{opacity:1}],{duration:_h,delay:f,easing:"ease-out",fill:"backwards"}):null,b=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:ow});e.style.height=`${p}px`;let w=!1,T=()=>{w||(w=!0,l(),r())};Promise.allSettled([b.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(c,f+_h)+120)},Nh)}function sw(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 xs="--persona-artifact-inline-body-height";function iw(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,a=320,s=t?.height;typeof s=="number"||s==="auto"?(r=s,a=s):s&&typeof s=="object"&&(r=s.streaming??320,a=s.complete??320);let l=t?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:t?.followOutput!==!1,d,c,f=t?.fadeMask;f===!0?(d=!0,c=!0):f===!1?(d=!1,c=!1):f&&typeof f=="object"?(d=f.top===!0,c=f.bottom===!0):l==="clip"?(d=!1,c=!0):(d=!0,c=!0);let g=t?.transition==="none"?"none":"auto",m=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:a,followOutput:p,overflow:l,fadeTop:d,fadeBottom:c,transition:g,completeDisplay:m}}function Uh(e,t){let n=QC(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:a,showExpand:s,showViewToggle:l}=sw(o),p=o?.inlineActions??[],d=iw(o),c=d.completeDisplay==="card",f=null,g=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=ie=>ml(YC(ie),t),w=ie=>{m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(xs),m.replaceChildren(b(ie)),jo.set(m,ue=>{m.replaceChildren(b(ue))})};if(c&&n.status==="complete")return w(n),m;let T=gl(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>f??d.viewMode}),L=v("div","persona-artifact-inline-body");L.appendChild(T.el);let A=ie=>{let ue=ie.status!=="complete",oe=ue?d.streamingHeight:d.completeHeight,me=typeof oe=="number";me?m.style.setProperty(xs,`${oe}px`):m.style.removeProperty(xs);let Se=!!T.el.querySelector(".persona-code-pre"),Ce=!!T.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",Se),L.classList.toggle("persona-artifact-inline-body--sized",me&&Ce),L.classList.toggle("persona-artifact-inline-body--cap",!ue&&!Ce&&typeof d.completeHeight=="number")},S=n.status,C=(ie,ue)=>{S!=="complete"&&ie.status==="complete"?(typeof d.completeHeight=="number"?m.style.setProperty(xs,`${d.completeHeight}px`):m.style.removeProperty(xs),zh(L,ue?.suppressTransition?"none":d.transition,ie.id,()=>{T.update(ie),A(ie)})):T.update(ie),A(ie),S=ie.status};A(n);let M=d.overflow==="clip"&&s&&!!n.id;if(M&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${Oh(n).title} in panel`)),!r)return m.appendChild(L),jo.set(m,C),m;let P=v("div","persona-artifact-inline-chrome");P.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let R=v("div","persona-artifact-inline-chrome-lead"),F=v("span","persona-flex persona-items-center persona-flex-shrink-0"),O=ae("file-text",16,"currentColor",2);O&&F.appendChild(O);let $=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),E=v("span","persona-artifact-inline-type");R.append(F,$,E);let G=v("div","persona-artifact-inline-chrome-actions"),Q=v("span","persona-flex persona-items-center persona-gap-1"),Z=()=>f??d.viewMode,J=l?ma({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:Z(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:ie=>{let ue=ie==="source"?"source":"rendered";ue!==Z()&&(f=ue,T.update(g),A(g))}}):null,fe=a?Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;fe&&n.id&&fe.setAttribute("data-copy-artifact",n.id);let ne=s?Tt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ne&&n.id&&ne.setAttribute("data-expand-artifact-inline",n.id),G.appendChild(Q),J&&G.appendChild(J.element),fe&&G.appendChild(fe),ne&&G.appendChild(ne),P.append(R,G),m.append(P,L);let ge=ie=>{let{title:ue,typeLabel:oe}=Oh(ie);$.textContent=ue,$.title=ue,M&&L.setAttribute("aria-label",`Open ${ue} in panel`);let me=ie.status!=="complete";if(me){E.classList.contains("persona-artifact-inline-status")||(E.className="persona-artifact-inline-status",E.removeAttribute("data-preserve-animation"),E.replaceChildren());let Se=fa(ie,o,"inline-chrome");Tr(E,Se,o)}else ua(ie.id),E.className="persona-artifact-inline-type",E.removeAttribute("data-preserve-animation"),E.replaceChildren(),E.textContent=oe;if(fe&&fe.classList.toggle("persona-hidden",me),J){let Se=ie.artifactType==="markdown"?ie.file:void 0,Ce=!1;if(!me&&Se&&d.viewMode!=="source"){let Be=Mr(Se);Be==="markdown"?Ce=!0:(Be==="html"||Be==="svg")&&(Ce=o?.filePreview?.enabled!==!1)}J.element.classList.toggle("persona-hidden",!Ce),J.setSelected(Z())}if(Q.replaceChildren(),!me&&p.length>0){let Se=bs(ie);if(Se)for(let Ce of p)try{if(Ce.visible===void 0||Ce.visible(Se)){let Be=ga(Ce,{documentChrome:!0});Be.setAttribute("data-artifact-custom-action",Ce.id),Be.classList.add("persona-flex-shrink-0"),Q.appendChild(Be)}}catch{}}};return ge(n),jo.set(m,(ie,ue)=>{if(c&&S!=="complete"&&ie.status==="complete"){let oe=m.isConnected?m.getBoundingClientRect().height:0;S="complete";let me=ie,Se=!1,Ce=Be=>{me=Be,Se=!0};jo.set(m,Ce),aw(m,oe,{swap:()=>{w(me),Se=!1,jo.set(m,Ce)},onSettled:()=>{Se?w(me):jo.set(m,Be=>{m.replaceChildren(b(Be))})}});return}(ie.status!=="complete"||ie.id!==g.id)&&(f=null),g=ie,C(ie,ue),ge(ie)}),m}var Vh=(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:"",a=e.status==="streaming"?"streaming":"complete",s=typeof e.artifactType=="string"?e.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:s,status:a},config:t.config,defaultRenderer:()=>Uh(e,t)});if(l)return l}return Uh(e,t)};var wu=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)})}},Nn=new wu;Nn.register("PersonaArtifactCard",ml,{bubbleChrome:!1});Nn.register("PersonaArtifactInline",Vh,{bubbleChrome:!1});function vs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?cl(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Au=!1;function lw(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function zh(e,t,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,a=!1;try{a=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{a=!1}if(t!=="auto"||!e||typeof r!="function"||Au||a){o();return}Au=!0;let s=lw(n);e.style.setProperty("view-transition-name",s);let l=()=>{Au=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var cw="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",dw="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function pw(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 uw(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 fw=220;function mw(){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 gw(e){return`
33
+ <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 hw(e,t,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let s=n.renderIndicator({artifactId:e,config:t});if(s)return o.appendChild(s),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Lh());let a=null;return n.label!==!1&&(a=v("div","persona-artifact-frame-loading-text"),a.textContent=n.label,r.appendChild(a)),o.appendChild(r),{el:o,revealLabel:()=>{a&&a.classList.add("persona-artifact-frame-loading-text--visible")}}}function yw(e,t,n,o,r,a){let s=null,l=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},f=(S,C)=>{let M=setTimeout(()=>{d.delete(M),S()},C);d.add(M)},g=()=>{s&&s.parentElement&&s.remove(),s=null},m=()=>{if(s||p)return;let S=hw(r,a,o);s=S.el,e.appendChild(s),l=Date.now(),o.label!==!1&&f(S.revealLabel,o.labelDelayMs)},b=()=>{s&&(s.classList.add("persona-artifact-frame-loading--out"),f(g,fw))},w=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",A)},T=()=>{if(p||(p=!0,w(),c(),!s))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-l));S>0?f(b,S):b()};function L(S){if(n===null)return;let C=S.data;!C||C.persona!=="artifact-preview-ready"||C.token!==n||S.source===t.contentWindow&&T()}function A(){let S=C=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>C()):setTimeout(C,0)};S(()=>S(()=>T()))}return f(m,o.delayMs),f(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",A),()=>{p=!0,c(),w(),g()}}function gl(e,t){let{config:n}=t,o=t.registry??Nn,r=t.bodyLayout,a=n.markdown?hr(n.markdown):null,s=ta(n.sanitize),l=e,p=!1,d=ne=>{let ge=ao()!==null;a&&!ge&&!p&&(p=!0,ea(()=>fe(l)));let ie=a?a(ne):Vn(ne);return a&&ge&&s?s(ie):ie},c=v("div","persona-artifact-preview-body"),f=null,g=null,m=null,b=()=>{m&&(m(),m=null),f=null,g=null},w=null,T=null,L=null,A=!1,S=()=>{w=null,T=null,L=null,A=!1},C=null,M=null,P=()=>{C=null,M=null},R=40,F=0,O=ne=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ne()):setTimeout(ne,0),$=ne=>ne.scrollHeight-ne.clientHeight-ne.scrollTop<=R,E=ne=>{if(!r)return;let ge=ne.scrollHeight-ne.clientHeight>1,ie=ne.scrollHeight-ne.clientHeight-ne.scrollTop;ne.classList.toggle("persona-artifact-fade-top",r.fadeTop&&ge&&ne.scrollTop>1),ne.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&ge&&ie>1)},G=ne=>{F||(F=O(()=>{F=0,ne.scrollTop=ne.scrollHeight,E(ne)}))},Q=(ne,ge,ie,ue)=>{let oe=!!r,me=ie.id+"|"+(oe?"w":"p");if(!w||L!==me||w.parentElement!==c){b(),P(),c.replaceChildren();let Be=v("pre",cw+" persona-code-pre"),ut=v("code","persona-code");if(Be.appendChild(ut),oe){let Je=v("div","persona-artifact-source-window");if(Je.appendChild(Be),c.appendChild(Je),!(r?.overflow==="clip")&&typeof Je.addEventListener=="function"){let Ne=()=>Je.scrollHeight-Je.clientHeight>1;Je.addEventListener("scroll",()=>{$(Je)&&(A=!1),E(Je)},{passive:!0}),Je.addEventListener("wheel",_e=>{Ne()&&_e.deltaY<0&&(A=!0)},{passive:!0}),Je.addEventListener("touchmove",()=>{Ne()&&(A=!0)},{passive:!0})}w=Je}else c.appendChild(Be),w=Be;T=ut,L=me}let Se=oe?w:null;Se&&(Se.classList.toggle("persona-artifact-source-window--fixed",ue),Se.classList.toggle("persona-artifact-source-window--clip",ue&&r?.overflow==="clip"));let Ce=Se?$(Se):!0;if(T.replaceChildren(Dh(ne,ge?.language,ge?.path)),Se){let Be=ie.status!=="complete";ue&&Be&&r?.followOutput&&!A&&Ce?G(Se):Be||(A=!1),E(Se)}},Z=ne=>{b(),S(),P(),c.replaceChildren();let ge=v("div",dw);ge.innerHTML=d(ne),c.appendChild(ge)},J=ne=>{let ge=ne.id,ie=n.features?.artifacts,ue=fa(ne,ie,"status-body");if(C&&M===ge&&C.parentElement===c){let Se=C.querySelector(".persona-artifact-status-view-text");Se&&Tr(Se,ue,ie);return}b(),S(),c.replaceChildren();let oe=v("div","persona-artifact-status-view"),me=v("div","persona-artifact-status-view-text");Tr(me,ue,ie),oe.appendChild(me),c.appendChild(oe),C=oe,M=ge},fe=ne=>{l=ne;let ge=t.resolveViewMode?.(ne)??r?.viewMode??"rendered",ie=ne.artifactType==="markdown"?ne.file:void 0,ue=ne.status!=="complete";ue||ua(ne.id);let oe=ue?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof oe=="number";if(r?.streamingView==="status"&&ue){J(ne);return}if(ie){let Ce=cl(ne.markdown??""),Be=Mr(ie),ut=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ue&&ge==="rendered"&&ut&&(Be==="html"||Be==="svg")){let Qe=ne.id+"\0"+Ce;if(f&&g===Qe&&f.parentElement===c)return;S(),P(),b(),c.replaceChildren();let Ne=n.features?.artifacts?.filePreview,_e=Ne?.iframeSandbox??"allow-scripts";!Ne?.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(gt=>gt&&gt!=="allow-same-origin").join(" "));let Ae=uw(Ne?.loading),Me=v("div","persona-artifact-frame"),qe=v("iframe","persona-artifact-iframe");qe.setAttribute("sandbox",_e),qe.setAttribute("data-artifact-id",ne.id);let Jt=null;Ae.enabled&&Ae.injectReadySignal?(Jt=mw(),qe.srcdoc=Ce+gw(Jt)):qe.srcdoc=Ce,Me.appendChild(qe),c.appendChild(Me),Ae.enabled&&(m=yw(Me,qe,Jt,Ae,ne.id,n)),f=Me,g=Qe;return}if(b(),!ue&&Be==="markdown"&&ge==="rendered"){Z(Ce);return}Q(Ce,{language:ie.language,path:ie.path},ne,me);return}if(ne.artifactType==="markdown"){if(ge==="source"){b(),Q(ne.markdown??"",void 0,ne,me);return}Z(ne.markdown??"");return}b(),S(),P(),c.replaceChildren();let Se=ne.component?o.get(ne.component):void 0;if(Se){let Be={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ut=Se(ne.props??{},Be);if(ut){c.appendChild(ut);return}}catch{}}c.appendChild(pw(ne))};return fe(e),{el:c,update(ne){fe(ne)}}}var $h=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function n(g,m,b={}){g=c(g);let w=f(m),T=d(g,w,b),L=r(T,()=>l(T,g,w,A=>A.morphStyle==="innerHTML"?(a(A,g,w),Array.from(g.childNodes)):o(A,g,w)));return T.pantry.remove(),L}function o(g,m,b){let w=f(m);return a(g,w,b,m,m.nextSibling),Array.from(w.childNodes)}function r(g,m){if(!g.config.restoreFocus)return m();let b=document.activeElement;if(!(b instanceof HTMLInputElement||b instanceof HTMLTextAreaElement))return m();let{id:w,selectionStart:T,selectionEnd:L}=b,A=m();return w&&w!==document.activeElement?.getAttribute("id")&&(b=g.target.querySelector(`[id="${w}"]`),b?.focus()),b&&!b.selectionEnd&&L&&b.setSelectionRange(T,L),A}let a=(function(){function g(C,M,P,R=null,F=null){M instanceof HTMLTemplateElement&&P instanceof HTMLTemplateElement&&(M=M.content,P=P.content),R||(R=M.firstChild);for(let O of P.childNodes){if(R&&R!=F){let E=b(C,O,R,F);if(E){E!==R&&T(C,R,E),s(E,O,C),R=E.nextSibling;continue}}if(O instanceof Element){let E=O.getAttribute("id");if(C.persistentIds.has(E)){let G=L(M,E,R,C);s(G,O,C),R=G.nextSibling;continue}}let $=m(M,O,R,C);$&&(R=$.nextSibling)}for(;R&&R!=F;){let O=R;R=R.nextSibling,w(C,O)}}function m(C,M,P,R){if(R.callbacks.beforeNodeAdded(M)===!1)return null;if(R.idMap.has(M)){let F=document.createElement(M.tagName);return C.insertBefore(F,P),s(F,M,R),R.callbacks.afterNodeAdded(F),F}else{let F=document.importNode(M,!0);return C.insertBefore(F,P),R.callbacks.afterNodeAdded(F),F}}let b=(function(){function C(R,F,O,$){let E=null,G=F.nextSibling,Q=0,Z=O;for(;Z&&Z!=$;){if(P(Z,F)){if(M(R,Z,F))return Z;E===null&&(R.idMap.has(Z)||(E=Z))}if(E===null&&G&&P(Z,G)&&(Q++,G=G.nextSibling,Q>=2&&(E=void 0)),R.activeElementAndParents.includes(Z))break;Z=Z.nextSibling}return E||null}function M(R,F,O){let $=R.idMap.get(F),E=R.idMap.get(O);if(!E||!$)return!1;for(let G of $)if(E.has(G))return!0;return!1}function P(R,F){let O=R,$=F;return O.nodeType===$.nodeType&&O.tagName===$.tagName&&(!O.getAttribute?.("id")||O.getAttribute?.("id")===$.getAttribute?.("id"))}return C})();function w(C,M){if(C.idMap.has(M))S(C.pantry,M,null);else{if(C.callbacks.beforeNodeRemoved(M)===!1)return;M.parentNode?.removeChild(M),C.callbacks.afterNodeRemoved(M)}}function T(C,M,P){let R=M;for(;R&&R!==P;){let F=R;R=R.nextSibling,w(C,F)}return R}function L(C,M,P,R){let F=R.target.getAttribute?.("id")===M&&R.target||R.target.querySelector(`[id="${M}"]`)||R.pantry.querySelector(`[id="${M}"]`);return A(F,R),S(C,F,P),F}function A(C,M){let P=C.getAttribute("id");for(;C=C.parentNode;){let R=M.idMap.get(C);R&&(R.delete(P),R.size||M.idMap.delete(C))}}function S(C,M,P){if(C.moveBefore)try{C.moveBefore(M,P)}catch{C.insertBefore(M,P)}else C.insertBefore(M,P)}return g})(),s=(function(){function g(A,S,C){return C.ignoreActive&&A===document.activeElement?null:(C.callbacks.beforeNodeMorphed(A,S)===!1||(A instanceof HTMLHeadElement&&C.head.ignore||(A instanceof HTMLHeadElement&&C.head.style!=="morph"?p(A,S,C):(m(A,S,C),L(A,C)||a(C,A,S))),C.callbacks.afterNodeMorphed(A,S)),A)}function m(A,S,C){let M=S.nodeType;if(M===1){let P=A,R=S,F=P.attributes,O=R.attributes;for(let $ of O)T($.name,P,"update",C)||P.getAttribute($.name)!==$.value&&P.setAttribute($.name,$.value);for(let $=F.length-1;0<=$;$--){let E=F[$];if(E&&!R.hasAttribute(E.name)){if(T(E.name,P,"remove",C))continue;P.removeAttribute(E.name)}}L(P,C)||b(P,R,C)}(M===8||M===3)&&A.nodeValue!==S.nodeValue&&(A.nodeValue=S.nodeValue)}function b(A,S,C){if(A instanceof HTMLInputElement&&S instanceof HTMLInputElement&&S.type!=="file"){let M=S.value,P=A.value;w(A,S,"checked",C),w(A,S,"disabled",C),S.hasAttribute("value")?P!==M&&(T("value",A,"update",C)||(A.setAttribute("value",M),A.value=M)):T("value",A,"remove",C)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&S instanceof HTMLOptionElement)w(A,S,"selected",C);else if(A instanceof HTMLTextAreaElement&&S instanceof HTMLTextAreaElement){let M=S.value,P=A.value;if(T("value",A,"update",C))return;M!==P&&(A.value=M),A.firstChild&&A.firstChild.nodeValue!==M&&(A.firstChild.nodeValue=M)}}function w(A,S,C,M){let P=S[C],R=A[C];if(P!==R){let F=T(C,A,"update",M);F||(A[C]=S[C]),P?F||A.setAttribute(C,""):T(C,A,"remove",M)||A.removeAttribute(C)}}function T(A,S,C,M){return A==="value"&&M.ignoreActiveValue&&S===document.activeElement?!0:M.callbacks.beforeAttributeUpdated(A,S,C)===!1}function L(A,S){return!!S.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function l(g,m,b,w){if(g.head.block){let T=m.querySelector("head"),L=b.querySelector("head");if(T&&L){let A=p(T,L,g);return Promise.all(A).then(()=>{let S=Object.assign(g,{head:{block:!1,ignore:!0}});return w(S)})}}return w(g)}function p(g,m,b){let w=[],T=[],L=[],A=[],S=new Map;for(let M of m.children)S.set(M.outerHTML,M);for(let M of g.children){let P=S.has(M.outerHTML),R=b.head.shouldReAppend(M),F=b.head.shouldPreserve(M);P||F?R?T.push(M):(S.delete(M.outerHTML),L.push(M)):b.head.style==="append"?R&&(T.push(M),A.push(M)):b.head.shouldRemove(M)!==!1&&T.push(M)}A.push(...S.values());let C=[];for(let M of A){let P=document.createRange().createContextualFragment(M.outerHTML).firstChild;if(b.callbacks.beforeNodeAdded(P)!==!1){if("href"in P&&P.href||"src"in P&&P.src){let R,F=new Promise(function(O){R=O});P.addEventListener("load",function(){R()}),C.push(F)}g.appendChild(P),b.callbacks.afterNodeAdded(P),w.push(P)}}for(let M of T)b.callbacks.beforeNodeRemoved(M)!==!1&&(g.removeChild(M),b.callbacks.afterNodeRemoved(M));return b.head.afterHeadMorphed(g,{added:w,kept:L,removed:T}),C}let d=(function(){function g(C,M,P){let{persistentIds:R,idMap:F}=A(C,M),O=m(P),$=O.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes($))throw`Do not understand how to morph style ${$}`;return{target:C,newContent:M,config:O,morphStyle:$,ignoreActive:O.ignoreActive,ignoreActiveValue:O.ignoreActiveValue,restoreFocus:O.restoreFocus,idMap:F,persistentIds:R,pantry:b(),activeElementAndParents:w(C),callbacks:O.callbacks,head:O.head}}function m(C){let M=Object.assign({},t);return Object.assign(M,C),M.callbacks=Object.assign({},t.callbacks,C.callbacks),M.head=Object.assign({},t.head,C.head),M}function b(){let C=document.createElement("div");return C.hidden=!0,document.body.insertAdjacentElement("afterend",C),C}function w(C){let M=[],P=document.activeElement;if(P?.tagName!=="BODY"&&C.contains(P))for(;P&&(M.push(P),P!==C);)P=P.parentElement;return M}function T(C){let M=Array.from(C.querySelectorAll("[id]"));return C.getAttribute?.("id")&&M.push(C),M}function L(C,M,P,R){for(let F of R){let O=F.getAttribute("id");if(M.has(O)){let $=F;for(;$;){let E=C.get($);if(E==null&&(E=new Set,C.set($,E)),E.add(O),$===P)break;$=$.parentElement}}}}function A(C,M){let P=T(C),R=T(M),F=S(P,R),O=new Map;L(O,F,C,P);let $=M.__idiomorphRoot||M;return L(O,F,$,R),{persistentIds:F,idMap:O}}function S(C,M){let P=new Set,R=new Map;for(let{id:O,tagName:$}of C)R.has(O)?P.add(O):R.set(O,$);let F=new Set;for(let{id:O,tagName:$}of M)F.has(O)?P.add(O):R.get(O)===$&&F.add(O);for(let O of P)F.delete(O);return F}return g})(),{normalizeElement:c,normalizeParent:f}=(function(){let g=new WeakSet;function m(L){return L instanceof Document?L.documentElement:L}function b(L){if(L==null)return document.createElement("div");if(typeof L=="string")return b(T(L));if(g.has(L))return L;if(L instanceof Node){if(L.parentNode)return new w(L);{let A=document.createElement("div");return A.append(L),A}}else{let A=document.createElement("div");for(let S of[...L])A.append(S);return A}}class w{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],S=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;S&&S!=this.nextSibling;)A.push(S),S=S.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((S,C)=>{if(C instanceof Element){C.matches(A)&&S.push(C);let M=C.querySelectorAll(A);for(let P=0;P<M.length;P++)S.push(M[P])}return S},[])}insertBefore(A,S){return this.realParentNode.insertBefore(A,S)}moveBefore(A,S){return this.realParentNode.moveBefore(A,S)}get __idiomorphRoot(){return this.originalNode}}function T(L){let A=new DOMParser,S=L.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(S.match(/<\/html>/)||S.match(/<\/head>/)||S.match(/<\/body>/)){let C=A.parseFromString(L,"text/html");if(S.match(/<\/html>/))return g.add(C),C;{let M=C.firstChild;return M&&g.add(M),M}}else{let M=A.parseFromString("<body><template>"+L+"</template></body>","text/html").body.querySelector("template").content;return g.add(M),M}}return{normalizeElement:m,normalizeParent:b}})();return{morph:n,defaults:t}})();var hl=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;$h.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,a){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 a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let s=r.textContent??"",l=a.textContent??"";if(s!==l)return}return!1}}}}})};var jh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Su={index:-1,draft:""};function Gh(e){let{direction:t,history:n,currentValue:o,atStart:r,state:a}=e,s=a.index!==-1;if(n.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!r)return{handled:!1,state:a};if(!s){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(a.index>0){let l=a.index-1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<n.length-1){let l=a.index+1;return{handled:!0,value:n[l],state:{index:l,draft:a.draft}}}return{handled:!0,value:a.draft,state:{index:-1,draft:a.draft}}}function Kh(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 Xh(){return new Map}function Jh(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Qh(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Yh(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Zh(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 yl(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function jn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function uo(e,t){return jn(e)-e.scrollTop<=t}function bl(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return s||Math.abs(c)<a?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&l&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function xl(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 ey(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Mu(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 ty(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},bw=["pre","code","a","script","style"],vl=e=>({type:e?.type??Cs.type,placeholder:e?.placeholder??Cs.placeholder,speed:e?.speed??Cs.speed,duration:e?.duration??Cs.duration,buffer:e?.buffer??Cs.buffer}),oy=[{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"}],ws=new Map;for(let e of oy)ws.set(e.name,e);var Er=e=>{ws.set(e.name,e)},ku=e=>{oy.some(t=>t.name===e)||ws.delete(e)},Lu=()=>Array.from(ws.keys()),ha=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:ws.get(e)??null,Cl=(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 a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
34
+ `);return a<0?"":e.slice(0,a)}return e},xw=(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},vw=(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},Tu=/\s/,Cw=(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},ww=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=0;for(;l<a.length;)if(Tu.test(a[l])){let p=l;for(;p<a.length&&Tu.test(a[p]);)p+=1;s.appendChild(o.createTextNode(a.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=l;for(;d<a.length&&!Tu.test(a[d]);)p.appendChild(xw(o,a[d],t,n.value)),n.value+=1,d+=1;s.appendChild(p),l=d}r.replaceChild(s,e)},Aw=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let a=e.nodeValue??"";if(!a)return;let s=o.createDocumentFragment(),l=a.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?s.appendChild(o.createTextNode(p)):(s.appendChild(vw(o,p,t,n.value)),n.value+=1));r.replaceChild(s,e)},As=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let a=new Set((o?.skipTags??bw).map(f=>f.toLowerCase())),s=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=s.nextNode();for(;p;)Cw(p,a)||l.push(p),p=s.nextNode();let d={value:o?.startIndex??0},c=t==="char"?ww:Aw;for(let f of l)c(f,n,d);return r.innerHTML},wl=(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},Ss=(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},ny=new WeakMap,Sw=(e,t)=>{if(!e.styles)return;let n=ny.get(t);if(n||(n=new Set,ny.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let 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)},Eu=new WeakMap,Mw=(e,t)=>{if(!e.onAttach)return;let n=Eu.get(t);if(n||(n=new Map,Eu.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},ry=e=>{let t=Eu.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Al=(e,t)=>{Sw(e,t),Mw(e,t)};function Pu(e,t=Ut){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Ms=0,Go=null;function Ru(e=document){if(Ms++,Ms===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;Go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY: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,Ms=Math.max(0,Ms-1),Ms===0&&Go)){let n=e.body,o=e.defaultView??window;n.style.overflow=Go.originalOverflow,n.style.position=Go.originalPosition,n.style.top=Go.originalTop,n.style.width=Go.originalWidth,o.scrollTo(0,Go.scrollY),Go=null}}}var Ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},St=e=>(e?.launcher?.mountMode??"floating")==="docked",Ko=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",ln=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ts.side,width:t?.width??Ts.width,animate:t?.animate??Ts.animate,reveal:t?.reveal??Ts.reveal,maxHeight:t?.maxHeight??Ts.maxHeight}};var Iu=e=>e==="followUp"?"follow-up":e,Wu=(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"}},Tw=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'}},ay=new WeakSet,Ew=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,kw=e=>{Ew()||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"})})},Hu=e=>{var A,S,C;let{item:t,index:n,surface:o,source:r,variant:a,streaming:s,config:l,plugins:p,chipsConfig:d,session:c,getTextarea:f,eventTarget:g}=e,m=o==="followUp",b=t.behavior,w=()=>{if(c.isStreaming())return;let M={suggestion:{...t},surface:o,source:r,behavior:b},P=g.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:M,bubbles:!0,composed:!0,cancelable:!0}));if(m&&g.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:t.prompt},bubbles:!0,composed:!0})),!P)return;for(let F of p)if(F.onSuggestionSelect?.({suggestion:{...t},surface:o,source:r,variant:a,config:l})===!1)return;let R=f();if(b==="fill"){R.value=t.prompt,R.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),R.focus();return}R.value="",c.sendMessage(t.prompt)},T=()=>{let M=v("button",`persona-suggestion persona-suggestion--${a}`);if(M.type="button",M.disabled=s,M.dataset.suggestionId=t.id,M.dataset.emphasis=t.emphasis,M.dataset.behavior=b,a==="chip"&&(d?.fontFamily&&(M.style.fontFamily=Tw(d.fontFamily)),d?.fontWeight&&(M.style.fontWeight=d.fontWeight),d?.paddingX&&(M.style.paddingLeft=d.paddingX,M.style.paddingRight=d.paddingX),d?.paddingY&&(M.style.paddingTop=d.paddingY,M.style.paddingBottom=d.paddingY)),t.icon){let R=ae(t.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);R&&(R.classList.add("persona-suggestion__icon"),t.iconColor&&(R.style.color=t.iconColor),M.appendChild(R))}let P=v("span","persona-suggestion__copy");if(P.appendChild(ke("span",{className:"persona-suggestion__label",text:t.label})),t.description&&a!=="chip"&&P.appendChild(ke("span",{className:"persona-suggestion__description",text:t.description})),M.appendChild(P),a!=="chip"){let R=ae("arrow-right",16,"currentColor",1.8);R&&(R.classList.add("persona-suggestion__arrow"),M.appendChild(R))}return M.addEventListener("click",w),M},L=null;for(let M of p)if(M.renderSuggestion&&(L=M.renderSuggestion({suggestion:{...t},index:n,surface:o,source:r,variant:a,streaming:s,config:l,defaultRenderer:T,select:w}),L))break;return L??(L=T()),(A=L.dataset).suggestionId||(A.suggestionId=t.id),(S=L.dataset).behavior||(S.behavior=b),(C=L.dataset).emphasis||(C.emphasis=t.emphasis),L instanceof HTMLButtonElement||L.setAttribute("aria-disabled",s?"true":"false"),L},Es=e=>{let t=[],n=[],o=null,r=null,a=()=>{e.removeAttribute("data-scroll-left"),e.removeAttribute("data-scroll-right")},s=()=>{if(r=null,e.hidden||e.dataset.variant!=="chip"||e.dataset.overflow!=="scroll"){a();return}let c=Math.max(0,e.scrollWidth-e.clientWidth);if(c<=1){a();return}let f=getComputedStyle(e).direction==="rtl",g=Math.min(c,Math.max(0,Math.abs(e.scrollLeft))),m=4,b=g<=m,w=g>=c-m,T=f?!w:!b,L=f?!b:!w;e.toggleAttribute("data-scroll-left",T),e.toggleAttribute("data-scroll-right",L)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&s();return}r=requestAnimationFrame(s)};e.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(e),{buttons:t,elements:n,destroy:()=>{e.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(c,f,g,m,b,w)=>{e.replaceChildren(),t.length=0,n.length=0;let T=w?.source??"config",L=w?.surface??(T==="config"?"starter":"followUp"),A=L==="followUp",S=w?.variant??"chip",C=w?.behavior??"send",M=w?.overflow??"wrap",P=w?.config??{},R=w?.plugins??[],F=typeof w?.maxItems=="number"?Math.max(0,Math.floor(w.maxItems)):void 0,O=A?"followUps":"starters";!ay.has(P)&&P.debug===!0&&S!=="chip"&&P.suggestions?.[O]?.overflow!==void 0&&(ay.add(P),console.info(`[persona] suggestions.${O}.overflow applies to the "chip" variant only; the "${S}" variant manages its own stacking.`));let $=fe=>fe.map(Wu).filter(ne=>ne!==null).map(ne=>({...ne,behavior:ne.behavior??C})),E=$(c??[]);R.forEach(fe=>{fe.transformSuggestions&&(E=$(fe.transformSuggestions({suggestions:E.map(ne=>({...ne})),surface:L,source:T,config:P})))});let G=F===void 0?E:E.slice(0,F);if(!G.length){e.hidden=!0,o=null,a();return}if(!A&&(m??f.getMessages()).some(ne=>ne.role==="user")){e.hidden=!0,o=null;return}e.hidden=!1,e.classList.add("persona-suggestions"),e.dataset.personaSuggestionSurface=Iu(L),e.dataset.variant=S,e.dataset.overflow=M;let Q=document.createDocumentFragment(),Z=f.isStreaming();G.forEach((fe,ne)=>{let ge=Hu({item:fe,index:ne,surface:L,source:T,variant:S,streaming:Z,config:P,plugins:R,chipsConfig:b,session:f,getTextarea:()=>g,eventTarget:e});Q.appendChild(ge),n.push(ge),[...ge instanceof HTMLButtonElement?[ge]:[],...Array.from(ge.querySelectorAll("button"))].forEach(ue=>{t.includes(ue)||(ue.disabled=Z,t.push(ue))})}),e.appendChild(Q),s(),l();let J=JSON.stringify({normalized:G,surface:L,variant:S,source:T});J!==o&&(o=J,kw(n),e.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:G.map(fe=>({...fe})),surface:L,source:T,variant:S},bubbles:!0,composed:!0})),A&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:G.map(fe=>fe.prompt)},bubbles:!0,composed:!0})))}}};var gn={"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 Lw="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Sl=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Lw,buttonSize:r,iconSize:a="28px"}=t,s=e?.launcher??{},l=r??s.closeButtonSize??"32px",p=v("div",o),d=s.closeButtonTooltipText??"Close chat",c=s.closeButtonShowTooltip??!0,f=s.closeButtonIconName??"x",g=s.closeButtonIconText??"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),b=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:l,width:l,display:n?void 0:"none",color:s.closeButtonColor||Xt.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),w=ae(f,a,"currentColor",1);return w?(w.style.display="block",b.appendChild(w)):b.textContent=g,p.appendChild(b),qt({anchor:b,trigger:p,text:()=>b.getAttribute("aria-label")??d,enabled:c}),{button:b,wrapper:p}},Pw="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ml=(e,t={})=>{let{wrapperClassName:n=Pw,buttonSize:o,iconSize:r="20px"}=t,s=(e?.launcher??{}).clearChat??{},l=o??s.size??"32px",p=s.iconName??"refresh-cw",d=s.iconColor??"",c=s.backgroundColor??"",f=s.borderWidth??"",g=s.borderColor??"",m=s.borderRadius??"",b=s.paddingX??"",w=s.paddingY??"",T=s.tooltipText??"Clear chat",L=s.showTooltip??!0,A=v("div",n),S=!!(f||g),C=ke("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:l,width:l,color:d||Xt.actionIconColor,backgroundColor:c||void 0,border:S?`${f||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),M=ae(p,r,"currentColor",1);return M&&(M.style.display="block",C.appendChild(M)),A.appendChild(C),qt({anchor:C,trigger:A,text:()=>C.getAttribute("aria-label")??T,enabled:L}),{button:C,wrapper:A}};var Xt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Bu={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)"},Rw={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)"},fo=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??{},a=r.headerIconSize??"48px",s=r.closeButtonPlacement??"inline",l=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:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!l)if(p){let M=parseFloat(a)||24,P=ae(p,M*.6,"currentColor",1);P?d.replaceChildren(P):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let M=v("img");M.src=t.launcher.iconUrl,M.alt="",M.className="persona-rounded-xl persona-object-cover",M.style.height=a,M.style.width=a,d.replaceChildren(M)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=ke("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor,...Bu}}),g=ke("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor,...Rw}});c.append(f,g),l?o.append(c):o.append(d,c);let m=r.clearChat??{},b=m.enabled??!0,w=m.placement??"inline",T=null,L=null;if(b){let P=Ml(t,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=P.button,L=P.wrapper,w==="top-right"&&(L.style.right="48px"),w==="inline"&&o.appendChild(L)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:C}=Sl(t,{showClose:n,wrapperClassName:A});return s!=="top-right"&&o.appendChild(C),{header:o,iconHolder:d,headerTitle:f,headerSubtitle:g,closeButton:S,closeButtonWrapper:C,clearChatButton:T,clearChatButtonWrapper:L}},kr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",a=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Du=e=>{let t=fo({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 Iw(e,t,n){if(t?.length)for(let o of t){let r=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Xt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let a=ae(o.icon,16,"currentColor",2);a&&r.appendChild(a)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let a=v("div","persona-relative");a.appendChild(r);let s=$o({items:o.menuItems,onSelect:l=>n?.(l),anchor:a,position:"bottom-right"});a.appendChild(s.element),r.addEventListener("click",l=>{l.stopPropagation(),s.toggle()}),e.appendChild(a)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Fu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:a}=e,s=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.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=ul({label:s.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Xt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=v("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Xt.titleColor,Object.assign(c.style,Bu),c.textContent=s.title??"Chat Assistant",d.appendChild(c),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let C=r.onTitleClick;d.addEventListener("click",M=>{M.target.closest("button")||C()}),d.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),C())})}let S=r?.titleRowHover;S&&(d.style.borderRadius=S.borderRadius??"10px",d.style.padding=S.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=S.background??"",d.style.borderColor=S.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}l.appendChild(d);let f=s.closeButtonSize??"32px",g=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=n?"":"none",m.style.color=s.closeButtonColor||Xt.actionIconColor;let b=s.closeButtonIconName??"x",w=ae(b,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",o&&m.addEventListener("click",o),g.appendChild(m);let T=v("div","persona-flex persona-items-center persona-gap-1");p||Iw(T,r?.trailingActions,r?.onAction??a),T.appendChild(g),l.appendChild(T);let L=v("div");L.style.display="none";let A=v("span");return A.style.display="none",{header:l,iconHolder:L,headerTitle:c,headerSubtitle:A,closeButton:m,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:Du,minimal:Fu},Ou=e=>Tl[e]??Tl.default,ya=(e,t,n)=>{if(t?.render){let s=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),l=v("div");l.style.display="none";let p=v("span"),d=v("span"),c=v("button");c.style.display="none";let f=v("div");return f.style.display="none",{header:s,iconHolder:l,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",a=Ou(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&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var El=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 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},a=`${n*o}px`;t.style.maxHeight=a,t.style.overflowY="auto";let s=()=>{let p=t.style.maxHeight;if(p!==a){let c=parseFloat(p);if(Number.isFinite(c)&&c>0)return c}let d=n*r();return a=`${d}px`,t.style.maxHeight=a,d},l=()=>{t.addEventListener("input",()=>{t.style.height="auto";let p=Math.min(t.scrollHeight,s());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:l}},kl=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,a=t.stopIconName??"square",s=t.tooltipText??"Send message",l=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,f=t.size??"40px",g=t.backgroundColor,m=t.textColor,b=v("div","persona-send-button-wrapper"),w=ke("button",{className:Fn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?f:void 0,height:n?f:void 0,minWidth:n?f:void 0,minHeight:n?f:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&g||void 0,borderWidth: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,L=null;if(n){let C=parseFloat(t.iconSize??"")||Math.round((parseFloat(f)||24)*.5),M=t.iconStrokeWidth??2,P=m?.trim()||"currentColor";r?(T=ae(r,C,P,M),T?w.appendChild(T):w.textContent=o):w.textContent=o,L=ae(a,C,P,M)}else w.textContent=p;w.setAttribute("aria-label",s),b.appendChild(w),qt({anchor:w,trigger:b,text:()=>w.getAttribute("aria-label")??"",enabled:c});let A="send";return{button:w,wrapper:b,setMode:C=>{if(C===A)return;A=C;let M=C==="stop"?l:s;if(w.setAttribute("aria-label",M),n){if(T&&L){let P=C==="stop"?L:T;w.replaceChildren(P)}}else w.textContent=C==="stop"?d:p}}},Ll=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 s=e?.sendButton?.size??"40px",l=t.iconName??"mic",p=t.iconSize??s,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,f=t.iconColor??e?.sendButton?.textColor,g=v("div","persona-send-button-wrapper"),m=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:f||"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}}),w=ae(l,d,f||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",g.appendChild(m);let T=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return qt({anchor:m,trigger:g,text:()=>m.getAttribute("aria-label")??T,enabled:L}),{button:m,wrapper:g}},Pl=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??co).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let a=t.buttonIconName??"paperclip",s=n,l=parseFloat(s)||40,p=Math.round(l*.6),d=v("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:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1"}}),f=ae(a,p,"currentColor",1.5);f?c.appendChild(f):c.textContent="\u{1F4CE}",c.addEventListener("click",m=>{m.preventDefault(),r.click()}),d.appendChild(c);let g=t.buttonTooltipText??"Attach file";return qt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??g}),{button:c,wrapper:d,input:r,previewsContainer:o}},Rl=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 a=t.idleText??"Online";if(t.idleLink){let s=v("a");s.href=t.idleLink,s.target="_blank",s.rel="noopener noreferrer",s.textContent=a,s.style.color="inherit",s.style.textDecoration="none",o.appendChild(s)}else o.textContent=a;return o},Il=()=>ke("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Lr=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=Il(),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:a,attachAutoResize:s}=El(t);s();let l=kl(t),p=Ll(t),d=Pl(t),c=Rl(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(a);let f=ke("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=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 d&&g.append(d.wrapper),p&&m.append(p.wrapper),m.append(l.wrapper),f.append(g,m),r.append(f),r.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&a.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:f,leftActions:g,rightActions:m,setSendButtonMode:l.setMode}};var sy=()=>{let e=ke("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=ae("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"),a=ae("chevron-up",16,"currentColor",1.5);return a&&r.appendChild(a),e.append(t,o,r),{root:e,textNode:o}},Wl=e=>{let{config:t}=e,n=ke("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Il(),r=Rl(t);r.style.display="none";let{textarea:a,attachAutoResize:s}=El(t);a.style.maxHeight="100px",s();let l=kl(t),p=Ll(t),d=Pl(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"}}),f=v("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&f.append(d.wrapper);let g=v("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&g.append(p.wrapper),g.append(l.wrapper),c.addEventListener("click",b=>{b.target!==l.button&&b.target!==l.wrapper&&b.target!==p?.button&&b.target!==p?.wrapper&&b.target!==d?.button&&b.target!==d?.wrapper&&a.focus()}),d&&c.append(d.input),c.append(f,a,g),d&&n.append(d.previewsContainer),n.append(o,c,r);let m=c;return{footer:n,suggestions:o,composerForm:c,textarea:a,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:m,leftActions:f,rightActions:g,setSendButtonMode:l.setMode}};var Ww=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}},Hw=(e,t)=>{if(!e)return null;let n=Ww(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Bw=(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},Dw=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Nu=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(":"))},_u=320,dy=320,Fw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Ow=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Nw=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),_w=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Uw=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=v("span","persona-mention-chip-icon"),a=ae(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(ke("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},qw=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:t}))}return n},iy="\uE000",ly="\uE001",Vw=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${iy}${r}:${g}${ly}`,s=t.map((g,m)=>g.kind==="text"?g.text:a(m)).join(""),l=n(s);if(!t.every((g,m)=>g.kind==="text"||l.includes(a(m)))){e.replaceChildren(qw(t,o));return}e.innerHTML=l;let d=new RegExp(`${iy}${r}:(\\d+)${ly}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),f=[];for(let g=c.nextNode();g;g=c.nextNode())f.push(g);for(let g of f){let m=g;for(let b=d.exec(m.data);b;b=d.exec(m.data)){let w=t[Number(b[1])],T=m.splitText(b.index);T.data=T.data.slice(b[0].length),w?.kind==="mention"&&T.parentNode?.insertBefore(ms(w.ref,{readonly:!0,render:o}),T),m=T}}},zw=(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,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let d=v("img");d.alt=l.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${_u}px`,d.style.maxHeight=`${dy}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&&s())}),d.addEventListener("load",()=>{c=!0}),Dw(l.image)?(d.src=l.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},$w=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(!Nu(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=`${_u}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},jw=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(!Nu(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=`${_u}px`,r.style.maxHeight=`${dy}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}},Gw=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(!Nu(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}},Pr=()=>{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},Uu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:Pr};if(t){let r=t(o);if(r!==null)return r}return Pr()},Kw=(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},cy=(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},ks=(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},qu=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){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",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],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],g=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${f} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=(b,w,T)=>{let L=Tt({icon:b,label:w,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",T),L};return o&&g.appendChild(m("copy","Copy message","copy")),s&&g.appendChild(m("volume-2","Read aloud","read-aloud")),r&&g.appendChild(m("thumbs-up","Upvote","upvote")),a&&g.appendChild(m("thumbs-down","Downvote","downvote")),g},ba=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,d=s.timestamp,c=p?.show??!1,f=d?.show??!1,g=p?.position??"left",m=d?.position??"below",b=ks(e.role,l),w=v("div",b.join(" "));w.id=`bubble-${e.id}`,w.setAttribute("data-message-id",e.id),w.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(w.style.backgroundColor="transparent",w.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=Fw(e),L=e.content?.trim()??"",S=T.length>0&&L===Fi,C=vl(a?.widgetConfig?.features?.streamAnimation),M=a?.widgetConfig?.features?.streamAnimation?.plugins,P=e.role==="assistant"&&C.type!=="none"?ha(C.type,M):null,R=e.role==="assistant"&&P?.isAnimating?.(e)===!0,F=e.role==="assistant"&&P!==null&&(!!e.streaming||R);F&&P?.bubbleClass&&w.classList.add(P.bubbleClass);let O=document.createElement("div");O.classList.add("persona-message-content"),e.streaming&&O.classList.add("persona-content-streaming"),F&&P&&(P.containerClass&&O.classList.add(P.containerClass),O.style.setProperty("--persona-stream-step",`${C.speed}ms`),O.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let $=F?Cl(e.content??"",C.buffer,P,e,!!e.streaming):e.content??"",E=()=>{let oe=t({text:$,message:e,streaming:!!e.streaming,raw:e.rawContent});return F&&P?.wrap==="char"?As(oe,"char",e.id,{skipTags:P.skipTags}):F&&P?.wrap==="word"?As(oe,"word",e.id,{skipTags:P.skipTags}):oe},G=null;if(S?(G=document.createElement("div"),G.innerHTML=E(),G.style.display="none",O.appendChild(G)):e.contentSegments?.length?Vw(O,e.contentSegments,oe=>t({text:oe,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):O.innerHTML=E(),F&&P?.useCaret&&!S&&L){let oe=wl(),me=O.querySelectorAll(".persona-stream-char, .persona-stream-word"),Se=me[me.length-1];if(Se?.parentNode)Se.parentNode.insertBefore(oe,Se.nextSibling);else{let Ce=O.lastElementChild;Ce?Ce.appendChild(oe):O.appendChild(oe)}}if(f&&m==="inline"&&e.createdAt){let oe=cy(e,d,"span");oe.classList.add("persona-timestamp-inline");let me=O.lastElementChild;me?me.appendChild(oe):O.appendChild(oe)}if(T.length>0){let oe=zw(T,!S&&!!L,()=>{S&&G&&(G.style.display="")});oe?w.appendChild(oe):S&&G&&(G.style.display="")}let Q=Ow(e);if(Q.length>0){let oe=$w(Q);oe&&w.appendChild(oe)}let Z=Nw(e);if(Z.length>0){let oe=jw(Z);oe&&w.appendChild(oe)}let J=_w(e);if(J.length>0){let oe=Gw(J);oe&&w.appendChild(oe)}let fe=e.contentSegments?.length?null:Uw(e.contextMentions);if(fe&&w.appendChild(fe),w.appendChild(O),f&&m==="below"&&e.createdAt){let oe=cy(e,d);oe.classList.add("persona-mt-1"),w.appendChild(oe)}let ne=e.role==="assistant"?Hw(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let oe=!!($&&$.trim()),me=C.placeholder==="skeleton",Se=me&&C.buffer==="line"&&oe;if(oe)Se&&w.appendChild(Ss());else if(me)w.appendChild(Ss());else{let Ce=Uu("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);Ce&&w.appendChild(Ce)}}if(ne&&e.stopReason&&!e.streaming&&(L||(O.style.display="none"),w.appendChild(Bw(e.stopReason,ne))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let oe=qu(e,o,r);w.appendChild(oe)}if(!c||e.role==="system")return w;let ie=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Kw(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ie.append(w,ue):ie.append(ue,w),ie},py=(e,t,n,o,r,a)=>{let s=n??{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ba(e,t,n,o,r,a)};var Xw=40,Jw=(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=ae(t.name,Xw);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},uy=(e,t,n={})=>{let o=ke("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),a=v("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,a,t),iconHolder:o,title:r,subtitle:a,starterSuggestions:t}},xa=(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==="",Jw(e.iconHolder,t.icon),e.host.setAttribute("data-persona-welcome-variant",t.variant),e.host.setAttribute("data-persona-welcome-dismiss",t.dismiss)},Qw="data-persona-welcome-plugin",fy="data-persona-welcome-overlay",Hl="persona-welcome-overlay-active",Vu=new WeakMap,my=(e,t,n)=>{n.setAttribute(Qw,""),t.appendChild(n),t.setAttribute("data-persona-welcome-content","plugin"),t.setAttribute(fy,""),e.classList.contains(Hl)||(Vu.set(e,e.scrollTop),e.classList.add(Hl),e.scrollTop=0)},gy=(e,t,n)=>{n&&n!==t&&n.remove(),t.removeAttribute("data-persona-welcome-content"),t.removeAttribute(fy),e.classList.contains(Hl)&&(e.classList.remove(Hl),e.scrollTop=Vu.get(e)??e.scrollTop,Vu.delete(e))},hy=()=>{let e=ke("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return e.hidden=!0,e},Dl=(e,t,n)=>{if(e.replaceChildren(),!t){e.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ke("div",{className:ks("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},Yw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,yy=(e,t)=>{if(Yw()||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 Zw="Hello \u{1F44B}",eA="I can answer questions and help you get things done here.",by=new WeakSet,Mn=(e,t)=>!!e&&e[t]!==void 0,tA=(e,t)=>{!e||e.debug!==!0||!t.length||by.has(e)||(by.add(e),t.forEach(n=>console.warn(`[persona] ${n}`)))},mo=e=>{let t=e?.welcome,n=e?.copy,o=Mn(t,"variant")?t.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Mn(t,"dismiss")?t.dismiss:"never",a=[];return Mn(t,"title")&&Mn(n,"welcomeTitle")&&a.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Mn(t,"subtitle")&&Mn(n,"welcomeSubtitle")&&a.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Mn(t,"variant")&&Mn(n,"showWelcomeCard")&&a.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Mn(t,"message")&&a.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Mn(t,"dismiss")&&t.dismiss!=="on-first-message"&&a.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),tA(e,a),{title:Mn(t,"title")?t.title:n?.welcomeTitle??Zw,subtitle:Mn(t,"subtitle")?t.subtitle:n?.welcomeSubtitle??eA,icon:t?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:t?.message}},Xo=(e,t)=>e.variant==="none"?!1:e.dismiss==="never"?!0:!(t??[]).some(n=>n.role==="user");var xy=e=>{let t=e?.launcher?.enabled??!0,n=St(e);if(Ko(e)){let c=e?.launcher?.composerBar??{},f=v("div","persona-widget-wrapper persona-fixed persona-transition");f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=c.expandedSize??"anchored",f.style.zIndex=String(e?.launcher?.zIndex??Ut);let g=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");g.style.width="100%",f.appendChild(g);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=c.expandedSize??"anchored",m.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:f,panel:g,pillRoot:m}}if(n){let c=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),f=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(f),{wrapper:c,panel:f}}if(!t){let c=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),f=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),g=e?.launcher?.width??"100%";return c.style.width=g,f.style.width="100%",c.appendChild(f),{wrapper:c,panel:f}}let r=e?.launcher??{},a=r.position&&gn[r.position]?gn[r.position]:gn["bottom-right"],s=v("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String(e?.launcher?.zIndex??Ut);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??mn;return l.style.width=d,l.style.maxWidth=d,s.appendChild(l),{wrapper:s,panel:l}},zu=e=>{let t=ke("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Iu(e)}});return t.hidden=!0,t},vy=(e,t)=>{let n=zu("starter"),o=uy(e,n,{flatShadow:St(e)}),r=mo(e);Bl(o,r),xa(t,o.host,Xo(r,e?.initialMessages));let a=hy();return Dl(a,r.message,e),{welcome:o,greetingHost:a}},nA=(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}=Sl(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 a=e?.launcher?.clearChat?.enabled??!0,s=null,l=null;if(a){let R=Ml(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=R.button,l=R.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.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:f}=vy(e,d),{host:g,title:m,subtitle:b}=c,w=c.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),L=zu("followUp"),A=qo(e,!0);A&&(T.style.maxWidth=A,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),d.append(g,f,T,L);let S=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"}}),C=Wl({config:e}),{root:M,textNode:P}=sy();return n.append(p,r,d,S),l&&n.appendChild(l),{container:n,body:d,messagesWrapper:T,starterSuggestions:w,transcriptSuggestions:L,composerOverlay:S,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,welcomeHost:g,welcomeIconHolder:c.iconHolder,greetingHost:f,introTitle:m,introSubtitle:b,closeButton:o,closeButtonWrapper:r,clearChatButton:s,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:p,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions,setSendButtonMode:C.setSendButtonMode,peekBanner:M,peekTextNode:P}},Cy=(e,t=!0)=>{if(Ko(e))return nA(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,a=o?ya(e,o,{showClose:t}):fo({config:e,showClose:t}),s=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"}});s.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:p}=vy(e,s),{host:d,title:c,subtitle:f}=l,g=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),b=zu("followUp"),w=qo(e,!1);w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),s.append(d,p,m,b);let T=Lr({config:e}),L=e?.layout?.showFooter!==!1;r?kr(n,a,e):(a.header.style.display="none",kr(n,a,e)),n.append(s);let A=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 L||(T.footer.style.display="none"),n.append(T.footer),n.append(A),{container:n,body:s,messagesWrapper:m,starterSuggestions:g,transcriptSuggestions:b,composerOverlay:A,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:d,welcomeIconHolder:l.iconHolder,greetingHost:p,introTitle:c,introSubtitle:f,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.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 $u=(e,t)=>{let n=v("button");n.type="button",n.innerHTML=`
35
35
  <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>
36
36
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
37
37
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -39,14 +39,14 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
39
39
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
40
40
  </span>
41
41
  <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>
42
- `,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=Et(a),p=n.querySelector("[data-role='launcher-title']");if(p){let S=s.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let S=s.subtitle??"Here to help you get answers fast";c.textContent=S,c.setAttribute("title",S)}let d=n.querySelector(".persona-flex-col");d&&(s.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(s.agentIconHidden)u.style.display="none";else{let S=s.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,s.agentIconBackgroundColor?(u.style.backgroundColor=s.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",s.agentIconName){let C=parseFloat(S)||24,T=oe(s.agentIconName,C*.6,"var(--persona-text-inverse, #ffffff)",2);T?(u.appendChild(T),u.style.display=""):(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}else s.iconUrl?u.style.display="none":(u.textContent=s.agentIconText??"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let S=s.agentIconSize??"40px";g.style.height=S,g.style.width=S,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let S=s.callToActionIconSize??"32px";f.style.height=S,f.style.width=S,s.callToActionIconBackgroundColor?(f.style.backgroundColor=s.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(f.style.color=s.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let C=0;if(s.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=s.callToActionIconPadding,C=(parseFloat(s.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),s.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",s.callToActionIconName){let T=parseFloat(S)||24,W=Math.max(T-C,8),w=oe(s.callToActionIconName,W,"currentColor",2);w?f.appendChild(w):f.textContent=s.callToActionIconText??"\u2197"}else f.textContent=s.callToActionIconText??"\u2197"}let h=s.position&&Pn[s.position]?Pn[s.position]:Pn["bottom-right"],A="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?E:`${A} ${h}`,l||(n.style.zIndex=String(s.zIndex??Gt));let k="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=s.border??k,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:M,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=s.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}};var zg=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=qg(e),a=Vg(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},c={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,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:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:l,header:p,composer:c,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},zp=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>Vp(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Vp(e,n);return{instance:r,element:r.element}};var Uv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},qv=(e,t)=>{if(!e)return null;let n=Uv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Vv=(e,t)=>{let n=b("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},zv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},$p=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(":"))},jp=320,Kg=320,$v=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),jv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Gv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Kv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Xv=e=>{if(!e||e.length===0)return null;let t=Be("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Be("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=b("span","persona-mention-chip-icon"),a=oe(n.iconName??"at-sign",13,"currentColor",2);a&&r.appendChild(a),o.appendChild(r),o.appendChild(Be("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},Jv=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(qa(o.ref,{readonly:!0,render:t}))}return n},$g="\uE000",jg="\uE001",Qv=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),a=g=>`${$g}${r}:${g}${jg}`,s=t.map((g,f)=>g.kind==="text"?g.text:a(f)).join(""),l=n(s);if(!t.every((g,f)=>g.kind==="text"||l.includes(a(f)))){e.replaceChildren(Jv(t,o));return}e.innerHTML=l;let c=new RegExp(`${$g}${r}:(\\d+)${jg}`),d=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let g=d.nextNode();g;g=d.nextNode())u.push(g);for(let g of u){let f=g;for(let h=c.exec(f.data);h;h=c.exec(f.data)){let A=t[Number(h[1])],E=f.splitText(h.index);E.data=E.data.slice(h[0].length),A?.kind==="mention"&&E.parentNode?.insertBefore(qa(A.ref,{readonly:!0,render:o}),E),f=E}}},Yv=(e,t,n)=>{if(e.length===0)return null;try{let o=b("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,a=!1,s=()=>{a||(a=!0,o.remove(),n?.())};return e.forEach((l,p)=>{let c=b("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${jp}px`,c.style.maxHeight=`${Kg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&s())}),c.addEventListener("load",()=>{d=!0}),zv(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(s(),null):o}catch{return n?.(),null}},Zv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!$p(o.audio))return;let r=b("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},eC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!$p(o.video))return;let r=b("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${jp}px`,r.style.maxHeight=`${Kg}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}},tC=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!$p(o.data))return;let r=b("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}},lr=()=>{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},Gp=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:lr};if(t){let r=t(o);if(r!==null)return r}return lr()},nC=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=b("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},Gg=(e,t,n="div")=>{let o=b(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},Kp=(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},Xp=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,a=t.showDownvote??!0,s=t.showReadAloud??!1;if(!o&&!r&&!a&&!s){let h=b("div");return h.style.display="none",h.id=`actions-${e.id}`,h.setAttribute("data-actions-for",e.id),h}let l=t.visibility??"hover",p=t.align??"right",c=t.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(h,A,E)=>{let k=Mt({icon:h,label:A,size:14,className:"persona-message-action-btn"});return k.setAttribute("data-action",E),k};return o&&g.appendChild(f("copy","Copy message","copy")),s&&g.appendChild(f("volume-2","Read aloud","read-aloud")),r&&g.appendChild(f("thumbs-up","Upvote","upvote")),a&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Gr=(e,t,n,o,r,a)=>{let s=n??{},l=s.layout??"bubble",p=s.avatar,c=s.timestamp,d=p?.show??!1,u=c?.show??!1,g=p?.position??"left",f=c?.position??"below",h=Kp(e.role,l),A=b("div",h.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),l==="flat"?(A.style.backgroundColor="transparent",A.style.color=e.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=$v(e),k=e.content?.trim()??"",S=E.length>0&&k===fi,C=Ki(a?.widgetConfig?.features?.streamAnimation),T=a?.widgetConfig?.features?.streamAnimation?.plugins,W=e.role==="assistant"&&C.type!=="none"?zr(C.type,T):null,w=e.role==="assistant"&&W?.isAnimating?.(e)===!0,D=e.role==="assistant"&&W!==null&&(!!e.streaming||w);D&&W?.bubbleClass&&A.classList.add(W.bubbleClass);let F=document.createElement("div");F.classList.add("persona-message-content"),e.streaming&&F.classList.add("persona-content-streaming"),D&&W&&(W.containerClass&&F.classList.add(W.containerClass),F.style.setProperty("--persona-stream-step",`${C.speed}ms`),F.style.setProperty("--persona-stream-duration",`${C.duration}ms`));let j=D?Xi(e.content??"",C.buffer,W,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:j,message:e,streaming:!!e.streaming,raw:e.rawContent});return D&&W?.wrap==="char"?Ya(Z,"char",e.id,{skipTags:W.skipTags}):D&&W?.wrap==="word"?Ya(Z,"word",e.id,{skipTags:W.skipTags}):Z},q=null;if(S?(q=document.createElement("div"),q.innerHTML=O(),q.style.display="none",F.appendChild(q)):e.contentSegments?.length?Qv(F,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),a?.widgetConfig?.contextMentions?.renderMentionToken):F.innerHTML=O(),D&&W?.useCaret&&!S&&k){let Z=Ji(),me=F.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ae=me[me.length-1];if(Ae?.parentNode)Ae.parentNode.insertBefore(Z,Ae.nextSibling);else{let we=F.lastElementChild;we?we.appendChild(Z):F.appendChild(Z)}}if(u&&f==="inline"&&e.createdAt){let Z=Gg(e,c,"span");Z.classList.add("persona-timestamp-inline");let me=F.lastElementChild;me?me.appendChild(Z):F.appendChild(Z)}if(E.length>0){let Z=Yv(E,!S&&!!k,()=>{S&&q&&(q.style.display="")});Z?A.appendChild(Z):S&&q&&(q.style.display="")}let Q=jv(e);if(Q.length>0){let Z=Zv(Q);Z&&A.appendChild(Z)}let de=Gv(e);if(de.length>0){let Z=eC(de);Z&&A.appendChild(Z)}let be=Kv(e);if(be.length>0){let Z=tC(be);Z&&A.appendChild(Z)}let De=e.contentSegments?.length?null:Xv(e.contextMentions);if(De&&A.appendChild(De),A.appendChild(F),u&&f==="below"&&e.createdAt){let Z=Gg(e,c);Z.classList.add("persona-mt-1"),A.appendChild(Z)}let ie=e.role==="assistant"?qv(e.stopReason,a?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(j&&j.trim()),me=C.placeholder==="skeleton",Ae=me&&C.buffer==="line"&&Z;if(Z)Ae&&A.appendChild(Za());else if(me)A.appendChild(Za());else{let we=Gp("inline",a?.loadingIndicatorRenderer,a?.widgetConfig);we&&A.appendChild(we)}}if(ie&&e.stopReason&&!e.streaming&&(k||(F.style.display="none"),A.appendChild(Vv(e.stopReason,ie))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Xp(e,o,r);A.appendChild(Z)}if(!d||e.role==="system")return A;let ne=b("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),le=nC(p,e.role);return g==="right"||g==="left"&&e.role==="user"?ne.append(A,le):ne.append(le,A),ne},Xg=(e,t,n,o,r,a)=>{let s=n??{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Gr(e,t,n,o,r,a)};var Kr=new Set,oC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),rC=(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(`
43
- `):""},Jg=(e,t)=>{let n=Kr.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),a=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 c=oe(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},Jp=(e,t)=>{let n=e.reasoning,o=b("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??{},a=r.expandable!==!1,s=a&&Kr.has(e.id),l=n.status!=="complete",p=rC(e,r.previewMaxLines??3),c=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",a&&(c.setAttribute("aria-expanded",s?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=t?.reasoning??{},h=String(n.startedAt??Date.now()),A=()=>{let de=b("span","");return de.setAttribute("data-tool-elapsed",h),de.textContent=si(n),de},E=f.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:si(n),createElapsedElement:A});typeof E=="string"&&E.trim()?(u.textContent=E,d.appendChild(u)):E instanceof HTMLElement?d.appendChild(E):(u.textContent=g,d.appendChild(u));let k=b("span","persona-text-xs persona-text-persona-primary");k.textContent=Am(n),d.appendChild(k);let M=r.loadingAnimation??"none",S=f.activeTextTemplate,C=f.completeTextTemplate,T=l?S:C,W=E instanceof HTMLElement,w=(de,be)=>{u.textContent="";let De=ii(de,""),ie=0;for(let ge of De){let ne=ge.styles.length>0?(()=>{let le=b("span",ge.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(le),le})():u;if(ge.isDuration&&l)ne.appendChild(A());else{let le=ge.isDuration?si(n):ge.text;be?ie=Po(ne,le,ie):ne.appendChild(document.createTextNode(le))}}};if(!W&&T)if(k.style.display="none",u.style.display="",l&&M!=="none"){let de=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),M==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),w(T,!1)):(u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w(T,!0))}else w(T,!1);else if(!W&&l&&M!=="none"){u.style.display="";let de=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),M==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${M}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let be=u.textContent||g;u.textContent="",Po(u,be,0)}n.status==="complete"&&(u.style.display="none")}else W||(n.status==="complete"?u.style.display="none":u.style.display="");let D=null;if(a){D=b("div","persona-flex persona-items-center");let be=oe(s?"chevron-up":"chevron-down",16,"currentColor",2);be?D.appendChild(be):D.textContent=s?"Hide":"Show";let De=b("div","persona-flex persona-items-center persona-ml-auto");De.append(D),c.append(d,De)}else c.append(d);let F=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","reasoning"),F.style.display="none",F.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let de=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});oC(F,de)||(F.textContent=p),F.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(c,F),o;let j=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");j.style.display=s?"":"none";let O=n.chunks.join(""),q=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return q.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),j.appendChild(q),(()=>{if(c.setAttribute("aria-expanded",s?"true":"false"),D){D.innerHTML="";let be=oe(s?"chevron-up":"chevron-down",16,"currentColor",2);be?D.appendChild(be):D.textContent=s?"Hide":"Show"}j.style.display=s?"":"none",F.style.display=s?"none":F.textContent||F.childNodes.length?"":"none"})(),o.append(c,F,j),o};var Xr=new Set,aC=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),sC=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(-t).join(`
44
- `);let r=Ao(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
45
- `):""},Qp=(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)"},iC=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=sC(e,o?.previewMaxLines??3),s=n?Sm(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},c=s;return r==="tool-name"?c=n.name?.trim()||s:r==="tool-preview"&&a&&(c=a),l&&p.activeTextTemplate?c=bd(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=bd(n,p.completeTextTemplate,c)),{summary:c,previewText:a,isActive:l}},Qg=(e,t,n)=>{let o=Xr.has(e),r=n?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=oe(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Yp=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=b("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 a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&Xr.has(e.id),{summary:p,previewText:c,isActive:d}=iC(e,t),u=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",s&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let h=String(n.startedAt??Date.now()),A=()=>{let O=b("span","");return O.setAttribute("data-tool-elapsed",h),O.textContent=Fa(n),O},E=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:a.collapsedMode??"tool-call",isActive:d,config:t??{},elapsed:Fa(n),createElapsedElement:A});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=p,g.appendChild(f));let k=a.loadingAnimation??"none",M=o.activeTextTemplate,S=o.completeTextTemplate,C=d?M:S,T=E instanceof HTMLElement,W=(O,q)=>{f.textContent="";let Q=n.name?.trim()||"tool",de=ii(O,Q),be=0;for(let De of de){let ie=De.styles.length>0?(()=>{let ge=b("span",De.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return f.appendChild(ge),ge})():f;if(De.isDuration&&d)ie.appendChild(A());else{let ge=De.isDuration?Fa(n):De.text;q?be=Po(ie,ge,be):ie.appendChild(document.createTextNode(ge))}}};if(!T)if(d&&k!=="none"){let O=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",`${O}ms`),C&&W(C,!1);else if(f.classList.add(`persona-tool-loading-${k}`),f.style.setProperty("--persona-tool-anim-duration",`${O}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)),C)W(C,!0);else{let q=f.textContent||p;f.textContent="",Po(f,q,0)}}else C&&W(C,!1);let w=null;if(s){w=b("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show";let Q=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(w),u.append(g,Q)}else u.append(g);let D=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(D.setAttribute("data-persona-collapsed-preview","tool"),D.style.display="none",D.style.whiteSpace="pre-wrap",!l&&d&&a.activePreview&&c){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:c,isActive:d,config:t??{}});aC(D,O)||(D.textContent=c),D.style.display=""}if(!l&&d&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(u,D),r;let F=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(F.style.display=l?"":"none",o.contentBackgroundColor&&(F.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(F.style.color=o.contentTextColor),o.contentPaddingX&&(F.style.paddingLeft=o.contentPaddingX,F.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(F.style.paddingTop=o.contentPaddingY,F.style.paddingBottom=o.contentPaddingY),n.name){let O=b("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,F.appendChild(O)}if(n.args!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Arguments";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.args),O.append(q,Q),F.appendChild(O)}if(n.chunks&&n.chunks.length){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Activity";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=n.chunks.join(""),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=b("div","persona-space-y-1"),q=b("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(q.style.color=o.labelTextColor),q.textContent="Result";let Q=b("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Qp(Q,o),Q.textContent=Ao(n.result),O.append(q,Q),F.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=b("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,F.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",q=oe(l?"chevron-up":"chevron-down",16,O,2);q?w.appendChild(q):w.textContent=l?"Hide":"Show"}F.style.display=l?"":"none",D.style.display=l?"none":D.textContent||D.childNodes.length?"":"none"})(),r.append(u,D,F),r};var dr=new Map,il=e=>{let n=(e.startsWith(En)?e.slice(En.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Yg=e=>e?.approval!==!1?e?.approval:void 0,Zg=(e,t)=>{let n=Yg(t)?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},eh=(e,t,n)=>{let o=Yg(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 a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=oe(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},th=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Zg(e,n);eh(o,a,n),r.style.display=a?"":"none"};var ll=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=b("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.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 a;let s=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=b("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=oe(p,20,c,2);d&&l.appendChild(d);let u=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),f=b("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",g.appendChild(f),!r){let w=b("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"),g.appendChild(w)}u.appendChild(g);let A=n.toolType==="webmcp"||n.toolName.startsWith(En)?Pa(n.toolName):void 0,E=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...A?{displayTitle:A}:{},...n.reason?{reason:n.reason}:{}}),k=!n.toolName,M=E||(k?n.description:`The assistant wants to use \u201C${A??il(n.toolName)}\u201D.`),S=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=M,u.appendChild(S),n.reason){let w=b("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 D=b("span","persona-font-medium");D.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(D),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let C=o?.detailsDisplay??"collapsed",T=!!n.description&&!k,W=T||!!n.parameters;if(C!=="hidden"&&W){let w=Zg(e.id,t),D=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");D.type="button",D.setAttribute("data-expand-header","true"),D.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span");F.setAttribute("data-approval-details-label","true");let j=b("span","persona-inline-flex persona-items-center");j.setAttribute("data-approval-details-chevron","true"),D.append(F,j),eh(D,w,t),u.appendChild(D);let O=b("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",T){let q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,O.appendChild(q)}if(n.parameters){let q=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(q.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=Ao(n.parameters),O.appendChild(q)}u.appendChild(O)}if(r){let w=b("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let D=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");D.type="button",D.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",D.style.color=o?.approveButtonTextColor??"#ffffff",D.setAttribute("data-approval-action","approve");let F=oe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);F&&(F.style.marginRight="4px",D.appendChild(F));let j=document.createTextNode(o?.approveLabel??"Approve");D.appendChild(j);let O=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let q=oe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);q&&(q.style.marginRight="4px",O.appendChild(q));let Q=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(Q),w.append(D,O),u.appendChild(w)}return s.append(l,u),a.appendChild(s),a};function lC(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function nh(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=e,u=e.container??lC(t),g=!1,f=null,h=()=>{if(!g)return;let k=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${k.width}px`),s&&(n.style.maxWidth=`${k.width}px`);let M=n.getBoundingClientRect(),S=l?.()??null,C=S!=null?k.top+S:k.top,T=o==="top-start"||o==="top-end"?C-r-M.height:k.bottom+r,w=o==="bottom-end"||o==="top-end"?k.right-M.width:k.left,D=s?.()??null;if(D!=null){let F=Math.max(k.left,k.right-M.width);w=Math.min(Math.max(k.left+D,k.left),F)}n.style.top=`${T}px`,n.style.left=`${w}px`},A=()=>{g&&(g=!1,f&&(f(),f=null),n.remove())},E=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),h();let k=(t.ownerDocument??document).defaultView??window,M=t.ownerDocument??document,S=()=>{if(!t.isConnected){A(),d?.("anchor-removed");return}h()},C=W=>{let w=typeof W.composedPath=="function"?W.composedPath():[];w.includes(n)||w.includes(t)||(A(),d?.("outside"))},T=k.setTimeout(()=>{M.addEventListener("pointerdown",C,!0)},0);k.addEventListener("scroll",S,!0),k.addEventListener("resize",S),f=()=>{k.clearTimeout(T),M.removeEventListener("pointerdown",C,!0),k.removeEventListener("scroll",S,!0),k.removeEventListener("resize",S)},c?.()};return{get isOpen(){return g},open:E,close:A,toggle:()=>g?A():E(),reposition:h,destroy:A}}function oh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var dC=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),rh=(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))},cr=(e,t)=>{rh(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)},cC=e=>e?.approval!==!1?e?.approval:void 0,pC=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return dr.get(e)??n==="expanded"},Zp=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},uC=(e,t)=>{let n=b("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(En)?Pa(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??il(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},fC=e=>{let t=b("div","persona-approval-resolved"),n=oe("ban",15,"currentColor",2);n&&t.appendChild(n);let o=b("span","persona-approval-resolved-name");return o.textContent=e.toolName?il(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},mC=(e,t,n,o,r,a,s)=>{let l=b("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 p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",u=c||d,g=u&&pC(t.id,o),f=o?.showDetailsLabel??"Show details",h=o?.hideDetailsLabel??"Hide details",A=b("button","persona-approval-head");A.type="button",u?(A.setAttribute("data-action","toggle-params"),A.setAttribute("aria-expanded",g?"true":"false"),A.setAttribute("aria-label",g?h:f)):A.setAttribute("data-static","true");let E=b("span","persona-approval-logo"),k=oe("shield-check",16,"currentColor",2);k&&E.appendChild(k),A.appendChild(E);let M=uC(n,o);if(u){let D=b("span","persona-approval-toggle");D.setAttribute("aria-hidden","true");let F=oe("chevron-down",14,"currentColor",2);F&&D.appendChild(F),M.append(" "),M.appendChild(D)}A.appendChild(M),l.appendChild(A);let S=b("div","persona-approval-body");if(u){let D=b("div","persona-approval-details");if(D.setAttribute("data-role","params"),D.hidden=!g,c){let F=b("p","persona-approval-desc");o?.descriptionColor&&(F.style.color=o.descriptionColor),F.textContent=n.description,D.appendChild(F)}if(d){let F=b("pre","persona-approval-params");o?.parameterBackgroundColor&&(F.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(F.style.color=o.parameterTextColor),F.textContent=Ao(n.parameters),D.appendChild(F)}S.appendChild(D)}if(n.reason){let D=b("p","persona-approval-reason");o?.reasonColor?D.style.color=o.reasonColor:o?.descriptionColor&&(D.style.color=o.descriptionColor);let F=b("span","persona-approval-reason-label");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,D.append(F,document.createTextNode(n.reason)),S.appendChild(D)}let C=b("div","persona-approval-actions"),T=null,W=D=>{o?.approveButtonColor&&(D.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(D.style.color=o.approveButtonTextColor)},w=b("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"),s){let D=b("div","persona-approval-split"),F=b("button","persona-approval-primary");F.type="button",F.setAttribute("data-action","always"),W(F),F.append(o?.approveLabel??"Always allow",Zp("\u23CE"));let j=b("button","persona-approval-caret");j.type="button",j.setAttribute("data-action","toggle-menu"),j.setAttribute("aria-label","More options"),W(j);let O=oe("chevron-down",15,"currentColor",2);O&&j.appendChild(O),D.append(F,j),C.append(D,w),w.append(Zp("Esc"));let q=b("div","persona-approval-menu"),Q=b("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Zp("\u2318\u23CE")),q.appendChild(Q),T=nh({anchor:D,content:q,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,T),Q.addEventListener("click",()=>{cr(e,t.id),r()})}else{let D=b("button","persona-approval-primary persona-approval-primary--solo");D.type="button",D.setAttribute("data-action","allow"),W(D),D.append(o?.approveLabel??"Allow"),C.append(D,w)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",D=>{let F=D.target instanceof Element?D.target.closest("[data-action]"):null;if(!F)return;let j=F.getAttribute("data-action");if(j==="toggle-params"){let O=l.querySelector('[data-role="params"]');if(O){let q=O.hidden;O.hidden=!q,A.setAttribute("aria-expanded",q?"true":"false"),A.setAttribute("aria-label",q?h:f),dr.set(t.id,q)}return}if(j==="toggle-menu"){T?.toggle();return}if(j==="always"){cr(e,t.id),r({remember:!0});return}if(j==="allow"){cr(e,t.id),r();return}if(j==="deny"){cr(e,t.id),a();return}}),l},ah=()=>{let e=dC();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=cC(s);if(l.status!=="pending"){if(cr(e,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return fC(l)}rh(e,o.id);let c=p?.enableAlwaysAllow===!0,d=mC(e,o,l,p,r,a,c);if(c){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{oh(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),cr(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])cr(e,o);e.latestPendingApprovalId=null}}};var sh=e=>{let t=[],n=null;return{buttons:t,render:(r,a,s,l,p,c)=>{e.innerHTML="",t.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(a?a.getMessages():[])).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=a?a.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(h=>{let A=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");A.type="button",A.textContent=h,A.disabled=g,p?.fontFamily&&(A.style.fontFamily=f(p.fontFamily)),p?.fontWeight&&(A.style.fontWeight=p.fontWeight),p?.paddingX&&(A.style.paddingLeft=p.paddingX,A.style.paddingRight=p.paddingX),p?.paddingY&&(A.style.paddingTop=p.paddingY,A.style.paddingBottom=p.paddingY),A.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",d&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:h},bubbles:!0,composed:!0})),a.sendMessage(h))}),u.appendChild(A),t.push(A)}),e.appendChild(u),d){let h=JSON.stringify(r);h!==n&&(n=h,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var ns=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 os=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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{n(a.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 gC=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),hC=new Set(["step_start","execution_start"]),yC=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),bC=new Set(["step_complete","agent_turn_complete"]),xC=new Set(["flow_complete","agent_complete"]),ih=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),dh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,pr=(e,t)=>{let n=e[t];return dh(n)?n:void 0};function eu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function dl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function vC(e,t){return typeof t.type=="string"?t.type:e}function CC(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 wC(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 lh(e){let t=pr(e,"result"),n=[pr(e,"tokens"),pr(e,"totalTokens"),t?pr(t,"tokens"):void 0,pr(e,"usage"),t?pr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=un(o.output)??un(o.outputTokens)??un(o.completionTokens);if(r!==void 0)return r}return un(e.outputTokens)??un(e.completionTokens)??(t?un(t.outputTokens)??un(t.completionTokens):void 0)}function AC(e){let t=pr(e,"result");return un(e.executionTime)??un(e.executionTimeMs)??un(e.execution_time)??un(e.duration)??(t?un(t.executionTime)??un(t.executionTimeMs):void 0)}function SC(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var rs=class{constructor(t=SC){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:dl(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(!dh(n)){ih.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=vC(t,n),r=this.now();if(gC.has(o)){this.startRun(r);return}if(hC.has(o)){this.run||this.startRun(r);return}if(yC.has(o)){if(!wC(o,n))return;let a=CC(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+eu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:dl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(bC.has(o)){if(!this.run)return;let a=this.run,s=lh(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+eu(a.visibleCharCount),c=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:dl(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(xC.has(o)){if(!this.run)return;let a=this.run,s=lh(n),l=s??a.exactOutputTokens+eu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:dl(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(ih.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:AC(n)??o-t.startedAt}};function Jr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var MC={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)"}},TC={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},EC=["flowName","stepName","reasoningText","text","name","tool","toolName"],kC=100;function LC(e,t){let n={...MC,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return TC}function PC(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function RC(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"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function IC(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("."),a=n;for(let s of r)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function WC(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 HC(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 BC(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function DC(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 FC(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 a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function tu(e,t,n,o,r,a,s,l){let p=r.has(e.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Jr(c,o.classNames?.eventRow);let d=s.find(g=>g.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let g=d.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){let g=b("div",""),f=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");f.setAttribute("data-event-id",e.id);let h=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=oe(p?"chevron-down":"chevron-right","14px","currentColor",2);A&&h.appendChild(A);let E=b("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";E.textContent=k==="relative"?PC(e.timestamp,n):RC(e.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(t+1));let S=LC(e.type,o.badgeColors),C=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let T=o.descriptionFields??EC,W=IC(e.payload,T),w=null;W&&(w=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=W);let D=b("div","persona-flex-1 persona-min-w-0"),F=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),j=oe("clipboard","12px","currentColor",1.5);return j&&F.appendChild(j),F.addEventListener("click",async O=>{O.stopPropagation(),await WC(HC(e)),F.innerHTML="";let q=oe("check","12px","currentColor",1.5);q&&F.appendChild(q),setTimeout(()=>{F.innerHTML="";let Q=oe("clipboard","12px","currentColor",1.5);Q&&F.appendChild(Q)},1500)}),f.appendChild(h),f.appendChild(E),M&&f.appendChild(M),f.appendChild(C),w&&f.appendChild(w),f.appendChild(D),f.appendChild(F),g.appendChild(f),p&&g.appendChild(FC(e,s,l)),g}}function ch(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",u=r?.features?.eventStream??{},g=a.find(h=>h.renderEventStreamView);if(g?.renderEventStreamView&&r){let h=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>f().element,onClose:o});if(h)return{element:h,update:()=>{},destroy:()=>{}}}return f();function f(){let h=u.classNames,A=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Jr(A,h?.panel);let E=[],k="",M="",S=null,C=[],T={},W=0,w=$i(),D=0,F=0,j=!1,O=null,q=!1,Q=0,de=new Set,be=new Map,De="",ie="",ge=null,ne,le,Z,me,Ae=null,we=null,Se=null;function mt(){let _=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),$=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Jr($,h?.headerBar),s){we=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),we.style.cursor="help",Ae=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Ae.textContent="-- tok/s",Se=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Se.style.display="none",Se.style.pointerEvents="none";let Fe=we,Ht=Se,Sl=()=>{if(!Ht.textContent)return;let ms=Fe.getBoundingClientRect(),gs=_.getBoundingClientRect();Ht.style.left=`${ms.left-gs.left}px`,Ht.style.top=`${ms.bottom-gs.top+4}px`,Ht.style.display="block"},Do=()=>{Ht.style.display="none"};we.addEventListener("mouseenter",Sl),we.addEventListener("mouseleave",Do),we.appendChild(Ae)}let Y=b("div","persona-flex-1");ne=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let je=b("option","");je.value="",je.textContent="All events (0)",ne.appendChild(je),le=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),le.type="button",le.title="Copy All";let Qe=oe("clipboard-copy","12px","currentColor",1.5);Qe&&le.appendChild(Qe);let rt=b("span","persona-event-copy-all persona-text-xs");rt.textContent="Copy All",le.appendChild(rt),we&&$.appendChild(we),$.appendChild(Y),$.appendChild(ne),$.appendChild(le);let G=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Jr(G,h?.searchBar);let Ue=oe("search","14px","var(--persona-muted, #9ca3af)",1.5),he=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ue&&he.appendChild(Ue),Z=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Jr(Z,h?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",me=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let qe=oe("x","12px","currentColor",2);return qe&&me.appendChild(qe),G.appendChild(he),G.appendChild(Z),G.appendChild(me),_.appendChild($),_.appendChild(G),Se&&_.appendChild(Se),_}let We,_e=a.find(_=>_.renderEventStreamToolbar);_e?.renderEventStreamToolbar&&r?We=_e.renderEventStreamToolbar({config:r,defaultRenderer:()=>mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:$=>{k=$,et(),ae()},onSearchChange:$=>{M=$,et(),ae()}})??mt():We=mt();let Xe=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Xe.style.display="none";function $e(){if(!s||!Ae||!we)return;let _=s(),$=BC(_);Ae.textContent=$;let Y=DC(_);Se&&(Se.textContent=Y,Y||(Se.style.display="none")),we.setAttribute("aria-label",Y?`Throughput: ${$}, ${Y}`:`Throughput: ${$}`)}let Me=b("div","persona-flex-1 persona-min-h-0 persona-relative"),ke=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ke.style.height="100%";let Je=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Jr(Je,h?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Dt=oe(c,"14px","currentColor",2);Dt&&Je.appendChild(Dt);let Wt=b("span","");Wt.textContent=d,Je.appendChild(Wt);let Kt=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Kt.style.display="none",Me.appendChild(ke),Me.appendChild(Kt),Me.appendChild(Je),A.setAttribute("tabindex","0"),A.appendChild(We),A.appendChild(Xe),A.appendChild(Me);function wt(){let _=t.getAll(),$={};for(let G of _)$[G.type]=($[G.type]||0)+1;let Y=Object.keys($).sort(),je=Y.length!==C.length||!Y.every((G,Ue)=>G===C[Ue]),Re=!je&&Y.some(G=>$[G]!==T[G]),Qe=_.length!==Object.values(T).reduce((G,Ue)=>G+Ue,0);if(!je&&!Re&&!Qe||(C=Y,T=$,!ne))return;let rt=ne.value;if(ne.options[0].textContent=`All events (${_.length})`,je){for(;ne.options.length>1;)ne.remove(1);for(let G of Y){let Ue=b("option","");Ue.value=G,Ue.textContent=`${G} (${$[G]||0})`,ne.appendChild(Ue)}rt&&Y.includes(rt)?ne.value=rt:rt&&(ne.value="",k="")}else for(let G=1;G<ne.options.length;G++){let Ue=ne.options[G];Ue.textContent=`${Ue.value} (${$[Ue.value]||0})`}}function He(){let _=t.getAll();if(k&&(_=_.filter($=>$.type===k)),M){let $=M.toLowerCase();_=_.filter(Y=>Y.type.toLowerCase().includes($)||Y.payload.toLowerCase().includes($))}return _}function ce(){return k!==""||M!==""}function et(){W=0,D=0,w.resume(),Je.style.display="none"}function Pe(_){de.has(_)?de.delete(_):de.add(_),ge=_;let $=ke.scrollTop,Y=w.isFollowing();q=!0,w.pause(),ae(),ke.scrollTop=$,Y&&w.resume(),q=!1}function ue(){return Wo(ke,50)}function ae(){F=Date.now(),j=!1,$e(),wt();let _=t.getEvictedCount();_>0?(Xe.textContent=`${_.toLocaleString()} older events truncated`,Xe.style.display=""):Xe.style.display="none",E=He();let $=E.length,Y=t.getSize()>0;$===0&&Y&&ce()?(Kt.textContent=M?`No events matching '${M}'`:"No events matching filter",Kt.style.display="",ke.style.display="none"):(Kt.style.display="none",ke.style.display=""),le&&(le.title=ce()?`Copy Filtered (${$})`:"Copy All"),p&&!w.isFollowing()&&$>W&&(D+=$-W,Wt.textContent=d?`${d}${D>0?` (${D})`:""}`:"",Je.style.display=""),W=$;let je=t.getAll(),Re=je.length>0?je[0].timestamp:0,Qe=new Set(E.map(Ue=>Ue.id));for(let Ue of de)Qe.has(Ue)||de.delete(Ue);let rt=k!==De||M!==ie,G=be.size===0&&E.length>0;if(rt||G||E.length===0){ke.innerHTML="",be.clear();let Ue=document.createDocumentFragment();for(let he=0;he<E.length;he++){let qe=tu(E[he],he,Re,u,de,Pe,a,r);be.set(E[he].id,qe),Ue.appendChild(qe)}ke.appendChild(Ue),De=k,ie=M,ge=null}else{if(ge!==null){let he=be.get(ge);if(he&&he.parentNode===ke){let qe=E.findIndex(Fe=>Fe.id===ge);if(qe>=0){let Fe=tu(E[qe],qe,Re,u,de,Pe,a,r);ke.insertBefore(Fe,he),he.remove(),be.set(ge,Fe)}}ge=null}let Ue=new Set(E.map(he=>he.id));for(let[he,qe]of be)Ue.has(he)||(qe.remove(),be.delete(he));for(let he=0;he<E.length;he++){let qe=E[he];if(!be.has(qe.id)){let Fe=tu(qe,he,Re,u,de,Pe,a,r);be.set(qe.id,Fe),ke.appendChild(Fe)}}}w.isFollowing()&&(ke.scrollTop=ke.scrollHeight)}function Le(){if(Date.now()-F>=kC){O!==null&&(cancelAnimationFrame(O),O=null),ae();return}j||(j=!0,O=requestAnimationFrame(()=>{O=null,ae()}))}let it=(_,$)=>{if(!le)return;le.innerHTML="";let Y=oe(_,"12px","currentColor",1.5);Y&&le.appendChild(Y);let je=b("span","persona-text-xs");je.textContent="Copy All",le.appendChild(je),setTimeout(()=>{le.innerHTML="";let Re=oe("clipboard-copy","12px","currentColor",1.5);Re&&le.appendChild(Re);let Qe=b("span","persona-text-xs");Qe.textContent="Copy All",le.appendChild(Qe),le.disabled=!1},$)},pe=async()=>{if(le){le.disabled=!0;try{let _;ce()?_=E:n?(_=await n(),_.length===0&&(_=t.getAll())):_=t.getAll();let $=_.map(Y=>{try{return JSON.parse(Y.payload)}catch{return Y.payload}});await navigator.clipboard.writeText(JSON.stringify($,null,2)),it("check",1500)}catch{it("x",1500)}}},ve=()=>{ne&&(k=ne.value,et(),ae())},ee=()=>{!Z||!me||(me.style.display=Z.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{M=Z.value,et(),ae()},150))},P=()=>{!Z||!me||(Z.value="",M="",me.style.display="none",S&&clearTimeout(S),et(),ae())},U=()=>{if(q)return;let _=ke.scrollTop,{action:$,nextLastScrollTop:Y}=ji({following:w.isFollowing(),currentScrollTop:_,lastScrollTop:Q,nearBottom:ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=Y,$==="resume"?(w.resume(),D=0,Je.style.display="none"):$==="pause"&&(w.pause(),p&&(Wt.textContent=d,Je.style.display=""))},x=_=>{let $=Gi({following:w.isFollowing(),deltaY:_.deltaY,nearBottom:ue(),resumeWhenNearBottom:!0});$==="pause"?(w.pause(),p&&(Wt.textContent=d,Je.style.display="")):$==="resume"&&(w.resume(),D=0,Je.style.display="none")},H=()=>{p&&(ke.scrollTop=ke.scrollHeight,w.resume(),D=0,Je.style.display="none")},R=_=>{let $=_.target;if(!$||$.closest("button"))return;let Y=$.closest("[data-event-id]");if(!Y)return;let je=Y.getAttribute("data-event-id");je&&Pe(je)},B=_=>{if((_.metaKey||_.ctrlKey)&&_.key==="f"){_.preventDefault(),Z?.focus(),Z?.select();return}_.key==="Escape"&&(Z&&document.activeElement===Z?(P(),Z.blur(),A.focus()):o&&o())};le&&le.addEventListener("click",pe),ne&&ne.addEventListener("change",ve),Z&&Z.addEventListener("input",ee),me&&me.addEventListener("click",P),ke.addEventListener("scroll",U),ke.addEventListener("wheel",x,{passive:!0}),ke.addEventListener("click",R),Je.addEventListener("click",H),A.addEventListener("keydown",B);function K(){S&&clearTimeout(S),O!==null&&(cancelAnimationFrame(O),O=null),j=!1,be.clear(),le&&le.removeEventListener("click",pe),ne&&ne.removeEventListener("change",ve),Z&&Z.removeEventListener("input",ee),me&&me.removeEventListener("click",P),ke.removeEventListener("scroll",U),ke.removeEventListener("wheel",x),ke.removeEventListener("click",R),Je.removeEventListener("click",H),A.removeEventListener("keydown",B)}return{element:A,update:Le,destroy:K}}}function ph(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let g=u;return a.findIndex(f=>f===g||f.contains(g))},c=u=>{let g=p(u.target);if(g<0)return;let f=g;if(u.key===r)f=Math.min(g+1,a.length-1);else if(u.key===o)f=Math.max(g-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=a.length-1;else return;u.preventDefault(),f!==g&&t.onSelect(f)},d=u=>{let g=p(u.target);g>=0&&l(a[g])};return e.addEventListener("keydown",c),e.addEventListener("focusin",d),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(u,g){if(a=u,u.forEach((f,h)=>{f.setAttribute("role","tab");let A=h===g;f.setAttribute("aria-selected",A?"true":"false"),f.tabIndex=A||g<0&&h===0?0:-1}),s){let f=(g>=0?u[g]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){e.removeEventListener("keydown",c),e.removeEventListener("focusin",d)}}}function uh(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),g=typeof document<"u"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{g?.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"),q?.hide()};g&&g.addEventListener("click",()=>{f(),t.onDismiss?.()});let h=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");h.setAttribute("data-persona-theme-zone","artifact-pane"),r&&h.classList.add("persona-artifact-pane-document");let A=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");A.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&A.classList.add("persona-artifact-toolbar-document");let E=b("span","persona-text-xs persona-font-medium persona-truncate");E.textContent=a;let k=Mt({icon:"x",label:s});k.addEventListener("click",()=>{f(),t.onDismiss?.()});let M="rendered",S=qr({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:ee=>{M=ee==="source"?"source":"rendered",it()}}),C=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),T=n?.documentToolbarShowCopyLabel===!0,W=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,D=!!(W&&w&&w.length>0),F=null,j,O=null,q=null;if(r&&(T||W)&&!D){if(j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let ee=oe("chevron-down",14,"currentColor",2);ee&&j.appendChild(ee)}}else r&&D?(F=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=T?Zn({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=Mt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),F.append(j,O)):r?j=Mt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(j=Mt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&j.classList.add("persona-hidden"));let Q=r?Mt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Mt({icon:"refresh-cw",label:"Refresh"}),de=r?Mt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Mt({icon:"x",label:s}),be=Mt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&be.classList.add("persona-hidden");let De=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ie=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Me.find(H=>H.id===ke)??Me[Me.length-1],P=ee?.id??null,U=ee?.artifactType==="markdown"?ee.markdown??"":"",x=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:U,jsonPayload:x,id:P}},ne=async()=>{let ee=Me.find(P=>P.id===ke)??Me[Me.length-1];try{await navigator.clipboard.writeText(Xa(ee))}catch{}};if(j.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&D){let{markdown:P,jsonPayload:U,id:x}=ge();try{await ee({actionId:"primary",artifactId:x,markdown:P,jsonPayload:U})}catch{}return}await ne()}),O&&w?.length){let ee=()=>h.closest("[data-persona-root]")??document.body,P=()=>{q=Ro({items:w.map(U=>({id:U.id,label:U.label})),onSelect:async U=>{let{markdown:x,jsonPayload:H,id:R}=ge(),B=n?.onDocumentToolbarCopyMenuSelect;try{B?await B({actionId:U,artifactId:R,markdown:x,jsonPayload:H}):U==="markdown"||U==="md"?await navigator.clipboard.writeText(x):U==="json"||U==="source"?await navigator.clipboard.writeText(H):await navigator.clipboard.writeText(x||H)}catch{}},anchor:F??O,position:"bottom-right",portal:ee()})};h.isConnected?P():requestAnimationFrame(P),O.addEventListener("click",U=>{U.stopPropagation(),q?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}it()}),de.addEventListener("click",()=>{f(),t.onDismiss?.()});let le=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");if(r)A.replaceChildren(),F?C.append(F,Q,de):C.append(j,Q,de),C.insertBefore(De,de),C.insertBefore(be,de),A.append(S.element,le,C);else{let ee=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append(j,De,be,k),A.appendChild(E),A.appendChild(ee)}l&&(A.style.paddingLeft=l,A.style.paddingRight=l);let Z=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border");p&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Ae=b("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),we=ph(Z,{onSelect:ee=>t.onSelect(Me[ee].id)}),Se=ee=>{let P=ee.scrollWidth-ee.clientWidth,U=P>1,x=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",d&&U&&x>1),ee.classList.toggle("persona-artifact-tab-fade-end",u&&U&&x<P-1)},mt=0,We=()=>{if(mt)return;let ee=()=>{mt=0,Se(Z)};mt=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};Z.addEventListener("scroll",()=>We(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Se(Z)).observe(Z);let _e=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Xe=()=>{_e.scrollLeft=0},$e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Xe):setTimeout(Xe,0)};if(l){for(let ee of[Z,Ae])ee.style.paddingLeft=l,ee.style.paddingRight=l;_e.style.padding=l}h.appendChild(A),h.appendChild(Z),h.appendChild(Ae),h.appendChild(_e);let Me=[],ke=null,Je=!1,Dt=!1,Wt=!0,Kt=!1,wt=null,He="",ce=null,et=!1,Pe=ee=>ee.artifactType==="markdown"&&!!ee.file||r?M:"rendered",ue=ee=>{r||(ee&&!et?(A.insertBefore(S.element,E),et=!0):!ee&&et&&(S.element.remove(),et=!1))},ae=()=>ke&&Me.find(ee=>ee.id===ke)||Me[Me.length-1],Le=()=>{let ee=Ga(ae());if(!ee){De.replaceChildren();return}let P=ie.filter(U=>U.visible===void 0||U.visible(ee)).map(U=>Vr(U,{documentChrome:r,onClick:()=>{let x=Ga(ae());if(x)try{Promise.resolve(U.onClick(x)).catch(()=>{})}catch{}}}));De.replaceChildren(...P)},it=()=>{Le();let ee=r&&Me.length<=1,P=!!me;if(Z.classList.toggle("persona-hidden",ee||P),Ae.classList.toggle("persona-hidden",ee||!P),P&&me){let H=Me.map(R=>R.id).join("|")+" "+(ke??"");if(H!==He){He=H;let R=me({records:Me,selectedId:ke,onSelect:t.onSelect});Ae.firstElementChild!==R&&Ae.replaceChildren(R)}}else{we.beforeRender(),Z.replaceChildren();let H=[],R=-1;for(let[B,K]of Me.entries()){let _=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");_.type="button";let $=K.artifactType==="markdown"?K.file:void 0,Y=$?Dn($.path):K.title||K.id.slice(0,8),je=$?.path||K.title||Y;_.textContent=Y,_.title=je,_.setAttribute("aria-label",je),K.id===ke&&(_.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=B),_.addEventListener("click",()=>t.onSelect(K.id)),Z.appendChild(_),H.push(_)}if(we.render(H,R),R>=0&&ke!==wt){wt=ke;let B=H[R];typeof B.scrollIntoView=="function"&&B.scrollIntoView({block:"nearest",inline:"nearest"})}Se(Z)}let U=ke&&Me.find(H=>H.id===ke)||Me[Me.length-1];if(!U){_e.replaceChildren(),ce=null,ue(!1);return}let x=U.artifactType==="markdown"?U.file:void 0;if(ue(!!x),r){let H=x?Lo(x):U.artifactType==="markdown"?"MD":U.component??"Component",R=(U.title||"Document").trim(),B=x?Dn(x.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";le.textContent=`${B} \xB7 ${H}`}else E.textContent=x?Dn(x.path):a;ce?(ce.el.parentElement!==_e&&_e.replaceChildren(ce.el),ce.update(U)):(ce=Vi(U,{config:e,resolveViewMode:Pe}),_e.replaceChildren(ce.el)),_e.classList.toggle("persona-artifact-content-flush",!!_e.querySelector(".persona-code-pre"))},pe=()=>{let ee=Me.length>0;if(h.classList.toggle("persona-hidden",!ee),g){let x=((typeof h.closest=="function"?h.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ee&&x&&Je?(g.classList.remove("persona-hidden"),h.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open"))}},ve=()=>{Kt=!1,it(),pe()};return{element:h,backdrop:g,update(ee){let P=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,U=P!==ke;Me=ee.artifacts,ke=P,Me.length>0&&(Je=!0),Kt=!0,Wt&&ve(),U&&Xe()},setMobileOpen(ee){Je=ee,!ee&&g?(g.classList.add("persona-hidden"),h.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(ee){ee!==Dt&&(Dt=ee,$e());let P=oe(ee?"minimize":"maximize",16,"currentColor",2);P&&be.replaceChildren(P);let U=ee?"Collapse artifacts panel":"Expand artifacts panel";be.setAttribute("aria-label",U),be.title=U},setExpandToggleVisible(ee){be.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||j.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ie=ee,Le()},setTabFade(ee){let P=c(ee);P.start===d&&P.end===u||(d=P.start,u=P.end,Se(Z))},setRenderTabBar(ee){ee!==me&&(me=ee,He="",it())},setVisible(ee){ee!==Wt&&(Wt=ee,ee&&Kt&&ve())}}}function Zt(e){return e?.features?.artifacts?.enabled===!0}function fh(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 OC(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 mh=["panel","seamless","detached"];function nu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&mh.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ou(e){return!e||!Zt(e)?!1:nu(e)==="detached"}function as(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-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),OC(e),fh(e,t);return}let n=t.features?.artifacts?.layout,o=nu(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):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"),fh(e,t)}function ss(e,t){for(let l of mh)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"),!Zt(t))return;let n=t.features?.artifacts?.layout,o=nu(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function gh(e,t){return!t||!Zt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var NC=new Set(["__proto__","prototype","constructor"]),_C=new Set(["collapsed","card","panel","inline"]),hh=new Set(["markdown","component"]),UC=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ur=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),pl=e=>!NC.has(e),ru=e=>typeof e=="string"&&_C.has(e),fr=e=>Object.keys(e).length>0;function On(e,t,n,o){e.push({path:t,code:n,message:o})}var qC="Ignored because this key is not part of the persisted preference schema.",cl="Ignored an unsupported value.",VC="Expected collapsed, panel, or inline.",zC='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',yh={kind:"mode",message:cl},Qr={kind:"string",message:"Expected a CSS length string."},to={kind:"boolean"},$C={paneWidth:Qr,paneMaxWidth:Qr,paneMinWidth:Qr,expandedPanelWidth:Qr,resizableMinWidth:Qr,resizableMaxWidth:Qr,expandLauncherPanelWhenOpen:to,resizable:to},jC={kind:"object",message:"Expected a preference object.",children:{showToolCalls:to,showReasoning:to,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:cl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:cl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:cl},expandable:to,grouped:to}},reasoningDisplay:{kind:"object",children:{expandable:to,activePreview:to}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:yh,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:yh,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:hh,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:hh}}},filePreview:{kind:"object",children:{enabled:to}},layout:{kind:"object",children:$C}}}}};function bh(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:On(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:On(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:On(o,n,"invalid_value",t.message);case"mode":return ru(e)?on(e):On(o,n,"invalid_value",t.message);case"modeMap":{if(!ur(e))return On(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[s,l]of Object.entries(e)){let p=r?s:bo(s);pl(s)&&(r?r.has(s):UC.test(p))?ru(l)?a[p]=on(l):On(o,`${n}.${s}`,"invalid_value",VC):On(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":zC)}return fr(a)?a:void 0}case"object":{if(t.bareMode&&ru(e))return on(e);if(!ur(e))return On(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!pl(l)||!r.includes(l))&&On(o,a(l),"unknown_key",qC);let s={};for(let l of r){let p=t.children[l],c=bh(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&On(o,a(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,u=s[d];s[d]=ur(u)&&ur(c)?{...u,...c}:c}return fr(s)?s:void 0}}}function au(e){let t=[];return{preferences:(e===null?void 0:bh(e,jC,"",t))??{},issues:t}}function Yr(e){if(Array.isArray(e))return e.map(Yr);if(!ur(e))return e;let t={};for(let[n,o]of Object.entries(e))pl(n)&&o!==void 0&&(t[n]=Yr(o));return t}function xh(e,t){let n=Yr(e);for(let[o,r]of Object.entries(t)){if(!pl(o)||r===void 0)continue;let a=n[o];n[o]=ur(a)&&ur(r)?xh(a,r):Yr(r)}return n}function GC(e){let t={},n;for(let r of e){let a=au(r).preferences;n=vh(n,a.artifacts?.display),t=xh(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function KC(e,t){if(t===void 0)return e===void 0?void 0:Yr(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},a={...o?{default:o}:{},...fr(r)?{byMediaType:r}:{}};return fr(a)?a:void 0}function vh(e,t){if(t===void 0)return e===void 0?void 0:Yr(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},a=KC(n.files,t.files),s={...o?{default:o}:{},...fr(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return fr(s)?s:void 0}function su(e={},t){let n=GC(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??{},a={...r};if(n.artifacts.display!==void 0){let s=vh(r.display,n.artifacts.display);s!==void 0&&(a.display=s)}n.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(a.layout={...r.layout,...n.artifacts.layout}),o.artifacts=a}return o}function is(e){let t=e.preferences;return!t||!fr(t)?e:{...e,features:su(e.features??{},[t])}}function XC(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 JC(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 QC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function YC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function iu(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 a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Ch(e,t,n,o,r,a){let s=XC(r,200),l=YC(t,n,o,200);l=Math.max(s,l);let p=JC(a);return p!==null&&(l=Math.min(l,p)),QC(e,s,l)}var wh={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"}},lu=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=wh[s]??wh.init;a.classList.add("persona-form-card","persona-space-y-4");let p=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let h=b("p","persona-text-sm persona-text-persona-muted");h.textContent=l.description,p.appendChild(h)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(h=>{let A=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${h.name}`;let E=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");E.textContent=h.label,A.appendChild(E);let k=h.type??"text",M;k==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=k),M.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",M.id=`${t.id}-${s}-${h.name}`,M.name=h.name,M.placeholder=h.placeholder??"",h.required&&(M.required=!0),A.appendChild(M),d.appendChild(A)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(g),u.appendChild(f),d.appendChild(u),a.replaceChildren(p,d),d.addEventListener("submit",async h=>{h.preventDefault();let A=n.formEndpoint??"/form",E=new FormData(d),k={};E.forEach((M,S)=>{k[S]=M}),k.type=s,f.disabled=!0,g.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let S=await M.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(M){g.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var du=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(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ls=new du;var Ah=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ZC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences"]),Sh=(e,t,n)=>{if(!Ah(e)||!Ah(t)||ZC.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=Sh(e[r],t[r],a)}return o};function ul(e,t){let n=Sh(e,t,"");return Or(n)}var Mh=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var ew=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},tw=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 a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},ds=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=ew(e),n=tw(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},cu=e=>typeof e=="string"?e:e==null?"":String(e),mr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:cu(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=cu(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:cu(n.text)}}},Th=e=>Array.isArray(e)?e.map(t=>String(t)):[],cs=e=>{let t=new Set(Th(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Th(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((c,d)=>c||d?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),o();let p={action:l,message:a.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let d=()=>{e.emit("action:resubmit",p)},u=c(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var nw=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}},ow=e=>e.map(t=>({...t,streaming:!1})),rw=e=>e.map(t=>({...t,status:"complete"})),fl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?nw(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?ow(n.messages):void 0,artifacts:n.artifacts?rw(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 Zr=ho(Ys(),1);function aw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function sw(e,t){if(!aw(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 ml(){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,Zr.parse)(n,Zr.STR|Zr.OBJ),a=sw(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Eh(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function gl(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Ln.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function kh(){let e=ml();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lh(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 ps(e){let t=Lh(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 hl(e){let t=Lh(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 iw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function yl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=iw}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let h=document.createElement("h3");h.className="persona-feedback-title",h.textContent=o,f.appendChild(h);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=r,f.appendChild(A),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let k=[];for(let W=1;W<=5;W++){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",`${W} star${W>1?"s":""}: ${c[W-1]}`),w.title=c[W-1],w.dataset.rating=String(W),w.innerHTML=`
42
+ `,n.addEventListener("click",t);let o=a=>{let s=a.launcher??{},l=St(a),p=n.querySelector("[data-role='launcher-title']");if(p){let S=s.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=s.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(s.textHidden||l?c.style.display="none":c.style.display="");let f=n.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let S=s.agentIconSize??"40px";if(f.style.height=S,f.style.width=S,s.agentIconBackgroundColor?(f.style.backgroundColor=s.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",s.agentIconName){let C=parseFloat(S)||24,M=ae(s.agentIconName,C*.6,"var(--persona-text-inverse, #ffffff)",2);M?(f.appendChild(M),f.style.display=""):(f.textContent=s.agentIconText??"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=s.agentIconText??"\u{1F4AC}",f.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let S=s.agentIconSize??"40px";g.style.height=S,g.style.width=S,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(g.src=s.iconUrl,g.style.display="block"):g.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let S=s.callToActionIconSize??"32px";m.style.height=S,m.style.width=S,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let C=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,C=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",s.callToActionIconName){let M=parseFloat(S)||24,P=Math.max(M-C,8),R=ae(s.callToActionIconName,P,"currentColor",2);R?m.appendChild(R):m.textContent=s.callToActionIconText??"\u2197"}else m.textContent=s.callToActionIconText??"\u2197"}let b=s.position&&gn[s.position]?gn[s.position]:gn["bottom-right"],w="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${w} ${b}`,l||(n.style.zIndex=String(s.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",A="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=s.border??L,n.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,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=s.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}},oA="teaser-dismissed",Ay=new Set,wy=e=>{let t=e?.persistState;return`${(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"}${oA}`},rA=(e,t)=>{if(Ay.has(e))return!0;if(!t)return!1;try{return window.localStorage.getItem(e)==="1"}catch{return!1}},aA=(e,t)=>{if(Ay.add(e),!!t)try{window.localStorage.setItem(e,"1")}catch{}},sA=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,iA=e=>{let t=e?.launcher?.teaser;return!t||!t.text||e?.launcher?.enabled===!1||St(e??{})?null:t},Sy=(e,t)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=e??{},r=null,a=null,s=null,l=null,p=null,d=!1,c=!1,f=!1,g=!1,m=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,b=()=>{p!==null&&(clearTimeout(p),p=null)},w=()=>{!a||!d||(d=!1,a.hidden=!0)},T=J=>{b(),f=!0,w(),aA(wy(o),J&&m())},L=J=>{!r||f||T(J==="user"&&d)},A=()=>{p=null,!(!a||f||g)&&(c=!0,d=!0,a.hidden=!1,!(sA()||typeof a.animate!="function")&&a.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},S=()=>{!r||!a||f||c||g||rA(wy(o),m())||(b(),p=setTimeout(A,Math.max(0,r.delayMs??0)))},C=()=>{T(m()),t()},M=J=>{J.stopPropagation(),T(m())},R=$u(e,()=>{L("user"),t()}),F=()=>{b(),l?.removeEventListener("click",C),s?.removeEventListener("click",M),a?.remove(),a=null,l=null,s=null,d=!1},O=()=>{l=ke("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",C),s=ke("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),s.addEventListener("click",M),a=ke("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,s),n.insertBefore(a,R.element)},$=()=>{let J=o.launcher?.position??"bottom-right",fe=gn[J]??gn["bottom-right"];if(!a){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",R.element.style.position="";return}n.className=Fn("persona-launcher-surface",fe),n.setAttribute("data-teaser",J),n.style.zIndex=String(o.launcher?.zIndex??Ut),R.element.style.position="static"},E=J=>{let fe=iA(J);if(r=fe,!fe){F();return}a||O(),l.textContent=fe.text,s.hidden=fe.dismissible===!1,s.setAttribute("aria-label",fe.dismissLabel??"Dismiss message"),S()},G=J=>{o=J,R.update(J),E(J),$()},Q=(J,fe="user")=>{g=J,J&&L(fe)},Z=()=>{F(),R.destroy(),n.remove()};return n.appendChild(R.element),e&&(E(e),$()),{element:n,launcher:R,get teaser(){return a?{element:a,show:A,dismiss:T}:null},setPanelOpen:Q,update:G,destroy:Z}};var My=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=xy(e),a=Cy(e,t),s={wrapper:n,panel:o,pillRoot:r},l={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,starterSuggestions:a.starterSuggestions,transcriptSuggestions:a.transcriptSuggestions,composerOverlay:a.composerOverlay,welcomeHost:a.welcomeHost,welcomeIconHolder:a.welcomeIconHolder,greetingHost:a.greetingHost,introTitle:a.introTitle,introSubtitle:a.introSubtitle},p={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},d={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,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:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:l,header:p,composer:d,replaceHeader:g=>(p.element.replaceWith(g.header),p.element=g.header,p.iconHolder=g.iconHolder,p.headerTitle=g.headerTitle,p.headerSubtitle=g.headerSubtitle,p.closeButton=g.closeButton,p.closeButtonWrapper=g.closeButtonWrapper,p.clearChatButton=g.clearChatButton,p.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{d.footer.replaceWith(g),d.footer=g}}},ju=({config:e,plugins:t,onToggle:n})=>{let o=t.find(a=>a.renderLauncher);if(o?.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>$u(e,n).element,onToggle:n});if(a)return{instance:null,element:a}}let r=Sy(e,n);return{instance:r,element:r.element}};var lA=e=>{let t=e?.persistState;return(typeof t=="object"?t?.keyPrefix:void 0)??"persona-"},cA=(e,t,n)=>`${lA(e)}plugin:${t}:${n}`,Ty=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 a=s=>cA(e(),r,s);return{get:s=>{let l=a(s),p=o();if(p)try{return p.getItem(l)}catch{n=!0}return t.get(l)??null},set:(s,l)=>{let p=a(s),d=o();if(d)try{d.setItem(p,l);return}catch{n=!0}t.set(p,l)},remove:s=>{let l=a(s);t.delete(l);let p=o();if(p)try{p.removeItem(l)}catch{n=!0}}}}};var va=new Set,dA=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),pA=(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(`
43
+ `):""},Ey=(e,t)=>{let n=va.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),a=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 d=ae(n?"chevron-up":"chevron-down",16,"currentColor",2);d?l.appendChild(d):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",a&&(a.style.display=n?"none":a.textContent||a.childNodes.length?"":"none")},Gu=(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??{},a=r.expandable!==!1,s=a&&va.has(e.id),l=n.status!=="complete",p=pA(e,r.previewMaxLines??3),d=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",s?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",m=t?.reasoning??{},b=String(n.startedAt??Date.now()),w=()=>{let Z=v("span","");return Z.setAttribute("data-tool-elapsed",b),Z.textContent=Pi(n),Z},T=m.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:g,previewText:p,isActive:l,config:t??{},elapsed:Pi(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(f.textContent=T,c.appendChild(f)):T instanceof HTMLElement?c.appendChild(T):(f.textContent=g,c.appendChild(f));let L=v("span","persona-text-xs persona-text-persona-primary");L.textContent=Vg(n),c.appendChild(L);let A=r.loadingAnimation??"none",S=m.activeTextTemplate,C=m.completeTextTemplate,M=l?S:C,P=T instanceof HTMLElement,R=(Z,J)=>{f.textContent="";let fe=Ri(Z,""),ne=0;for(let ge of fe){let ie=ge.styles.length>0?(()=>{let ue=v("span",ge.styles.map(oe=>`persona-tool-text-${oe}`).join(" "));return f.appendChild(ue),ue})():f;if(ge.isDuration&&l)ie.appendChild(w());else{let ue=ge.isDuration?Pi(n):ge.text;J?ne=zo(ie,ue,ne):ie.appendChild(document.createTextNode(ue))}}};if(!P&&M)if(L.style.display="none",f.style.display="",l&&A!=="none"){let Z=m.loadingAnimationDuration??2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),R(M,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),R(M,!0))}else R(M,!1);else if(!P&&l&&A!=="none"){f.style.display="";let Z=m.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let J=f.textContent||g;f.textContent="",zo(f,J,0)}n.status==="complete"&&(f.style.display="none")}else P||(n.status==="complete"?f.style.display="none":f.style.display="");let F=null;if(a){F=v("div","persona-flex persona-items-center");let J=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);J?F.appendChild(J):F.textContent=s?"Hide":"Show";let fe=v("div","persona-flex persona-items-center persona-ml-auto");fe.append(F),d.append(c,fe)}else d.append(c);let O=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","reasoning"),O.style.display="none",O.style.whiteSpace="pre-wrap",!s&&l&&r.activePreview&&p){let Z=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:l,config:t??{}});dA(O,Z)||(O.textContent=p),O.style.display=""}if(!s&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!a)return o.append(d,O),o;let $=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=s?"":"none";let E=n.chunks.join(""),G=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return G.textContent=E||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(G),(()=>{if(d.setAttribute("aria-expanded",s?"true":"false"),F){F.innerHTML="";let J=ae(s?"chevron-up":"chevron-down",16,"currentColor",2);J?F.appendChild(J):F.textContent=s?"Hide":"Show"}$.style.display=s?"":"none",O.style.display=s?"none":O.textContent||O.childNodes.length?"":"none"})(),o.append(d,O,$),o};var Ca=new Set,uA=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),fA=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(-t).join(`
44
+ `);let r=Do(n.args).trim();return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
45
+ `):""},Ku=(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)"},mA=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",a=fA(e,o?.previewMaxLines??3),s=n?zg(n):"";if(!n)return{summary:s,previewText:a,isActive:!1};let l=n.status!=="complete",p=t?.toolCall??{},d=s;return r==="tool-name"?d=n.name?.trim()||s:r==="tool-preview"&&a&&(d=a),l&&p.activeTextTemplate?d=ld(n,p.activeTextTemplate,d):!l&&p.completeTextTemplate&&(d=ld(n,p.completeTextTemplate,d)),{summary:d,previewText:a,isActive:l}},ky=(e,t,n)=>{let o=Ca.has(e),r=n?.toolCall??{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),l=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let d=a.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)",f=ae(o?"chevron-up":"chevron-down",16,c,2);f?d.appendChild(f):d.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},Xu=(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 a=t?.features?.toolCallDisplay??{},s=a.expandable!==!1,l=s&&Ca.has(e.id),{summary:p,previewText:d,isActive:c}=mA(e,t),f=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");f.type="button",s&&(f.setAttribute("aria-expanded",l?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let g=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()),w=()=>{let E=v("span","");return E.setAttribute("data-tool-elapsed",b),E.textContent=cs(n),E},T=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:a.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:cs(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,g.appendChild(m)):T instanceof HTMLElement?g.appendChild(T):(m.textContent=p,g.appendChild(m));let L=a.loadingAnimation??"none",A=o.activeTextTemplate,S=o.completeTextTemplate,C=c?A:S,M=T instanceof HTMLElement,P=(E,G)=>{m.textContent="";let Q=n.name?.trim()||"tool",Z=Ri(E,Q),J=0;for(let fe of Z){let ne=fe.styles.length>0?(()=>{let ge=v("span",fe.styles.map(ie=>`persona-tool-text-${ie}`).join(" "));return m.appendChild(ge),ge})():m;if(fe.isDuration&&c)ne.appendChild(w());else{let ge=fe.isDuration?cs(n):fe.text;G?J=zo(ne,ge,J):ne.appendChild(document.createTextNode(ge))}}};if(!M)if(c&&L!=="none"){let E=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),L==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),C&&P(C,!1);else if(m.classList.add(`persona-tool-loading-${L}`),m.style.setProperty("--persona-tool-anim-duration",`${E}ms`),L==="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)),C)P(C,!0);else{let G=m.textContent||p;m.textContent="",zo(m,G,0)}}else C&&P(C,!1);let R=null;if(s){R=v("div","persona-flex persona-items-center");let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show";let Q=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Q.append(R),f.append(g,Q)}else f.append(g);let F=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!l&&c&&a.activePreview&&d){let E=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});uA(F,E)||(F.textContent=d),F.style.display=""}if(!l&&c&&a.activeMinHeight&&(r.style.minHeight=a.activeMinHeight),!s)return r.append(f,F),r;let O=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(O.style.display=l?"":"none",o.contentBackgroundColor&&(O.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(O.style.color=o.contentTextColor),o.contentPaddingX&&(O.style.paddingLeft=o.contentPaddingX,O.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(O.style.paddingTop=o.contentPaddingY,O.style.paddingBottom=o.contentPaddingY),n.name){let E=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?E.style.color=o.contentTextColor:o.headerTextColor&&(E.style.color=o.headerTextColor),E.textContent=n.name,O.appendChild(E)}if(n.args!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Arguments";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.args),E.append(G,Q),O.appendChild(E)}if(n.chunks&&n.chunks.length){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Activity";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=n.chunks.join(""),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=v("div","persona-space-y-1"),G=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(G.style.color=o.labelTextColor),G.textContent="Result";let Q=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");Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Ku(Q,o),Q.textContent=Do(n.result),E.append(G,Q),O.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(E.style.color=o.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,O.appendChild(E)}return(()=>{if(f.setAttribute("aria-expanded",l?"true":"false"),R){R.innerHTML="";let E=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",G=ae(l?"chevron-up":"chevron-down",16,E,2);G?R.appendChild(G):R.textContent=l?"Hide":"Show"}O.style.display=l?"":"none",F.style.display=l?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(f,F,O),r};var Rr=new Map,Fl=e=>{let n=(e.startsWith(Dn)?e.slice(Dn.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)},Ly=e=>e?.approval!==!1?e?.approval:void 0,Py=(e,t)=>{let n=Ly(t)?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ry=(e,t,n)=>{let o=Ly(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 a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let s=ae(t?"chevron-up":"chevron-down",14,"currentColor",2);s&&a.appendChild(s)}},Iy=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let a=Py(e,n);Ry(o,a,n),r.style.display=a?"":"none"};var Ol=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",a=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",a.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",a.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 a;let s=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 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=ae(p,20,d,2);c&&l.appendChild(c);let f=v("div","persona-flex-1 persona-min-w-0"),g=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",g.appendChild(m),!r){let R=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");R.setAttribute("data-approval-status",n.status),n.status==="approved"?(R.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",R.style.color="var(--persona-palette-colors-success-700, #15803d)",R.textContent="Approved"):n.status==="denied"?(R.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",R.style.color="var(--persona-palette-colors-error-700, #b91c1c)",R.textContent="Denied"):n.status==="timeout"&&(R.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",R.style.color="var(--persona-palette-colors-warning-700, #b45309)",R.textContent="Timeout"),g.appendChild(R)}f.appendChild(g);let w=n.toolType==="webmcp"||n.toolName.startsWith(Dn)?os(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...w?{displayTitle:w}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,A=T||(L?n.description:`The assistant wants to use \u201C${w??Fl(n.toolName)}\u201D.`),S=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=A,f.appendChild(S),n.reason){let R=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");R.setAttribute("data-approval-reason","true"),o?.reasonColor?R.style.color=o.reasonColor:o?.descriptionColor&&(R.style.color=o.descriptionColor);let F=v("span","persona-font-medium");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,R.appendChild(F),R.appendChild(document.createTextNode(n.reason)),f.appendChild(R)}let C=o?.detailsDisplay??"collapsed",M=!!n.description&&!L,P=M||!!n.parameters;if(C!=="hidden"&&P){let R=Py(e.id,t),F=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");F.type="button",F.setAttribute("data-expand-header","true"),F.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span");O.setAttribute("data-approval-details-label","true");let $=v("span","persona-inline-flex persona-items-center");$.setAttribute("data-approval-details-chevron","true"),F.append(O,$),Ry(F,R,t),f.appendChild(F);let E=v("div");if(E.setAttribute("data-approval-details","true"),E.style.display=R?"":"none",M){let G=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(G.style.color=o.descriptionColor),G.textContent=n.description,E.appendChild(G)}if(n.parameters){let G=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&&(G.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(G.style.color=o.parameterTextColor),G.style.fontSize="0.75rem",G.style.lineHeight="1rem",G.textContent=Do(n.parameters),E.appendChild(G)}f.appendChild(E)}if(r){let R=v("div","persona-flex persona-gap-2 persona-mt-2");R.setAttribute("data-approval-buttons","true");let F=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");F.type="button",F.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",F.style.color=o?.approveButtonTextColor??"#ffffff",F.setAttribute("data-approval-action","approve");let O=ae("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);O&&(O.style.marginRight="4px",F.appendChild(O));let $=document.createTextNode(o?.approveLabel??"Approve");F.appendChild($);let E=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");E.type="button",E.style.backgroundColor=o?.denyButtonColor??"transparent",E.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",E.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,E.setAttribute("data-approval-action","deny");let G=ae("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);G&&(G.style.marginRight="4px",E.appendChild(G));let Q=document.createTextNode(o?.denyLabel??"Deny");E.appendChild(Q),R.append(F,E),f.appendChild(R)}return s.append(l,f),a.appendChild(s),a};function gA(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function Wy(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:a=!1,horizontalOffset:s,verticalOffset:l,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,f=e.container??gA(t),g=!1,m=null,b=()=>{if(!g)return;let L=t.getBoundingClientRect();n.style.position="fixed",a&&(n.style.minWidth=`${L.width}px`),s&&(n.style.maxWidth=`${L.width}px`);let A=n.getBoundingClientRect(),S=l?.()??null,C=S!=null?L.top+S:L.top,M=o==="top-start"||o==="top-end"?C-r-A.height:L.bottom+r,R=o==="bottom-end"||o==="top-end"?L.right-A.width:L.left,F=s?.()??null;if(F!=null){let O=Math.max(L.left,L.right-A.width);R=Math.min(Math.max(L.left+F,L.left),O)}n.style.top=`${M}px`,n.style.left=`${R}px`},w=()=>{g&&(g=!1,m&&(m(),m=null),n.remove())},T=()=>{if(g)return;g=!0,p!=null&&(n.style.zIndex=String(p)),f.appendChild(n),b();let L=(t.ownerDocument??document).defaultView??window,A=t.ownerDocument??document,S=()=>{if(!t.isConnected){w(),c?.("anchor-removed");return}b()},C=P=>{let R=typeof P.composedPath=="function"?P.composedPath():[];R.includes(n)||R.includes(t)||(w(),c?.("outside"))},M=L.setTimeout(()=>{A.addEventListener("pointerdown",C,!0)},0);L.addEventListener("scroll",S,!0),L.addEventListener("resize",S),m=()=>{L.clearTimeout(M),A.removeEventListener("pointerdown",C,!0),L.removeEventListener("scroll",S,!0),L.removeEventListener("resize",S)},d?.()};return{get isOpen(){return g},open:T,close:w,toggle:()=>g?w():T(),reposition:b,destroy:w}}function Hy(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var hA=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),By=(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))},Ir=(e,t)=>{By(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)},yA=e=>e?.approval!==!1?e?.approval:void 0,bA=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Rr.get(e)??n==="expanded"},Ju=e=>{let t=v("span","persona-approval-kbd");return t.textContent=e,t},xA=(e,t)=>{let n=v("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Dn)?os(e.toolName):void 0,a=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(a)return n.textContent=a,n;let s=r??Fl(e.toolName),l=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=s,n.appendChild(p),l){n.append(" from ");let d=document.createElement("strong");d.textContent=l,n.appendChild(d)}return n},vA=e=>{let t=v("div","persona-approval-resolved"),n=ae("ban",15,"currentColor",2);n&&t.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=e.toolName?Fl(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},CA=(e,t,n,o,r,a,s)=>{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 p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",f=d||c,g=f&&bA(t.id,o),m=o?.showDetailsLabel??"Show details",b=o?.hideDetailsLabel??"Hide details",w=v("button","persona-approval-head");w.type="button",f?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",g?"true":"false"),w.setAttribute("aria-label",g?b:m)):w.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),L=ae("shield-check",16,"currentColor",2);L&&T.appendChild(L),w.appendChild(T);let A=xA(n,o);if(f){let F=v("span","persona-approval-toggle");F.setAttribute("aria-hidden","true");let O=ae("chevron-down",14,"currentColor",2);O&&F.appendChild(O),A.append(" "),A.appendChild(F)}w.appendChild(A),l.appendChild(w);let S=v("div","persona-approval-body");if(f){let F=v("div","persona-approval-details");if(F.setAttribute("data-role","params"),F.hidden=!g,d){let O=v("p","persona-approval-desc");o?.descriptionColor&&(O.style.color=o.descriptionColor),O.textContent=n.description,F.appendChild(O)}if(c){let O=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(O.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(O.style.color=o.parameterTextColor),O.textContent=Do(n.parameters),F.appendChild(O)}S.appendChild(F)}if(n.reason){let F=v("p","persona-approval-reason");o?.reasonColor?F.style.color=o.reasonColor:o?.descriptionColor&&(F.style.color=o.descriptionColor);let O=v("span","persona-approval-reason-label");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,F.append(O,document.createTextNode(n.reason)),S.appendChild(F)}let C=v("div","persona-approval-actions"),M=null,P=F=>{o?.approveButtonColor&&(F.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(F.style.color=o.approveButtonTextColor)},R=v("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),o?.denyButtonColor&&(R.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(R.style.color=o.denyButtonTextColor),R.append(o?.denyLabel??"Deny"),s){let F=v("div","persona-approval-split"),O=v("button","persona-approval-primary");O.type="button",O.setAttribute("data-action","always"),P(O),O.append(o?.approveLabel??"Always allow",Ju("\u23CE"));let $=v("button","persona-approval-caret");$.type="button",$.setAttribute("data-action","toggle-menu"),$.setAttribute("aria-label","More options"),P($);let E=ae("chevron-down",15,"currentColor",2);E&&$.appendChild(E),F.append(O,$),C.append(F,R),R.append(Ju("Esc"));let G=v("div","persona-approval-menu"),Q=v("button","persona-approval-menu-item");Q.type="button",Q.append("Allow once",Ju("\u2318\u23CE")),G.appendChild(Q),M=Wy({anchor:F,content:G,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,M),Q.addEventListener("click",()=>{Ir(e,t.id),r()})}else{let F=v("button","persona-approval-primary persona-approval-primary--solo");F.type="button",F.setAttribute("data-action","allow"),P(F),F.append(o?.approveLabel??"Allow"),C.append(F,R)}return S.appendChild(C),l.appendChild(S),l.addEventListener("click",F=>{let O=F.target instanceof Element?F.target.closest("[data-action]"):null;if(!O)return;let $=O.getAttribute("data-action");if($==="toggle-params"){let E=l.querySelector('[data-role="params"]');if(E){let G=E.hidden;E.hidden=!G,w.setAttribute("aria-expanded",G?"true":"false"),w.setAttribute("aria-label",G?b:m),Rr.set(t.id,G)}return}if($==="toggle-menu"){M?.toggle();return}if($==="always"){Ir(e,t.id),r({remember:!0});return}if($==="allow"){Ir(e,t.id),r();return}if($==="deny"){Ir(e,t.id),a();return}}),l},Dy=()=>{let e=hA();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:a,config:s})=>{let l=o?.approval;if(!l)return null;let p=yA(s);if(l.status!=="pending"){if(Ir(e,o.id),l.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return vA(l)}By(e,o.id);let d=p?.enableAlwaysAllow===!0,c=CA(e,o,l,p,r,a,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=g=>{Hy(g)||o.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Ir(e,o.id),g.key==="Escape"?a():g.metaKey||g.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Ir(e,o);e.latestPendingApprovalId=null}}};var Ls=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 Ps=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 s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{n(a.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 wA=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),AA=new Set(["step_start","execution_start"]),SA=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),MA=new Set(["step_complete","agent_turn_complete"]),TA=new Set(["flow_complete","agent_complete"]),Fy=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ny=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),hn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Wr=(e,t)=>{let n=e[t];return Ny(n)?n:void 0};function Qu(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Nl(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function EA(e,t){return typeof t.type=="string"?t.type:e}function kA(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 LA(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 Oy(e){let t=Wr(e,"result"),n=[Wr(e,"tokens"),Wr(e,"totalTokens"),t?Wr(t,"tokens"):void 0,Wr(e,"usage"),t?Wr(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=hn(o.output)??hn(o.outputTokens)??hn(o.completionTokens);if(r!==void 0)return r}return hn(e.outputTokens)??hn(e.completionTokens)??(t?hn(t.outputTokens)??hn(t.completionTokens):void 0)}function PA(e){let t=Wr(e,"result");return hn(e.executionTime)??hn(e.executionTimeMs)??hn(e.execution_time)??hn(e.duration)??(t?hn(t.executionTime)??hn(t.executionTimeMs):void 0)}function RA(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=RA){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:Nl(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(!Ny(n)){Fy.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=EA(t,n),r=this.now();if(wA.has(o)){this.startRun(r);return}if(AA.has(o)){this.run||this.startRun(r);return}if(SA.has(o)){if(!LA(o,n))return;let a=kA(n);if(!a)return;this.run||this.startRun(r);let s=this.run;s.firstDeltaAt??(s.firstDeltaAt=r),s.visibleCharCount+=a.length;let l=s.exactOutputTokens+Qu(s.visibleCharCount),p=r-s.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Nl(l,p),outputTokens:l,durationMs:p,source:s.exactOutputTokens>0?"usage":"estimate"};return}if(MA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n);s!==void 0&&(a.exactOutputTokens+=s,a.visibleCharCount=0);let l=a.exactOutputTokens>0,p=a.exactOutputTokens+Qu(a.visibleCharCount),d=this.resolveDuration(a,n,r);this.metric={status:"running",tokensPerSecond:Nl(p,d),outputTokens:p,durationMs:d,source:l?"usage":"estimate"};return}if(TA.has(o)){if(!this.run)return;let a=this.run,s=Oy(n),l=s??a.exactOutputTokens+Qu(a.visibleCharCount),p=s!==void 0||a.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(a,n,r);this.metric={status:"complete",tokensPerSecond:Nl(l,d),outputTokens:l,durationMs:d,source:p},this.run=null;return}if(Fy.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:PA(n)??o-t.startedAt}};function wa(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var IA={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)"}},WA={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},HA=["flowName","stepName","reasoningText","text","name","tool","toolName"],BA=100;function DA(e,t){let n={...IA,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return WA}function FA(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function OA(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"),a=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${a}`}function NA(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("."),a=n;for(let s of r)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function _A(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 UA(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 qA(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function VA(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 zA(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 a=t.find(l=>l.renderEventStreamPayload);if(a?.renderEventStreamPayload&&n){let l=a.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>s(),parsedPayload:r});if(l)return l}return s();function s(){let l=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),p=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function Yu(e,t,n,o,r,a,s,l){let p=r.has(e.id),d=v("div","persona-border-b persona-border-persona-divider persona-text-xs");wa(d,o.classNames?.eventRow);let c=s.find(g=>g.renderEventStreamRow);if(c?.renderEventStreamRow&&l){let g=c.renderEventStreamRow({event:e,index:t,config:l,defaultRenderer:()=>f(),isExpanded:p,onToggleExpand:()=>a(e.id)});if(g)return d.appendChild(g),d}return d.appendChild(f()),d;function f(){let g=v("div",""),m=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");m.setAttribute("data-event-id",e.id);let b=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=ae(p?"chevron-down":"chevron-right","14px","currentColor",2);w&&b.appendChild(w);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";T.textContent=L==="relative"?FA(e.timestamp,n):OA(e.timestamp);let A=null;o.showSequenceNumbers!==!1&&(A=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),A.textContent=String(t+1));let S=DA(e.type,o.badgeColors),C=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");C.style.backgroundColor=S.bg,C.style.color=S.text,C.style.borderColor=S.text+"50",C.textContent=e.type;let M=o.descriptionFields??HA,P=NA(e.payload,M),R=null;P&&(R=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),R.textContent=P);let F=v("div","persona-flex-1 persona-min-w-0"),O=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),$=ae("clipboard","12px","currentColor",1.5);return $&&O.appendChild($),O.addEventListener("click",async E=>{E.stopPropagation(),await _A(UA(e)),O.innerHTML="";let G=ae("check","12px","currentColor",1.5);G&&O.appendChild(G),setTimeout(()=>{O.innerHTML="";let Q=ae("clipboard","12px","currentColor",1.5);Q&&O.appendChild(Q)},1500)}),m.appendChild(b),m.appendChild(T),A&&m.appendChild(A),m.appendChild(C),R&&m.appendChild(R),m.appendChild(F),m.appendChild(O),g.appendChild(m),p&&g.appendChild(zA(e,s,l)),g}}function _y(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:a=[],getThroughput:s}=e,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,d=l?.iconName??"arrow-down",c=l?.label??"",f=r?.features?.eventStream??{},g=a.find(b=>b.renderEventStreamView);if(g?.renderEventStreamView&&r){let b=g.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(b)return{element:b,update:()=>{},destroy:()=>{}}}return m();function m(){let b=f.classNames,w=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");wa(w,b?.panel);let T=[],L="",A="",S=null,C=[],M={},P=0,R=yl(),F=0,O=0,$=!1,E=null,G=!1,Q=0,Z=new Set,J=new Map,fe="",ne="",ge=null,ie,ue,oe,me,Se=null,Ce=null,Be=null;function ut(){let V=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),X=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(wa(X,b?.headerBar),s){Ce=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),Ce.style.cursor="help",Se=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",Be=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Be.style.display="none",Be.style.pointerEvents="none";let wt=Ce,yn=Be,Us=()=>{if(!yn.textContent)return;let bn=wt.getBoundingClientRect(),it=V.getBoundingClientRect();yn.style.left=`${bn.left-it.left}px`,yn.style.top=`${bn.bottom-it.top+4}px`,yn.style.display="block"},te=()=>{yn.style.display="none"};Ce.addEventListener("mouseenter",Us),Ce.addEventListener("mouseleave",te),Ce.appendChild(Se)}let ce=v("div","persona-flex-1");ie=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ve=v("option","");Ve.value="",Ve.textContent="All events (0)",ie.appendChild(Ve),ue=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),ue.type="button",ue.title="Copy All";let Pe=ae("clipboard-copy","12px","currentColor",1.5);Pe&&ue.appendChild(Pe);let ze=v("span","persona-event-copy-all persona-text-xs");ze.textContent="Copy All",ue.appendChild(ze),Ce&&X.appendChild(Ce),X.appendChild(ce),X.appendChild(ie),X.appendChild(ue);let Ue=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");wa(Ue,b?.searchBar);let We=ae("search","14px","var(--persona-muted, #9ca3af)",1.5),we=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");We&&we.appendChild(We),oe=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),wa(oe,b?.searchInput),oe.type="text",oe.placeholder="Search event payloads...",me=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),me.type="button",me.style.display="none";let nt=ae("x","12px","currentColor",2);return nt&&me.appendChild(nt),Ue.appendChild(we),Ue.appendChild(oe),Ue.appendChild(me),V.appendChild(X),V.appendChild(Ue),Be&&V.appendChild(Be),V}let Je,Qe=a.find(V=>V.renderEventStreamToolbar);Qe?.renderEventStreamToolbar&&r?Je=Qe.renderEventStreamToolbar({config:r,defaultRenderer:()=>ut(),eventCount:t.getSize(),filteredCount:0,onFilterChange:X=>{L=X,Le(),Te()},onSearchChange:X=>{A=X,Le(),Te()}})??ut():Je=ut();let Ne=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Ne.style.display="none";function _e(){if(!s||!Se||!Ce)return;let V=s(),X=qA(V);Se.textContent=X;let ce=VA(V);Be&&(Be.textContent=ce,ce||(Be.style.display="none")),Ce.setAttribute("aria-label",ce?`Throughput: ${X}, ${ce}`:`Throughput: ${X}`)}let Ae=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Me=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Me.style.height="100%";let qe=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");wa(qe,b?.scrollIndicator),qe.style.display="none",qe.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Jt=ae(d,"14px","currentColor",2);Jt&&qe.appendChild(Jt);let gt=v("span","");gt.textContent=c,qe.appendChild(gt);let Bt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Bt.style.display="none",Ae.appendChild(Me),Ae.appendChild(Bt),Ae.appendChild(qe),w.setAttribute("tabindex","0"),w.appendChild(Je),w.appendChild(Ne),w.appendChild(Ae);function Tn(){let V=t.getAll(),X={};for(let Ue of V)X[Ue.type]=(X[Ue.type]||0)+1;let ce=Object.keys(X).sort(),Ve=ce.length!==C.length||!ce.every((Ue,We)=>Ue===C[We]),de=!Ve&&ce.some(Ue=>X[Ue]!==M[Ue]),Pe=V.length!==Object.values(M).reduce((Ue,We)=>Ue+We,0);if(!Ve&&!de&&!Pe||(C=ce,M=X,!ie))return;let ze=ie.value;if(ie.options[0].textContent=`All events (${V.length})`,Ve){for(;ie.options.length>1;)ie.remove(1);for(let Ue of ce){let We=v("option","");We.value=Ue,We.textContent=`${Ue} (${X[Ue]||0})`,ie.appendChild(We)}ze&&ce.includes(ze)?ie.value=ze:ze&&(ie.value="",L="")}else for(let Ue=1;Ue<ie.options.length;Ue++){let We=ie.options[Ue];We.textContent=`${We.value} (${X[We.value]||0})`}}function En(){let V=t.getAll();if(L&&(V=V.filter(X=>X.type===L)),A){let X=A.toLowerCase();V=V.filter(ce=>ce.type.toLowerCase().includes(X)||ce.payload.toLowerCase().includes(X))}return V}function et(){return L!==""||A!==""}function Le(){P=0,F=0,R.resume(),qe.style.display="none"}function he(V){Z.has(V)?Z.delete(V):Z.add(V),ge=V;let X=Me.scrollTop,ce=R.isFollowing();G=!0,R.pause(),Te(),Me.scrollTop=X,ce&&R.resume(),G=!1}function tt(){return uo(Me,50)}function Te(){O=Date.now(),$=!1,_e(),Tn();let V=t.getEvictedCount();V>0?(Ne.textContent=`${V.toLocaleString()} older events truncated`,Ne.style.display=""):Ne.style.display="none",T=En();let X=T.length,ce=t.getSize()>0;X===0&&ce&&et()?(Bt.textContent=A?`No events matching '${A}'`:"No events matching filter",Bt.style.display="",Me.style.display="none"):(Bt.style.display="none",Me.style.display=""),ue&&(ue.title=et()?`Copy Filtered (${X})`:"Copy All"),p&&!R.isFollowing()&&X>P&&(F+=X-P,gt.textContent=c?`${c}${F>0?` (${F})`:""}`:"",qe.style.display=""),P=X;let Ve=t.getAll(),de=Ve.length>0?Ve[0].timestamp:0,Pe=new Set(T.map(We=>We.id));for(let We of Z)Pe.has(We)||Z.delete(We);let ze=L!==fe||A!==ne,Ue=J.size===0&&T.length>0;if(ze||Ue||T.length===0){Me.innerHTML="",J.clear();let We=document.createDocumentFragment();for(let we=0;we<T.length;we++){let nt=Yu(T[we],we,de,f,Z,he,a,r);J.set(T[we].id,nt),We.appendChild(nt)}Me.appendChild(We),fe=L,ne=A,ge=null}else{if(ge!==null){let we=J.get(ge);if(we&&we.parentNode===Me){let nt=T.findIndex(wt=>wt.id===ge);if(nt>=0){let wt=Yu(T[nt],nt,de,f,Z,he,a,r);Me.insertBefore(wt,we),we.remove(),J.set(ge,wt)}}ge=null}let We=new Set(T.map(we=>we.id));for(let[we,nt]of J)We.has(we)||(nt.remove(),J.delete(we));for(let we=0;we<T.length;we++){let nt=T[we];if(!J.has(nt.id)){let wt=Yu(nt,we,de,f,Z,he,a,r);J.set(nt.id,wt),Me.appendChild(wt)}}}R.isFollowing()&&(Me.scrollTop=Me.scrollHeight)}function be(){if(Date.now()-O>=BA){E!==null&&(cancelAnimationFrame(E),E=null),Te();return}$||($=!0,E=requestAnimationFrame(()=>{E=null,Te()}))}let re=(V,X)=>{if(!ue)return;ue.innerHTML="";let ce=ae(V,"12px","currentColor",1.5);ce&&ue.appendChild(ce);let Ve=v("span","persona-text-xs");Ve.textContent="Copy All",ue.appendChild(Ve),setTimeout(()=>{ue.innerHTML="";let de=ae("clipboard-copy","12px","currentColor",1.5);de&&ue.appendChild(de);let Pe=v("span","persona-text-xs");Pe.textContent="Copy All",ue.appendChild(Pe),ue.disabled=!1},X)},xe=async()=>{if(ue){ue.disabled=!0;try{let V;et()?V=T:n?(V=await n(),V.length===0&&(V=t.getAll())):V=t.getAll();let X=V.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(X,null,2)),re("check",1500)}catch{re("x",1500)}}},kn=()=>{ie&&(L=ie.value,Le(),Te())},ee=()=>{!oe||!me||(me.style.display=oe.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{A=oe.value,Le(),Te()},150))},I=()=>{!oe||!me||(oe.value="",A="",me.style.display="none",S&&clearTimeout(S),Le(),Te())},B=()=>{if(G)return;let V=Me.scrollTop,{action:X,nextLastScrollTop:ce}=bl({following:R.isFollowing(),currentScrollTop:V,lastScrollTop:Q,nearBottom:tt(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Q=ce,X==="resume"?(R.resume(),F=0,qe.style.display="none"):X==="pause"&&(R.pause(),p&&(gt.textContent=c,qe.style.display=""))},y=V=>{let X=xl({following:R.isFollowing(),deltaY:V.deltaY,nearBottom:tt(),resumeWhenNearBottom:!0});X==="pause"?(R.pause(),p&&(gt.textContent=c,qe.style.display="")):X==="resume"&&(R.resume(),F=0,qe.style.display="none")},D=()=>{p&&(Me.scrollTop=Me.scrollHeight,R.resume(),F=0,qe.style.display="none")},H=V=>{let X=V.target;if(!X||X.closest("button"))return;let ce=X.closest("[data-event-id]");if(!ce)return;let Ve=ce.getAttribute("data-event-id");Ve&&he(Ve)},N=V=>{if((V.metaKey||V.ctrlKey)&&V.key==="f"){V.preventDefault(),oe?.focus(),oe?.select();return}V.key==="Escape"&&(oe&&document.activeElement===oe?(I(),oe.blur(),w.focus()):o&&o())};ue&&ue.addEventListener("click",xe),ie&&ie.addEventListener("change",kn),oe&&oe.addEventListener("input",ee),me&&me.addEventListener("click",I),Me.addEventListener("scroll",B),Me.addEventListener("wheel",y,{passive:!0}),Me.addEventListener("click",H),qe.addEventListener("click",D),w.addEventListener("keydown",N);function K(){S&&clearTimeout(S),E!==null&&(cancelAnimationFrame(E),E=null),$=!1,J.clear(),ue&&ue.removeEventListener("click",xe),ie&&ie.removeEventListener("change",kn),oe&&oe.removeEventListener("input",ee),me&&me.removeEventListener("click",I),Me.removeEventListener("scroll",B),Me.removeEventListener("wheel",y),Me.removeEventListener("click",H),qe.removeEventListener("click",D),w.removeEventListener("keydown",N)}return{element:w,update:be,destroy:K}}}function Uy(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let a=[],s=!1,l=f=>{typeof f.scrollIntoView=="function"&&f.scrollIntoView({block:"nearest",inline:"nearest"})},p=f=>{let g=f;return a.findIndex(m=>m===g||m.contains(g))},d=f=>{let g=p(f.target);if(g<0)return;let m=g;if(f.key===r)m=Math.min(g+1,a.length-1);else if(f.key===o)m=Math.max(g-1,0);else if(f.key==="Home")m=0;else if(f.key==="End")m=a.length-1;else return;f.preventDefault(),m!==g&&t.onSelect(m)},c=f=>{let g=p(f.target);g>=0&&l(a[g])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){s=typeof document<"u"&&e.contains(document.activeElement)},render(f,g){if(a=f,f.forEach((m,b)=>{m.setAttribute("role","tab");let w=b===g;m.setAttribute("aria-selected",w?"true":"false"),m.tabIndex=w||g<0&&b===0?0:-1}),s){let m=(g>=0?f[g]:void 0)??f[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function qy(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",a=n?.toolbarTitle??"Artifacts",s=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=ee=>({start:ee===!1?!1:typeof ee=="object"&&ee?ee.start!==!1:!0,end:ee===!1?!1:typeof ee=="object"&&ee?ee.end!==!1:!0}),{start:c,end:f}=d(n?.tabFade),g=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=()=>{g?.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"),G?.hide()};g&&g.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 w=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");w.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&w.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=a;let L=Tt({icon:"x",label:s});L.addEventListener("click",()=>{m(),t.onDismiss?.()});let A="rendered",S=ma({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:ee=>{A=ee==="source"?"source":"rendered",re()}}),C=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=n?.documentToolbarShowCopyLabel===!0,P=n?.documentToolbarShowCopyChevron===!0,R=n?.documentToolbarCopyMenuItems,F=!!(P&&R&&R.length>0),O=null,$,E=null,G=null;if(r&&(M||P)&&!F){if($=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let ee=ae("chevron-down",14,"currentColor",2);ee&&$.appendChild(ee)}}else r&&F?(O=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=M?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),E=Tt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),O.append($,E)):r?$=Tt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):($=Tt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&$.classList.add("persona-hidden"));let Q=r?Tt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Tt({icon:"refresh-cw",label:"Refresh"}),Z=r?Tt({icon:"x",label:s,className:"persona-artifact-doc-icon-btn"}):Tt({icon:"x",label:s}),J=Tt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&J.classList.add("persona-hidden");let fe=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ne=e.features?.artifacts?.toolbarActions??[],ge=()=>{let ee=Ae.find(D=>D.id===Me)??Ae[Ae.length-1],I=ee?.id??null,B=ee?.artifactType==="markdown"?ee.markdown??"":"",y=ee?JSON.stringify({component:ee.component,props:ee.props},null,2):"";return{markdown:B,jsonPayload:y,id:I}},ie=async()=>{let ee=Ae.find(I=>I.id===Me)??Ae[Ae.length-1];try{await navigator.clipboard.writeText(vs(ee))}catch{}};if($.addEventListener("click",async()=>{let ee=n?.onDocumentToolbarCopyMenuSelect;if(ee&&F){let{markdown:I,jsonPayload:B,id:y}=ge();try{await ee({actionId:"primary",artifactId:y,markdown:I,jsonPayload:B})}catch{}return}await ie()}),E&&R?.length){let ee=()=>b.closest("[data-persona-root]")??document.body,I=()=>{G=$o({items:R.map(B=>({id:B.id,label:B.label})),onSelect:async B=>{let{markdown:y,jsonPayload:D,id:H}=ge(),N=n?.onDocumentToolbarCopyMenuSelect;try{N?await N({actionId:B,artifactId:H,markdown:y,jsonPayload:D}):B==="markdown"||B==="md"?await navigator.clipboard.writeText(y):B==="json"||B==="source"?await navigator.clipboard.writeText(D):await navigator.clipboard.writeText(y||D)}catch{}},anchor:O??E,position:"bottom-right",portal:ee()})};b.isConnected?I():requestAnimationFrame(I),E.addEventListener("click",B=>{B.stopPropagation(),G?.toggle()})}Q.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}re()}),Z.addEventListener("click",()=>{m(),t.onDismiss?.()});let ue=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)w.replaceChildren(),O?C.append(O,Q,Z):C.append($,Q,Z),C.insertBefore(fe,Z),C.insertBefore(J,Z),w.append(S.element,ue,C);else{let ee=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ee.append($,fe,J,L),w.appendChild(T),w.appendChild(ee)}l&&(w.style.paddingLeft=l,w.style.paddingRight=l);let oe=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");p&&oe.style.setProperty("--persona-artifact-tab-fade-size",p);let me=e.features?.artifacts?.renderTabBar,Se=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Ce=Uy(oe,{onSelect:ee=>t.onSelect(Ae[ee].id)}),Be=ee=>{let I=ee.scrollWidth-ee.clientWidth,B=I>1,y=Math.abs(ee.scrollLeft);ee.classList.toggle("persona-artifact-tab-fade-start",c&&B&&y>1),ee.classList.toggle("persona-artifact-tab-fade-end",f&&B&&y<I-1)},ut=0,Je=()=>{if(ut)return;let ee=()=>{ut=0,Be(oe)};ut=typeof requestAnimationFrame=="function"?requestAnimationFrame(ee):setTimeout(ee,0)};oe.addEventListener("scroll",()=>Je(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Be(oe)).observe(oe);let Qe=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ne=()=>{Qe.scrollLeft=0},_e=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ne):setTimeout(Ne,0)};if(l){for(let ee of[oe,Se])ee.style.paddingLeft=l,ee.style.paddingRight=l;Qe.style.padding=l}b.appendChild(w),b.appendChild(oe),b.appendChild(Se),b.appendChild(Qe);let Ae=[],Me=null,qe=!1,Jt=!1,gt=!0,Bt=!1,Tn=null,En="",et=null,Le=!1,he=ee=>ee.artifactType==="markdown"&&!!ee.file||r?A:"rendered",tt=ee=>{r||(ee&&!Le?(w.insertBefore(S.element,T),Le=!0):!ee&&Le&&(S.element.remove(),Le=!1))},Te=()=>Me&&Ae.find(ee=>ee.id===Me)||Ae[Ae.length-1],be=()=>{let ee=bs(Te());if(!ee){fe.replaceChildren();return}let I=ne.filter(B=>B.visible===void 0||B.visible(ee)).map(B=>ga(B,{documentChrome:r,onClick:()=>{let y=bs(Te());if(y)try{Promise.resolve(B.onClick(y)).catch(()=>{})}catch{}}}));fe.replaceChildren(...I)},re=()=>{be();let ee=r&&Ae.length<=1,I=!!me;if(oe.classList.toggle("persona-hidden",ee||I),Se.classList.toggle("persona-hidden",ee||!I),I&&me){let D=Ae.map(H=>H.id).join("|")+" "+(Me??"");if(D!==En){En=D;let H=me({records:Ae,selectedId:Me,onSelect:t.onSelect});Se.firstElementChild!==H&&Se.replaceChildren(H)}}else{Ce.beforeRender(),oe.replaceChildren();let D=[],H=-1;for(let[N,K]of Ae.entries()){let V=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");V.type="button";let X=K.artifactType==="markdown"?K.file:void 0,ce=X?$n(X.path):K.title||K.id.slice(0,8),Ve=X?.path||K.title||ce;V.textContent=ce,V.title=Ve,V.setAttribute("aria-label",Ve),K.id===Me&&(V.classList.add("persona-bg-persona-container","persona-border-persona-border"),H=N),V.addEventListener("click",()=>t.onSelect(K.id)),oe.appendChild(V),D.push(V)}if(Ce.render(D,H),H>=0&&Me!==Tn){Tn=Me;let N=D[H];typeof N.scrollIntoView=="function"&&N.scrollIntoView({block:"nearest",inline:"nearest"})}Be(oe)}let B=Me&&Ae.find(D=>D.id===Me)||Ae[Ae.length-1];if(!B){Qe.replaceChildren(),et=null,tt(!1);return}let y=B.artifactType==="markdown"?B.file:void 0;if(tt(!!y&&Mr(y)!=="other"),r){let D=y?Vo(y):B.artifactType==="markdown"?"MD":B.component??"Component",H=(B.title||"Document").trim(),N=y?$n(y.path):H.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ue.textContent=`${N} \xB7 ${D}`}else T.textContent=y?$n(y.path):a;et?(et.el.parentElement!==Qe&&Qe.replaceChildren(et.el),et.update(B)):(et=gl(B,{config:e,resolveViewMode:he}),Qe.replaceChildren(et.el)),Qe.classList.toggle("persona-artifact-content-flush",!!Qe.querySelector(".persona-code-pre"))},xe=()=>{let ee=Ae.length>0;if(b.classList.toggle("persona-hidden",!ee),g){let y=((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;ee&&y&&qe?(g.classList.remove("persona-hidden"),b.classList.add("persona-artifact-drawer-open")):(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open"))}},kn=()=>{Bt=!1,re(),xe()};return{element:b,backdrop:g,update(ee){let I=ee.selectedId??ee.artifacts[ee.artifacts.length-1]?.id??null,B=I!==Me;Ae=ee.artifacts,Me=I,Ae.length>0&&(qe=!0),Bt=!0,gt&&kn(),B&&Ne()},setMobileOpen(ee){qe=ee,!ee&&g?(g.classList.add("persona-hidden"),b.classList.remove("persona-artifact-drawer-open")):xe()},setExpanded(ee){ee!==Jt&&(Jt=ee,_e());let I=ae(ee?"minimize":"maximize",16,"currentColor",2);I&&J.replaceChildren(I);let B=ee?"Collapse artifacts panel":"Expand artifacts panel";J.setAttribute("aria-label",B),J.title=B},setExpandToggleVisible(ee){J.classList.toggle("persona-hidden",!ee)},setCopyButtonVisible(ee){r||$.classList.toggle("persona-hidden",!ee)},setCustomActions(ee){ne=ee,be()},setTabFade(ee){let I=d(ee);I.start===c&&I.end===f||(c=I.start,f=I.end,Be(oe))},setRenderTabBar(ee){ee!==me&&(me=ee,En="",re())},setVisible(ee){ee!==gt&&(gt=ee,ee&&Bt&&kn())}}}function tn(e){return e?.features?.artifacts?.enabled===!0}function Vy(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"),!tn(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 $A(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 zy=["panel","seamless","detached"];function Zu(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&zy.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function ef(e){return!e||!tn(e)?!1:Zu(e)==="detached"}function Is(e,t){if(!tn(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"),$A(e),Vy(e,t);return}let n=t.features?.artifacts?.layout,o=Zu(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 a=n?.panePadding?.trim();a?e.style.setProperty("--persona-artifact-pane-padding",a):e.style.removeProperty("--persona-artifact-pane-padding");let s=n?.documentToolbarIconColor?.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):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"),Vy(e,t)}function Ws(e,t){for(let l of zy)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"),!tn(t))return;let n=t.features?.artifacts?.layout,o=Zu(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let a=n?.paneShadow?.trim();a&&e.style.setProperty("--persona-artifact-pane-shadow",a);let s=n?.chatShadow?.trim();s&&e.style.setProperty("--persona-artifact-chat-shadow",s)}function $y(e,t){return!t||!tn(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var jA=new Set(["__proto__","prototype","constructor"]),GA=new Set(["collapsed","card","panel","inline"]),jy=new Set(["markdown","component"]),KA=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Hr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Ul=e=>!jA.has(e),tf=e=>typeof e=="string"&&GA.has(e),Br=e=>Object.keys(e).length>0;function Gn(e,t,n,o){e.push({path:t,code:n,message:o})}var XA="Ignored because this key is not part of the persisted preference schema.",_l="Ignored an unsupported value.",JA="Expected collapsed, panel, or inline.",QA='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Gy={kind:"mode",message:_l},Aa={kind:"string",message:"Expected a CSS length string."},go={kind:"boolean"},YA={paneWidth:Aa,paneMaxWidth:Aa,paneMinWidth:Aa,expandedPanelWidth:Aa,resizableMinWidth:Aa,resizableMaxWidth:Aa,expandLauncherPanelWhenOpen:go,resizable:go},ZA={kind:"object",message:"Expected a preference object.",children:{showToolCalls:go,showReasoning:go,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:_l},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:_l},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:_l},expandable:go,grouped:go}},reasoningDisplay:{kind:"object",children:{expandable:go,activePreview:go}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Gy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Gy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:jy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:jy}}},filePreview:{kind:"object",children:{enabled:go}},layout:{kind:"object",children:YA}}}}};function Ky(e,t,n,o){if(e!==void 0)switch(t.kind){case"boolean":return typeof e=="boolean"?e:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof e=="string"?e:Gn(o,n,"invalid_type",t.message);case"enum":return typeof e=="string"&&t.values.has(e)?e:Gn(o,n,"invalid_value",t.message);case"mode":return tf(e)?sn(e):Gn(o,n,"invalid_value",t.message);case"modeMap":{if(!Hr(e))return Gn(o,n,"invalid_type","Expected an object.");let r=t.keys==="mediaType"?void 0:t.keys,a={};for(let[s,l]of Object.entries(e)){let p=r?s:Po(s);Ul(s)&&(r?r.has(s):KA.test(p))?tf(l)?a[p]=sn(l):Gn(o,`${n}.${s}`,"invalid_value",JA):Gn(o,`${n}.${s}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":QA)}return Br(a)?a:void 0}case"object":{if(t.bareMode&&tf(e))return sn(e);if(!Hr(e))return Gn(o,n,"invalid_type",t.message??"Expected an object.");let r=Object.keys(t.children),a=l=>n?`${n}.${l}`:l;for(let l of Object.keys(e))(!Ul(l)||!r.includes(l))&&Gn(o,a(l),"unknown_key",XA);let s={};for(let l of r){let p=t.children[l],d=Ky(e[l],p,a(l),o);if(p.deprecated&&e[l]!==void 0&&Gn(o,a(l),"deprecated_key",p.deprecated),d===void 0)continue;let c=p.alias??l,f=s[c];s[c]=Hr(f)&&Hr(d)?{...f,...d}:d}return Br(s)?s:void 0}}}function nf(e){let t=[];return{preferences:(e===null?void 0:Ky(e,ZA,"",t))??{},issues:t}}function Sa(e){if(Array.isArray(e))return e.map(Sa);if(!Hr(e))return e;let t={};for(let[n,o]of Object.entries(e))Ul(n)&&o!==void 0&&(t[n]=Sa(o));return t}function Xy(e,t){let n=Sa(e);for(let[o,r]of Object.entries(t)){if(!Ul(o)||r===void 0)continue;let a=n[o];n[o]=Hr(a)&&Hr(r)?Xy(a,r):Sa(r)}return n}function eS(e){let t={},n;for(let r of e){let a=nf(r).preferences;n=Jy(n,a.artifacts?.display),t=Xy(t,a)}let o=t;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function tS(e,t){if(t===void 0)return e===void 0?void 0:Sa(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},a={...o?{default:o}:{},...Br(r)?{byMediaType:r}:{}};return Br(a)?a:void 0}function Jy(e,t){if(t===void 0)return e===void 0?void 0:Sa(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},a=tS(n.files,t.files),s={...o?{default:o}:{},...Br(r)?{byKind:r}:{},...a!==void 0?{files:a}:{}};return Br(s)?s:void 0}function of(e={},t){let n=eS(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??{},a={...r};if(n.artifacts.display!==void 0){let s=Jy(r.display,n.artifacts.display);s!==void 0&&(a.display=s)}n.artifacts.filePreview&&(a.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(a.layout={...r.layout,...n.artifacts.layout}),o.artifacts=a}return o}function Hs(e){let t=e.preferences;return!t||!Br(t)?e:{...e,features:of(e.features??{},[t])}}function nS(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 oS(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 rS(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function aS(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function rf(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 a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function Qy(e,t,n,o,r,a){let s=nS(r,200),l=aS(t,n,o,200);l=Math.max(s,l);let p=oS(a);return p!==null&&(l=Math.min(l,p)),rS(e,s,l)}var Yy={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"}},af=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(a=>{if(a.dataset.enhanced==="true")return;let s=a.dataset.tvForm??"init";a.dataset.enhanced="true";let l=Yy[s]??Yy.init;a.classList.add("persona-form-card","persona-space-y-4");let p=v("div","persona-space-y-1"),d=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=l.title,p.appendChild(d),l.description){let b=v("p","persona-text-sm persona-text-persona-muted");b.textContent=l.description,p.appendChild(b)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",l.fields.forEach(b=>{let w=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");w.htmlFor=`${t.id}-${s}-${b.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=b.label,w.appendChild(T);let L=b.type??"text",A;L==="textarea"?(A=document.createElement("textarea"),A.rows=3):(A=document.createElement("input"),A.type=L),A.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",A.id=`${t.id}-${s}-${b.name}`,A.name=b.name,A.placeholder=b.placeholder??"",b.required&&(A.required=!0),w.appendChild(A),c.appendChild(w)});let f=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=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",f.appendChild(g),f.appendChild(m),c.appendChild(f),a.replaceChildren(p,c),c.addEventListener("submit",async b=>{b.preventDefault();let w=n.formEndpoint??"/form",T=new FormData(c),L={};T.forEach((A,S)=>{L[S]=A}),L.type=s,m.disabled=!0,g.textContent="Submitting\u2026";try{let A=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!A.ok)throw new Error(`Form submission failed (${A.status})`);let S=await A.json();g.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(A){g.textContent=A instanceof Error?A.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var sf=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(a=>a.id));return[...n.filter(a=>!o.has(a.id)),...t].sort((a,s)=>(s.priority??0)-(a.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},Bs=new sf;var Zy=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),sS=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),eb=(e,t,n)=>{if(!Zy(e)||!Zy(t)||sS.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let a=n?`${n}.${r}`:r;o[r]=eb(e[r],t[r],a)}return o};function ql(e,t){let n=eb(e,t,"");return da(n)}var tb=()=>{let e=new Map,t=(r,a)=>(e.has(r)||e.set(r,new Set),e.get(r).add(a),()=>n(r,a)),n=(r,a)=>{e.get(r)?.delete(a)};return{on:t,off:n,emit:(r,a)=>{e.get(r)?.forEach(s=>{try{s(a)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var iS=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},lS=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 a=t[r];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},Ds=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=iS(e),n=lS(t);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...a}=o;return{type:String(r),payload:a,raw:o}}catch{return null}},lf=e=>typeof e=="string"?e:e==null?"":String(e),Dr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:lf(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=lf(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:lf(n.text)}}},nb=e=>Array.isArray(e)?e.map(t=>String(t)):[],Fs=e=>{let t=new Set(nb(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(nb(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.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=s?e.parsers.reduce((d,c)=>d||c?.({text:s,message:a.message})||null,null):null;if(!l)return null;t.add(a.message.id),o();let p={action:l,message:a.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},f=d(l,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:g,resubmit:f.resubmit}}}catch(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var cS=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}},dS=e=>e.map(t=>({...t,streaming:!1})),pS=e=>e.map(t=>({...t,status:"complete"})),Vl=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?cS(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?dS(n.messages):void 0,artifacts:n.artifacts?pS(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 Ma=ko(wi(),1);function uS(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function fS(e,t){if(!uS(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 zl(){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,Ma.parse)(n,Ma.STR|Ma.OBJ),a=fS(r,n);a&&(e=a)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function ob(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function $l(e,t){let{config:n,message:o,onPropsUpdate:r}=t,a=Nn.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return a(e.props,s)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,l),null}}function rb(){let e=zl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ab(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 Os(e){let t=ab(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 jl(e){let t=ab(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 mS=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gl(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:d=mS}=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 f=null,g=document.createElement("div");g.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 w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,m.appendChild(w),g.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 L=[];for(let P=1;P<=5;P++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${d[P-1]}`),R.title=d[P-1],R.dataset.rating=String(P),R.innerHTML=`
46
46
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
47
47
  <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>
48
48
  </svg>
49
- `,w.addEventListener("click",()=>{u=W,k.forEach((D,F)=>{let j=F<W;D.classList.toggle("selected",j),D.setAttribute("aria-checked",F===W-1?"true":"false")})}),k.push(w),E.appendChild(w)}g.appendChild(E);let M=null;if(p){let W=document.createElement("div");W.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=a,M.rows=3,M.setAttribute("aria-label","Additional comments"),W.appendChild(M),g.appendChild(W)}let S=document.createElement("div");S.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=l,C.addEventListener("click",()=>{n?.(),d.remove()});let T=document.createElement("button");return T.type="button",T.className="persona-feedback-btn persona-feedback-btn-submit",T.textContent=s,T.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}T.disabled=!0,T.textContent="Submitting...";try{let W=M?.value.trim()||void 0;await t(u,W),d.remove()}catch(W){T.disabled=!1,T.textContent=s,console.error("[CSAT Feedback] Failed to submit:",W)}}),S.appendChild(C),S.appendChild(T),g.appendChild(S),d.appendChild(g),d}function bl(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:a="What could we do better? (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let h=document.createElement("div");h.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=o,h.appendChild(A);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=r,h.appendChild(E),f.appendChild(h);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 M=document.createElement("div");M.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=c;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=d,M.appendChild(S),M.appendChild(C);let T=document.createElement("div");T.className="persona-feedback-numbers";let W=[];for(let O=0;O<=10;O++){let q=document.createElement("button");q.type="button",q.className="persona-feedback-rating-btn persona-feedback-number-btn",q.setAttribute("role","radio"),q.setAttribute("aria-checked","false"),q.setAttribute("aria-label",`Rating ${O} out of 10`),q.textContent=String(O),q.dataset.rating=String(O),O<=6?q.classList.add("persona-feedback-detractor"):O<=8?q.classList.add("persona-feedback-passive"):q.classList.add("persona-feedback-promoter"),q.addEventListener("click",()=>{g=O,W.forEach((Q,de)=>{Q.classList.toggle("selected",de===O),Q.setAttribute("aria-checked",de===O?"true":"false")})}),W.push(q),T.appendChild(q)}k.appendChild(M),k.appendChild(T),f.appendChild(k);let w=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=a,w.rows=3,w.setAttribute("aria-label","Additional comments"),O.appendChild(w),f.appendChild(O)}let D=document.createElement("div");D.className="persona-feedback-actions";let F=document.createElement("button");F.type="button",F.className="persona-feedback-btn persona-feedback-btn-skip",F.textContent=l,F.addEventListener("click",()=>{n?.(),u.remove()});let j=document.createElement("button");return j.type="button",j.className="persona-feedback-btn persona-feedback-btn-submit",j.textContent=s,j.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}j.disabled=!0,j.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(g,O),u.remove()}catch(O){j.disabled=!1,j.textContent=s,console.error("[NPS Feedback] Failed to submit:",O)}}),D.appendChild(F),D.appendChild(j),f.appendChild(D),u.appendChild(f),u}var ea="persona-chat-history",lw=30*1e3,dw=641,cw={"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 pw(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 a=cw[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{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 xl(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 uw(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 fw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var pu=e=>!e||typeof e!="object"?{}:{...e},Ph=e=>e.map(t=>({...t,streaming:!1})),Rh=(e,t,n)=>{let o=e?.markdown?Qo(e.markdown):null,r=Lr(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."),a=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let d=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});d!==null&&(s=d.text,d.persist||(a.message.__skipPersist=!0),d.resubmit&&!a.streaming&&n&&n())}let p=Gn()!==null,c;if(e?.postprocessMessage){let d=e.postprocessMessage({...a,text:s,raw:l??a.text??""});c=r?r(d):d}else if(o){let d=a.streaming?Jf(s):s,u=o(d);c=r&&p?r(u):u}else c=Hn(s);return c}};function Ih(e){let t=b("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)",a=e?.iconStrokeWidth??.5,s=oe(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=b("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var mw=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},gw=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:mw(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),vl=(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=Or(t),r=o.features;o=is(o);let a=ls.getForInstance(o.plugins),{plugin:s,teardown:l}=ah();o.components&&Ln.registerAll(o.components);let p=Mh(),d=o.persistState===!1?null:o.storageAdapter??fl(),u={},g=null,f=!1,h=i=>{if(o.onStateLoaded)try{let m=o.onStateLoaded(i);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:v}=m;return v&&(f=!0),y}return m}catch(m){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return i};if(d?.load)try{let i=d.load();if(i&&typeof i.then=="function")g=i.then(m=>h(m??{messages:[],metadata:{}}));else{let y=h(i??{messages:[],metadata:{}});y.metadata&&(u=pu(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=h({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let A=()=>u,E=i=>{u=i({...u})??{},Ol()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],M=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick],S=cs({parsers:k,handlers:M,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null});S.syncFromMetadata();let C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,W=o.autoFocusInput??!1,w=T,D=C,F=o.layout?.header?.layout,j=!1,O=()=>Bo(o),q=()=>C||O(),Q=O()?!1:C?T:!0,de=!1,be=null,De=()=>{de=!0,be&&clearTimeout(be),be=setTimeout(()=>{de&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),de=!1)},1e4)},ie=Rh(o,S,De),ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,le=o.features?.showEventStreamToggle??!1,Z=o.features?.scrollToBottom??{},me=o.features?.scrollBehavior??{},we=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Se=le?new os(we):null,mt=o.features?.eventStream?.maxEvents??2e3,We=le?new ns(mt,Se):null,_e=le?new rs:null,Xe=null,$e=!1,Me=null,ke=0;Se?.open().then(()=>We?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let Je={onCopy:i=>{p.emit("message:copy",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.id,"copy").catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",m)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{p.emit("message:feedback",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.messageId,i.type).catch(m=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",m)}),o.messageActions?.onFeedback?.(i)}},Dt=o.statusIndicator??{},Wt=i=>i==="idle"?Dt.idleText??It.idle:i==="connecting"?Dt.connectingText??It.connecting:i==="connected"?Dt.connectedText??It.connected:i==="error"?Dt.errorText??It.error:i==="paused"?Dt.pausedText??It.paused:i==="resuming"?Dt.resumingText??It.resuming:It[i];function Kt(i,m,y,v){if(v==="idle"&&y.idleLink){i.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=m,L.style.color="inherit",L.style.textDecoration="none",i.appendChild(L)}else i.textContent=m}let wt=zg({config:o,showClose:q()}),{wrapper:He,panel:ce,pillRoot:et}=wt.shell,Pe=wt.panelElements,{container:ue,body:ae,messagesWrapper:Le,suggestions:it,textarea:pe,sendButton:ve,sendButtonWrapper:ee,composerForm:P,statusText:U,introTitle:x,introSubtitle:H,closeButton:R,iconHolder:B,headerTitle:K,headerSubtitle:_,header:$,footer:Y,actionsRow:je,rightActions:Re}=Pe,Qe=Pe.leftActions,rt=Pe.setSendButtonMode,G=Pe.micButton,Ue=Pe.micButtonWrapper,he=Pe.attachmentButton,qe=Pe.attachmentButtonWrapper,Fe=Pe.attachmentInput,Ht=Pe.attachmentPreviewsContainer;ue.classList.add("persona-relative"),ae.classList.add("persona-relative");let Sl=12,Do=()=>Z.label??"",ms=()=>Z.iconName??"arrow-down",gs=()=>Z.enabled!==!1,fn=()=>me.mode??"anchor-top",no=()=>fn()==="follow"||fn()==="anchor-top"&&pa,Eu=()=>me.anchorTopOffset??16,yy=()=>me.restorePosition??"bottom",ku=()=>me.pauseOnInteraction===!0,Lu=()=>me.showActivityWhilePinned!==!1,Pu=()=>me.announce===!0,kt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let na=b("span","persona-flex persona-items-center"),Ml=b("span",""),Fo=b("span","");Fo.setAttribute("data-persona-scroll-to-bottom-count",""),Fo.style.display="none",kt.append(na,Ml,Fo),ue.appendChild(kt);let oo=b("div","persona-stream-anchor-spacer");oo.setAttribute("aria-hidden","true"),oo.setAttribute("data-persona-anchor-spacer",""),oo.style.flexShrink="0",oo.style.pointerEvents="none",oo.style.height="0px",ae.appendChild(oo);let Oo=b("div","persona-sr-only");Oo.setAttribute("aria-live","polite"),Oo.setAttribute("aria-atomic","true"),Oo.setAttribute("role","status"),Oo.setAttribute("data-persona-live-region",""),Object.assign(Oo.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"}),ue.appendChild(Oo);let oa=null,hs=null,Ru=i=>{!Pu()||!i||(hs=i,oa===null&&(oa=setTimeout(()=>{oa=null,hs&&Pu()&&(Oo.textContent=hs),hs=null},400)))},gr=()=>{let m=Y.style.display==="none"?0:Y.offsetHeight;kt.style.bottom=`${m+Sl}px`};gr();let Iu=()=>{let i=!!Do();kt.setAttribute("aria-label",Do()||"Jump to latest"),kt.title=Do(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),na.innerHTML="";let m=oe(ms(),"14px","currentColor",2);m?(na.appendChild(m),na.style.display=""):na.style.display="none",Ml.textContent=Do(),Ml.style.display=i?"":"none"};Iu();let At=null,an=null,Wu=null,Hu=a.find(i=>i.renderHeader);if(Hu?.renderHeader){let i=Hu.renderHeader({config:o,defaultRenderer:()=>{let m=eo({config:o,showClose:q()});return ir(ue,m,o),m.header},onClose:()=>ct(!1,"user")});if(i){let m=ue.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(i),$=i,wt.header.element=i)}}let Tl=()=>{if(!We)return;if($e=!0,!Xe&&We&&(Xe=ch({buffer:We,getFullHistory:()=>We.getAllFromStore(),onClose:()=>ra(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Xe&&(ae.style.display="none",Y.parentNode?.insertBefore(Xe.element,Y),Xe.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Yt.actionIconColor}`;let m=o.features?.eventStream?.classNames?.toggleButtonActive;m&&m.split(/\s+/).forEach(y=>y&&tt.classList.add(y))}let i=()=>{if(!$e)return;let m=Date.now();m-ke>=200&&(Xe?.update(),ke=m),Me=requestAnimationFrame(i)};ke=0,Me=requestAnimationFrame(i),ln(),p.emit("eventStream:opened",{timestamp:Date.now()})},ra=()=>{if($e){if($e=!1,Xe&&Xe.element.remove(),ae.style.display="",tt){tt.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(m=>m&&tt.classList.remove(m))}Me!==null&&(cancelAnimationFrame(Me),Me=null),ln(),p.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(le){let i=o.features?.eventStream?.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(i?.toggleButton?" "+i.toggleButton:"");tt=b("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=oe("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let v=Pe.clearChatButtonWrapper,L=Pe.closeButtonWrapper,I=v||L;I&&I.parentNode===$?$.insertBefore(tt,I):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}let by=i=>{let m=o.attachments;if(!m?.enabled)return;let y=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!y){y=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let L=i.querySelector("[data-persona-composer-form]");L?.parentNode?L.parentNode.insertBefore(y,L):i.insertBefore(y,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let L=b("input");L.type="file",L.setAttribute("data-persona-composer-attachment-input",""),L.accept=(m.allowedTypes??Yn).join(","),L.multiple=(m.maxFiles??4)>1,L.style.display="none",L.setAttribute("aria-label",m.buttonTooltipText??"Attach files"),i.appendChild(L)}},Bu=a.find(i=>i.renderComposer);if(Bu?.renderComposer){let i=o.composer,m=Bu.renderComposer({config:o,defaultRenderer:()=>jr({config:o}).footer,onSubmit:y=>{if(!z||z.isStreaming())return;let v=y.trim(),L=At?.hasAttachments()??!1;if(!v&&!L)return;uf();let I;L&&(I=[],I.push(...At.getContentParts()),v&&I.push(Mo(v))),z.sendMessage(v,{contentParts:I}),L&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Fe?.click()},models:i?.models,selectedModelId:i?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Wu?.()}:void 0});m&&(wt.replaceComposer(m),Y=wt.composer.footer)}let xy=i=>{let m=(...fe)=>{for(let re of fe){let xe=i.querySelector(re);if(xe)return xe}return null},y=i.querySelector("[data-persona-composer-form]"),v=i.querySelector("[data-persona-composer-input]"),L=i.querySelector("[data-persona-composer-submit]"),I=i.querySelector("[data-persona-composer-mic]"),J=i.querySelector("[data-persona-composer-status]");y&&(P=y),v&&(pe=v),L&&(ve=L),I&&(G=I,Ue=I.parentElement),J&&(U=J);let V=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");V&&(it=V);let X=m("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(he=X,qe=X.parentElement),Fe=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ht=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let se=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");se&&(je=se),Qe=m(".persona-widget-composer__left-actions")};by(Y),xy(Y);let ro=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(ro&&(Le.style.maxWidth=ro,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%"),ro&&P&&!O()&&(P.style.maxWidth=ro,P.style.marginLeft="auto",P.style.marginRight="auto"),ro&&it&&!O()&&(it.style.maxWidth=ro,it.style.marginLeft="auto",it.style.marginRight="auto"),ro&&Ht&&!O()&&(Ht.style.maxWidth=ro,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),o.attachments?.enabled&&Fe&&Ht){At=or.fromConfig(o.attachments),At.setPreviewsContainer(Ht),Fe.addEventListener("change",y=>{let v=y.target;At?.handleFileSelect(v.files),v.value=""});let i=o.attachments.dropOverlay,m=Ih(i);ue.appendChild(m)}let vy=()=>an?.prefetch();if(o.contextMentions?.enabled&&pe&&(an=tg({config:o,textarea:pe,anchor:P??pe,getMessages:()=>z.getMessages(),liveRegionHost:ue}),an)){let i=pe;i.parentElement?.insertBefore(an.contextRow,i);let m=an.affordanceButtons;for(let y=m.length-1;y>=0;y--){let v=m[y];Qe?Qe.insertBefore(v,Qe.firstChild):P?.appendChild(v)}}(()=>{let i=o.layout?.slots??{},m=v=>{switch(v){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Le;case"footer-top":return it;case"composer":return P;case"footer-bottom":return U;default:return null}},y=(v,L)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")$.insertBefore(L,$.firstChild);else if(v==="header-right")$.appendChild(L);else{let I=$.querySelector(".persona-flex-col");I?I.parentNode?.insertBefore(L,I.nextSibling):$.appendChild(L)}break;case"body-top":{let I=ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");I?I.replaceWith(L):ae.insertBefore(L,ae.firstChild);break}case"body-bottom":ae.appendChild(L);break;case"footer-top":it.replaceWith(L);break;case"footer-bottom":U.replaceWith(L);break;default:break}};for(let[v,L]of Object.entries(i))if(L)try{let I=L({config:o,defaultContent:()=>m(v)});I&&y(v,I)}catch(I){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,I)}})();let Du=i=>{let y=i.target.closest('button[data-expand-header="true"]');if(!y)return;let v=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");if(I==="reasoning")Kr.has(L)?Kr.delete(L):Kr.add(L),Jg(L,v);else if(I==="tool")Xr.has(L)?Xr.delete(L):Xr.add(L),Qg(L,v,o);else if(I==="approval"){let V=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=dr.get(L)??V;dr.set(L,!X),th(L,v,o)}qo.delete(L)};Le.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("keydown",i=>{let m=i.target;(i.key==="Enter"||i.key===" ")&&m.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Du(i))}),Le.addEventListener("copy",i=>{let{clipboardData:m}=i;if(!m)return;let y=Le.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let L=v.toString(),I=Tg(L);!I||I===L||(m.setData("text/plain",I),i.preventDefault())});let El=new Map,Fu=null,Ou="idle",Cy={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},wy=(i,m)=>{let{icon:y,label:v}=Cy[m];i.setAttribute("aria-label",v),i.title=v,i.setAttribute("aria-pressed",m==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",m!=="idle"),i.classList.toggle("persona-message-action-loading",m==="loading");let L=oe(y,14,"currentColor",2);L&&(i.innerHTML="",i.appendChild(L))},Nu=()=>{Le.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{let v=m.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;wy(m,v&&v===Fu?Ou:"idle")})};Le.addEventListener("click",i=>{let y=i.target.closest(".persona-message-action-btn[data-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest("[data-actions-for]");if(!v)return;let L=v.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let V=z.getMessages().find(X=>X.id===L);if(V&&Je.onCopy){let X=V.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let se=oe("check",14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let fe=oe("copy",14,"currentColor",2);fe&&(y.innerHTML="",y.appendChild(fe))},2e3)}).catch(se=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",se)}),Je.onCopy(V)}}else if(I==="read-aloud")z.toggleReadAloud(L);else if(I==="upvote"||I==="downvote"){let V=(El.get(L)??null)===I,X=I==="upvote"?"thumbs-up":"thumbs-down";if(V){El.delete(L),y.classList.remove("persona-message-action-active");let se=oe(X,14,"currentColor",2);se&&(y.innerHTML="",y.appendChild(se))}else{let se=I==="upvote"?"downvote":"upvote",fe=v.querySelector(`[data-action="${se}"]`);if(fe){fe.classList.remove("persona-message-action-active");let nt=oe(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(fe.innerHTML="",fe.appendChild(nt))}El.set(L,I),y.classList.add("persona-message-action-active");let re=oe(X,14,"currentColor",2);re&&(re.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(re)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let ze=z.getMessages().find(pt=>pt.id===L);ze&&Je.onFeedback&&Je.onFeedback({type:I,messageId:ze.id,message:ze})}}}),Le.addEventListener("click",i=>{let y=i.target.closest("button[data-approval-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.closest(".persona-approval-bubble");if(!v)return;let L=v.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let J=I==="approve"?"approved":"denied",X=z.getMessages().find(fe=>fe.id===L);if(!X?.approval)return;let se=v.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(re=>{re.disabled=!0,re.style.opacity="0.5",re.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?z.resolveWebMcpApproval(L,J):z.resolveApproval(X.approval,J)});let Ye=null,aa=null,sa=()=>{},ia="none",ys=null,vn={artifacts:[],selectedId:null},_n=!1,Cn=!1,la=!1,hr=!1,_u=()=>hr||vn.artifacts.some(i=>Bn(o.features?.artifacts,i)==="panel"),bs=()=>vn.artifacts.length>0&&!_n&&_u(),lt={current:null},kl=(i,m)=>{let y=z.getArtifactById(m),v=y?.markdown,L=y?.title||"artifact",I=y?.file,J=y?.artifactType??"markdown";if(!v){let se=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(se){let re=z.getMessages().find(xe=>xe.id===se);if(re?.rawContent)try{let xe=JSON.parse(re.rawContent);v=xe?.props?.markdown,L=xe?.props?.title||L,xe?.props?.file&&typeof xe.props.file=="object"&&(I=xe.props.file),!y&&typeof xe?.props?.artifactType=="string"&&(J=xe.props.artifactType)}catch{}}}return{markdown:v,title:L,file:I,artifactType:J}};Le.addEventListener("click",i=>{let y=i.target.closest("[data-download-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:I,title:J,file:V}=kl(y,v);if(!I)return;let{filename:X,mime:se,content:fe}=lg({title:J,markdown:I,file:V}),re=new Blob([fe],{type:se}),xe=URL.createObjectURL(re),ze=document.createElement("a");ze.href=xe,ze.download=X,ze.click(),URL.revokeObjectURL(xe)}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-artifact-custom-action]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-artifact-custom-action");if(!v)return;let L=y.closest("[data-artifact-inline]"),I=L?null:y.closest("[data-open-artifact]"),J=L?L.getAttribute("data-artifact-inline"):I?.getAttribute("data-open-artifact")??null,X=(L?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(pt=>pt.id===v);if(!X)return;let{markdown:se,title:fe,file:re,artifactType:xe}=kl(y,J??""),ze={artifactId:J,title:fe,artifactType:xe,markdown:se,file:re};try{Promise.resolve(X.onClick(ze)).catch(()=>{})}catch{}}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-copy-artifact]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-copy-artifact");if(!v)return;let L=z.getArtifactById(v),I="";if(L)I=Xa(L);else{let{markdown:J,file:V,artifactType:X}=kl(y,v);X==="markdown"&&(I=Xa({id:v,artifactType:"markdown",status:"complete",markdown:J??"",...V?{file:V}:{}}))}I&&navigator.clipboard.writeText(I).then(()=>{let J=oe("check",16,"currentColor",2);J&&(y.replaceChildren(J),setTimeout(()=>{let V=oe("copy",16,"currentColor",2);V&&y.replaceChildren(V)},1500))}).catch(()=>{})}),Le.addEventListener("click",i=>{let y=i.target.closest("[data-expand-artifact-inline]");if(!y)return;i.preventDefault(),i.stopPropagation();let v=y.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(_n=!1,hr=!0,Cn=!0,la=!0,z.selectArtifact(v),Un())}),Le.addEventListener("click",i=>{let m=i.target;if(m.closest("[data-download-artifact]")||m.closest("[data-artifact-custom-action]"))return;let y=m.closest("[data-open-artifact]");if(!y)return;let v=y.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(i.preventDefault(),i.stopPropagation(),_n=!1,hr=!0,z.selectArtifact(v),Un())}),Le.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let m=i.target;!m.hasAttribute("data-open-artifact")&&!m.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),m.click())});let yr=Pe.composerOverlay,br=(i,m,y)=>{let v=m.trim();if(!v||!lt.current)return;let L=i.getAttribute("data-tool-call-id")??"",I=y.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:L,answer:v,answers:y.structured,values:y.values??(y.source==="multi"?v.split(", "):[v]),isFreeText:I,source:y.source},bubbles:!0,composed:!0})),Co(yr,L);let J=lt.current.getMessages().find(V=>V.toolCall?.id===L);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,y.structured??v):lt.current.sendMessage(v)},No=i=>{let m=lt.current;if(!m)return;let y=i.getAttribute("data-tool-call-id")??"",v=m.getMessages().find(L=>L.toolCall?.id===y);v&&m.persistAskUserQuestionProgress(v,{answers:ei(i,v),currentIndex:xn(i)})},Uu=i=>Object.entries(i).map(([m,y])=>`${m}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Ll=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let m=xn(i),y=Ir(i);if(m>=y-1)return;let v=lt.current?.getMessages().find(L=>L.toolCall?.id===i.getAttribute("data-tool-call-id"));v&&(ti(i,v,o,m+1),No(i))};yr.addEventListener("click",i=>{let y=i.target.closest("[data-ask-user-action]");if(!y)return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;let L=y.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),L==="dismiss"){let I=v.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I);let J=lt.current?.getMessages().find(V=>V.toolCall?.id===I);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(L==="pick"){let I=y.getAttribute("data-option-label");if(!I)return;let J=v.getAttribute("data-multi-select")==="true",V=vo(v);if(V&&J){let X=Yo(v)[xn(v)],se=new Set(Array.isArray(X)?X:[]);se.has(I)?se.delete(I):se.add(I),wo(v,Array.from(se)),No(v);return}if(V){wo(v,I),No(v),Ll(v);return}if(J){let X=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",X?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!X);let se=v.querySelector('[data-ask-user-action="submit-multi"]');se&&(se.disabled=ud(v).length===0);return}br(v,I,{source:"pick",values:[I]});return}if(L==="submit-multi"){let I=ud(v);if(I.length===0)return;br(v,I.join(", "),{source:"multi",values:I});return}if(L==="open-free-text"){let I=v.querySelector('[data-ask-free-text-row="true"]');I&&(I.classList.remove("persona-hidden"),I.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(L==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(L==="submit-free-text"){let J=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(vo(v)){wo(v,J.trim()),No(v),Ll(v);return}br(v,J,{source:"free-text"});return}if(L==="next"||L==="back"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let re=Yo(v)[xn(v)];(typeof re!="string"||re!==X)&&wo(v,X)}let se=L==="next"?1:-1,fe=xn(v)+se;ti(v,J,o,fe),No(v);return}if(L==="submit-all"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(re=>re.toolCall?.id===I);if(!J)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&wo(v,X);let se=ei(v,J);lt.current.persistAskUserQuestionProgress(J,{answers:se,currentIndex:xn(v)});let fe=Uu(se);br(v,fe||"(submitted)",{source:"submit-all",structured:se});return}if(L==="skip"){if(!lt.current)return;let I=v.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(xe=>xe.toolCall?.id===I);if(!J)return;let V=vo(v),X=xn(v),se=Ir(v),fe=X>=se-1;if(!V){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:I},bubbles:!0,composed:!0})),Co(yr,I),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}wo(v,"");let re=v.querySelector('[data-ask-free-text-input="true"]');if(re&&(re.value=""),fe){let xe=ei(v,J),ze=Uu(xe);br(v,ze||"(skipped)",{source:"submit-all",structured:xe});return}ti(v,J,o,X+1),No(v);return}}),yr.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let y=i.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;i.preventDefault();let L=y.value;if(L.trim()){if(vo(v)){wo(v,L.trim()),No(v),Ll(v);return}br(v,L,{source:"free-text"})}});let qu=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let m=i.target;if(m?.tagName==="INPUT"||m?.tagName==="TEXTAREA"||m?.isContentEditable)return;let y=yr.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let v=Number(i.key),I=y.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];I&&(i.preventDefault(),I.click())};document.addEventListener("keydown",qu);let ao=null,bt=null,da=null,xs=null,Pl=()=>{},Vu=!1,vs="",Cs="";function Rl(){xs?.(),xs=null}let zu=()=>{if(!ao||!bt)return;let i=e.classList.contains("persona-artifact-welded-split"),m=e.ownerDocument.defaultView??window,y=m.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||y){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let v=ao.firstElementChild;if(!v||v===bt)return;let L=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${L}px`,bt.style.zIndex="5";let I=iu(ao,m),J=v.offsetWidth+I/2-L/2;bt.style.left=`${Math.max(0,J)}px`},ws=()=>{},Ay=()=>{let i=e.ownerDocument.defaultView??window,m=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!m||i.innerWidth>y?!1:C||Et(o)},As=()=>!Zt(o)||!bs()||e.classList.contains("persona-artifact-narrow-host")||Ay()||(e.ownerDocument.defaultView??window).innerWidth<dw?"none":ou(o)?"detached":"welded",Un=()=>{if(!Ye||!Zt(o))return;as(e,o),ss(e,o),ws();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,m=ce.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=i);let y=bs();Ye.setVisible(y),Ye.update(vn),_n?(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!1):vn.artifacts.length>0&&_u()?(Ye.element.classList.remove("persona-hidden"),Ye.setMobileOpen(!0)):(Ye.setMobileOpen(!1),Ye.element.classList.add("persona-hidden"),Ye.backdrop?.classList.add("persona-hidden"),Cn=!1,la=!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&&!la&&(Cn=!1),Cn!==Vu){let I=Ye.element;Cn?(vs=I.style.width,Cs=I.style.maxWidth,I.style.removeProperty("width"),I.style.removeProperty("max-width")):(vs&&(I.style.width=vs),Cs&&(I.style.maxWidth=Cs),vs="",Cs=""),Vu=Cn}e.classList.toggle("persona-artifact-expanded",Cn),Ye.setExpanded(Cn);let L=As();L!==ia&&(ia=L,sa()),Pl()};if(Zt(o)){ce.style.position="relative";let i=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(ue),Ye=uh(o,{onSelect:y=>lt.current?.selectArtifact(y),onDismiss:()=>{_n=!0,Un()},onToggleExpand:()=>{let y=!Cn,v=vn.selectedId??vn.artifacts[vn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(Cn=y,y||(la=!1),Un())}}),Ye.element.classList.add("persona-hidden"),ao=m,m.appendChild(i),m.appendChild(Ye.element),Ye.backdrop&&ce.appendChild(Ye.backdrop),ce.appendChild(m),Pl=()=>{if(!ao||!Ye)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye.element.style.removeProperty("width"),Ye.element.style.removeProperty("maxWidth");return}if(!bt){let v=b("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 L=e.ownerDocument,I=L.defaultView??window,J=V=>{if(!Ye||V.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||I.innerWidth<=640)return;V.preventDefault(),Rl();let X=V.clientX,se=Ye.element.getBoundingClientRect().width,fe=o.features?.artifacts?.layout,re=ze=>{let pt=ao.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),dn=iu(ao,I),St=nt?0:v.getBoundingClientRect().width||6,Pt=se-(ze.clientX-X),N=Ch(Pt,pt,dn,St,fe?.resizableMinWidth,fe?.resizableMaxWidth);Ye.element.style.width=`${N}px`,Ye.element.style.maxWidth="none",zu()},xe=()=>{L.removeEventListener("pointermove",re),L.removeEventListener("pointerup",xe),L.removeEventListener("pointercancel",xe),xs=null;try{v.releasePointerCapture(V.pointerId)}catch{}};xs=xe,L.addEventListener("pointermove",re),L.addEventListener("pointerup",xe),L.addEventListener("pointercancel",xe);try{v.setPointerCapture(V.pointerId)}catch{}};v.addEventListener("pointerdown",J),bt=v,ao.insertBefore(v,Ye.element),da=()=>{v.removeEventListener("pointerdown",J)}}if(bt){let v=bs();bt.classList.toggle("persona-hidden",!v),zu()}},ws=()=>{if(!C||!Ye||(o.launcher?.sidebarMode??!1)||Et(o)&&rn(o).reveal==="emerge")return;let v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640;if(L&&v.innerWidth<=I||!gh(o,C))return;let J=o.launcher?.width??o.launcherWidth??pn,V=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";bs()?(ce.style.width=V,ce.style.maxWidth=V):(ce.style.width=J,ce.style.maxWidth=J)},typeof ResizeObserver<"u"&&(aa=new ResizeObserver(()=>{Un()}),aa.observe(ce))}else ce.appendChild(ue);O()&&et&&(Pe.peekBanner&&et.appendChild(Pe.peekBanner),et.appendChild(Y)),e.appendChild(He),et&&e.appendChild(et);let Ss=()=>{if(O()){ce.style.width="100%",ce.style.maxWidth="100%";let Tt=o.launcher?.composerBar??{},nn=He.dataset.state==="expanded",qs=Tt.expandedSize??"anchored";if(!(nn&&qs!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Ma=o.theme?.components?.panel,Vs=ko(o),Tr=($n,Jo)=>$n==null||$n===""?Jo:Qt(Vs,$n)??$n,zs="1px solid var(--persona-border)",Zl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Xo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=Tr(Ma?.border,zs),ue.style.borderRadius=Tr(Ma?.borderRadius,Xo),ue.style.boxShadow=Tr(Ma?.shadow,Zl),ue.style.overflow="hidden";return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,L=o.launcher?.detachedPanel===!0,I=o.theme?.components?.panel,J=ko(o),V=(Tt,nn)=>Tt==null||Tt===""?nn:Qt(J,Tt)??Tt,X=e.ownerDocument.defaultView??window,se=o.launcher?.mobileFullscreen??!0,fe=o.launcher?.mobileBreakpoint??640,re=X.innerWidth<=fe,xe=se&&re&&C,ze=i&&se&&re,pt=o.launcher?.position??"bottom-left",nt=pt==="bottom-left"||pt==="top-left",dn=o.launcher?.zIndex??Gt,St="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))",Te=L&&!xe&&!ze;Te?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Oe=Te?St:m||xe?"none":St,Ce=Te?Pt:xe?"none":m?nt?"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":Pt;i&&!xe&&!Te&&(Ce="none",Oe="none");let Ct=Te?N:m||xe?"0":N,ut=V(I?.border,Oe),Ft=V(I?.shadow,Ce),ft=V(I?.borderRadius,Ct),tn=As(),Rt=tn==="detached",Ee=tn==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Ee);let Ne="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)))))",vt=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Zt(o)&&ou(o)&&v&&!i;e.classList.toggle("persona-artifact-chat-flush",vt);let dt=Rt||vt?"none":Ft,gt=Rt?St:Ee?"none":ut,Ze=Rt?N:ft;vt&&(gt="none",Ze="0");let Ie=I?.borderRadius!=null&&I.borderRadius!=="",yt=vt&&!Ie?"0":ft,zt=ae.scrollTop;e.style.cssText="",He.style.cssText="",ce.style.cssText="",ue.style.cssText="",ae.style.cssText="",Y.style.cssText="",$e&&(ae.style.display="none"),(y||v)&&(e.style.minWidth="0");let bn=()=>{if(zt<=0)return;(ae.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ae.scrollTop===zt)return;let nn=ae.scrollHeight-ae.clientHeight;nn<=0||(ae.scrollTop=Math.min(zt,nn))})};if(xe){He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),He.style.cssText=`
49
+ `,R.addEventListener("click",()=>{f=P,L.forEach((F,O)=>{let $=O<P;F.classList.toggle("selected",$),F.setAttribute("aria-checked",O===P-1?"true":"false")})}),L.push(R),T.appendChild(R)}g.appendChild(T);let A=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",A=document.createElement("textarea"),A.className="persona-feedback-comment",A.placeholder=a,A.rows=3,A.setAttribute("aria-label","Additional comments"),P.appendChild(A),g.appendChild(P)}let S=document.createElement("div");S.className="persona-feedback-actions";let C=document.createElement("button");C.type="button",C.className="persona-feedback-btn persona-feedback-btn-skip",C.textContent=l,C.addEventListener("click",()=>{n?.(),c.remove()});let M=document.createElement("button");return M.type="button",M.className="persona-feedback-btn persona-feedback-btn-submit",M.textContent=s,M.addEventListener("click",async()=>{if(f===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}M.disabled=!0,M.textContent="Submitting...";try{let P=A?.value.trim()||void 0;await t(f,P),c.remove()}catch(P){M.disabled=!1,M.textContent=s,console.error("[CSAT Feedback] Failed to submit:",P)}}),S.appendChild(C),S.appendChild(M),g.appendChild(S),c.appendChild(g),c}function Kl(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:a="What could we do better? (optional)...",submitText:s="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,f=document.createElement("div");f.className="persona-feedback-container persona-feedback-nps",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Net Promoter Score feedback");let g=null,m=document.createElement("div");m.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,b.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,b.appendChild(T),m.appendChild(b);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let C=document.createElement("span");C.className="persona-feedback-label-high",C.textContent=c,A.appendChild(S),A.appendChild(C);let M=document.createElement("div");M.className="persona-feedback-numbers";let P=[];for(let E=0;E<=10;E++){let G=document.createElement("button");G.type="button",G.className="persona-feedback-rating-btn persona-feedback-number-btn",G.setAttribute("role","radio"),G.setAttribute("aria-checked","false"),G.setAttribute("aria-label",`Rating ${E} out of 10`),G.textContent=String(E),G.dataset.rating=String(E),E<=6?G.classList.add("persona-feedback-detractor"):E<=8?G.classList.add("persona-feedback-passive"):G.classList.add("persona-feedback-promoter"),G.addEventListener("click",()=>{g=E,P.forEach((Q,Z)=>{Q.classList.toggle("selected",Z===E),Q.setAttribute("aria-checked",Z===E?"true":"false")})}),P.push(G),M.appendChild(G)}L.appendChild(A),L.appendChild(M),m.appendChild(L);let R=null;if(p){let E=document.createElement("div");E.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=a,R.rows=3,R.setAttribute("aria-label","Additional comments"),E.appendChild(R),m.appendChild(E)}let F=document.createElement("div");F.className="persona-feedback-actions";let O=document.createElement("button");O.type="button",O.className="persona-feedback-btn persona-feedback-btn-skip",O.textContent=l,O.addEventListener("click",()=>{n?.(),f.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=s,$.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let E=R?.value.trim()||void 0;await t(g,E),f.remove()}catch(E){$.disabled=!1,$.textContent=s,console.error("[NPS Feedback] Failed to submit:",E)}}),F.appendChild(O),F.appendChild($),m.appendChild(F),f.appendChild(m),f}var Ta="persona-chat-history",gS=30*1e3,hS=641,yS={"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 bS(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 a=yS[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${a}`,{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 Xl(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 xS(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 vS(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var cf=e=>!e||typeof e!="object"?{}:{...e},sb=e=>e.map(t=>({...t,streaming:!1})),ib=(e,t,n)=>{let o=e?.markdown?hr(e.markdown):null,r=ta(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."),a=>{let s=a.text??"",l=a.message.rawContent??null;if(t){let c=t.process({text:s,raw:l??s,message:a.message,streaming:a.streaming});c!==null&&(s=c.text,c.persist||(a.message.__skipPersist=!0),c.resubmit&&!a.streaming&&n&&n())}let p=ao()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...a,text:s,raw:l??a.text??""});d=r?r(c):c}else if(o){let c=a.streaming?hg(s):s,f=o(c);d=r&&p?r(f):f}else d=Vn(s);return d}};function lb(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)",a=e?.iconStrokeWidth??.5,s=ae(n,o,r,a);if(s&&t.appendChild(s),e?.label){let l=v("span","persona-drop-overlay-label");l.textContent=e.label,t.appendChild(l)}return t}var CS=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let a=n[o];n[o]=a?{...a,...r}:r}return n},wS=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:CS(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Jl=(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=da(t),r=o.features;o=Hs(o);let a=Bs.getForInstance(o.plugins),s=!1,l=Ty(()=>o),{plugin:p,teardown:d}=Dy();o.components&&Nn.registerAll(o.components);let c=tb(),g=o.persistState===!1?null:o.storageAdapter??Vl(),m={},b=null,w=!1,T=i=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(i);if(u&&typeof u=="object"&&"state"in u){let{state:h,open:x}=u;return x&&(w=!0),h}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return i};if(g?.load)try{let i=g.load();if(i&&typeof i.then=="function")b=i.then(u=>T(u??{messages:[],metadata:{}}));else{let h=T(i??{messages:[],metadata:{}});h.metadata&&(m=cf(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=T({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}let L=()=>m,A=i=>{m=i({...m})??{},yc()},S=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],C=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick],M=Fs({parsers:S,handlers:C,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,F=o.autoFocusInput??!1,O=R,$=P,E=o.layout?.header?.layout,G=!1,Q=()=>Ko(o),Z=()=>P||Q(),J=Q()?!1:P?R:!0,fe=!1,ne=null,ge=()=>{fe=!0,ne&&clearTimeout(ne),ne=setTimeout(()=>{fe&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),fe=!1)},1e4)},ie=ib(o,M,ge),ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,Se=o.features?.scrollToBottom??{},Ce=o.features?.scrollBehavior??{},ut=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Je=me?new Ps(ut):null,Qe=o.features?.eventStream?.maxEvents??2e3,Ne=me?new Ls(Qe,Je):null,_e=me?new Rs:null,Ae=null,Me=!1,qe=null,Jt=0;Je?.open().then(()=>Ne?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let gt={onCopy:i=>{c.emit("message:copy",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{c.emit("message:feedback",i),q?.isClientTokenMode()&&q.submitMessageFeedback(i.messageId,i.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(i)}},Bt=o.statusIndicator??{},Tn=i=>i==="idle"?Bt.idleText??Ht.idle:i==="connecting"?Bt.connectingText??Ht.connecting:i==="connected"?Bt.connectedText??Ht.connected:i==="error"?Bt.errorText??Ht.error:i==="paused"?Bt.pausedText??Ht.paused:i==="resuming"?Bt.resumingText??Ht.resuming:Ht[i];function En(i,u,h,x){if(x==="idle"&&h.idleLink){i.textContent="";let k=document.createElement("a");k.href=h.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=u,k.style.color="inherit",k.style.textDecoration="none",i.appendChild(k)}else i.textContent=u}let et=My({config:o,showClose:Z()}),{wrapper:Le,panel:he,pillRoot:tt}=et.shell,Te=et.panelElements,{container:be,body:re,messagesWrapper:xe,starterSuggestions:kn,transcriptSuggestions:ee,suggestions:I,textarea:B,sendButton:y,sendButtonWrapper:D,composerForm:H,statusText:N,welcomeHost:K,welcomeIconHolder:V,greetingHost:X,introTitle:ce,introSubtitle:Ve,closeButton:de,iconHolder:Pe,headerTitle:ze,headerSubtitle:Ue,header:We,footer:we,actionsRow:nt,rightActions:wt}=Te,yn=Te.leftActions,Us=Te.setSendButtonMode,te=Te.micButton,bn=Te.micButtonWrapper,it=Te.attachmentButton,xn=Te.attachmentButtonWrapper,Et=Te.attachmentInput,Ln=Te.attachmentPreviewsContainer;be.classList.add("persona-relative"),re.classList.add("persona-relative");let Gb=12,ka=()=>Se.label??"",Kb=()=>Se.iconName??"arrow-down",Xb=()=>Se.enabled!==!1,cn=()=>Ce.mode??"anchor-top",ho=()=>cn()==="follow"||cn()==="anchor-top"&&Oa,La=()=>Ce.anchorTopOffset??16,Jb=()=>Ce.restorePosition??"bottom",Mf=()=>Ce.pauseOnInteraction===!0,Tf=()=>Ce.showActivityWhilePinned!==!1,Ef=()=>Ce.announce===!0,ec=()=>Ce.scrollbar??"on-scroll",Pt=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");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let Pa=v("span","persona-flex persona-items-center"),tc=v("span",""),Jo=v("span","");Jo.setAttribute("data-persona-scroll-to-bottom-count",""),Jo.style.display="none",Pt.append(Pa,tc,Jo),be.appendChild(Pt);let vn=v("div","persona-stream-anchor-spacer");vn.setAttribute("aria-hidden","true"),vn.setAttribute("data-persona-anchor-spacer",""),vn.style.flexShrink="0",vn.style.pointerEvents="none",vn.style.height="0px",vn.style.display="none",re.appendChild(vn);let Qo=v("div","persona-sr-only");Qo.setAttribute("aria-live","polite"),Qo.setAttribute("aria-atomic","true"),Qo.setAttribute("role","status"),Qo.setAttribute("data-persona-live-region",""),Object.assign(Qo.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"}),be.appendChild(Qo);let Ra=null,qs=null,kf=i=>{!Ef()||!i||(qs=i,Ra===null&&(Ra=setTimeout(()=>{Ra=null,qs&&Ef()&&(Qo.textContent=qs),qs=null},400)))},Yo=()=>{let u=we.style.display==="none"?0:we.offsetHeight;Pt.style.bottom=`${u+Gb}px`};Yo();let Lf=()=>{let i=!!ka();Pt.setAttribute("aria-label",ka()||"Jump to latest"),Pt.title=ka(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),Pa.innerHTML="";let u=ae(Kb(),"14px","currentColor",2);u?(Pa.appendChild(u),Pa.style.display=""):Pa.style.display="none",tc.textContent=ka(),tc.style.display=i?"":"none"};Lf();let bt=null,Qt=null,Pf=null,Rf=a.find(i=>i.renderHeader);if(Rf?.renderHeader){let i=Rf.renderHeader({config:o,defaultRenderer:()=>{let u=fo({config:o,showClose:Z()});return kr(be,u,o),u.header},onClose:()=>lt(!1,"user")});if(i){let u=be.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(i),We=i,et.header.element=i)}}let nc=()=>{if(!Ne)return;if(Me=!0,!Ae&&Ne&&(Ae=_y({buffer:Ne,getFullHistory:()=>Ne.getAllFromStore(),onClose:()=>Ia(),config:o,plugins:a,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),Ae&&(re.style.display="none",we.parentNode?.insertBefore(Ae.element,we),Ae.update()),Ye){Ye.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(h=>h&&Ye.classList.add(h))}let i=()=>{if(!Me)return;let u=Date.now();u-Jt>=200&&(Ae?.update(),Jt=u),qe=requestAnimationFrame(i)};Jt=0,qe=requestAnimationFrame(i),Vt(),c.emit("eventStream:opened",{timestamp:Date.now()})},Ia=()=>{if(Me){if(Me=!1,Ae&&Ae.element.remove(),re.style.display="",Ye){Ye.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(u=>u&&Ye.classList.remove(u))}qe!==null&&(cancelAnimationFrame(qe),qe=null),Vt(),c.emit("eventStream:closed",{timestamp:Date.now()})}},Ye=null;if(me){let i=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"+(i?.toggleButton?" "+i.toggleButton:"");Ye=v("button",u),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let h=ae("activity","18px","currentColor",1.5);h&&Ye.appendChild(h);let x=Te.clearChatButtonWrapper,k=Te.closeButtonWrapper,W=x||k;W&&W.parentNode===We?We.insertBefore(Ye,W):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}let If=i=>{let u=o.attachments;if(!u?.enabled)return;let h=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!h){h=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let k=i.querySelector("[data-persona-composer-form]");k?.parentNode?k.parentNode.insertBefore(h,k):i.insertBefore(h,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let k=v("input");k.type="file",k.setAttribute("data-persona-composer-attachment-input",""),k.accept=(u.allowedTypes??co).join(","),k.multiple=(u.maxFiles??4)>1,k.style.display="none",k.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),i.appendChild(k)}},oc=a.find(i=>i.renderComposer),rc=!1,Wf=i=>{if(!oc?.renderComposer)return null;let u=o.composer,h=s?q.isStreaming():!1;return oc.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Gx(),storage:l(oc.id),onSubmit:x=>{if(!q||q.isStreaming())return;let k=x.trim(),W=bt?.hasAttachments()??!1;if(!k&&!W)return;Hm();let z;W&&(z=[],z.push(...bt.getContentParts()),k&&z.push(Oo(k))),q.sendMessage(k,{contentParts:z}),W&&bt.clearAttachments()},streaming:h,disabled:h,openAttachmentPicker:()=>{Et?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Pf?.()}:void 0})},Hf=Wf(()=>Lr({config:o}).footer);Hf&&(et.replaceComposer(Hf),we=et.composer.footer,rc=!0);let Bf=i=>{let u=(...pe)=>{for(let le of pe){let ye=i.querySelector(le);if(ye)return ye}return null},h=i.querySelector("[data-persona-composer-form]"),x=i.querySelector("[data-persona-composer-input]"),k=i.querySelector("[data-persona-composer-submit]"),W=i.querySelector("[data-persona-composer-mic]"),z=i.querySelector("[data-persona-composer-status]");h&&(H=h),x&&(B=x),k&&(y=k),W&&(te=W,bn=W.parentElement),z&&(N=z);let U=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(I=U);let j=u("[data-persona-composer-attachment-button]",".persona-attachment-button");j&&(it=j,xn=j.parentElement),Et=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Ln=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let Y=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");Y&&(nt=Y),yn=u(".persona-widget-composer__left-actions")};If(we),Bf(we);let Wa=qo(o,Q());Wa&&(xe.style.maxWidth=Wa,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Wa,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",kn.style.maxWidth=Wa,ee.style.maxWidth=Wa,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%");let Df=()=>{let i=qo(o,Q());if(!(!i||Q()))for(let u of[H,I,Ln,N])u&&(u.style.maxWidth=i,u.style.marginLeft="auto",u.style.marginRight="auto")};Df();let Ff=()=>{!o.attachments?.enabled||!Et||!Ln||(bt?bt.remountPreviews(Ln):(bt=Ar.fromConfig(o.attachments),bt.setPreviewsContainer(Ln)),Et.addEventListener("change",i=>{let u=i.target;bt?.handleFileSelect(u.files),u.value=""}),be.querySelector(".persona-attachment-drop-overlay")||be.appendChild(lb(o.attachments.dropOverlay)))};Ff();let Qb=()=>Qt?.prefetch(),Of=()=>{if(!(!o.contextMentions?.enabled||!B)&&(Qt=Ch({config:o,textarea:B,anchor:H??B,getMessages:()=>q.getMessages(),liveRegionHost:be}),Qt)){let i=B;i.parentElement?.insertBefore(Qt.contextRow,i);let u=Qt.affordanceButtons;for(let h=u.length-1;h>=0;h--){let x=u[h];yn?yn.insertBefore(x,yn.firstChild):H?.appendChild(x)}}};Of(),(()=>{let i=o.layout?.slots??{},u=x=>{switch(x){case"body-top":return re.querySelector("[data-persona-intro-card]");case"messages":return xe;case"footer-top":return I;case"composer":return H;case"footer-bottom":return N;default:return null}},h=(x,k)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")We.insertBefore(k,We.firstChild);else if(x==="header-right")We.appendChild(k);else{let W=We.querySelector(".persona-flex-col");W?W.parentNode?.insertBefore(k,W.nextSibling):We.appendChild(k)}break;case"body-top":{let W=re.querySelector("[data-persona-intro-card]");W?W.replaceWith(k):re.insertBefore(k,re.firstChild);break}case"body-bottom":re.appendChild(k);break;case"footer-top":I.replaceWith(k);break;case"footer-bottom":N.replaceWith(k);break;default:break}};for(let[x,k]of Object.entries(i))if(k)try{let W=k({config:o,defaultContent:()=>u(x)});W&&h(x,W)}catch(W){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,W)}})();let Nf=i=>{let h=i.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")va.has(k)?va.delete(k):va.add(k),Ey(k,x);else if(W==="tool")Ca.has(k)?Ca.delete(k):Ca.add(k),ky(k,x,o);else if(W==="approval"){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",j=Rr.get(k)??U;Rr.set(k,!j),Iy(k,x,o)}ar.delete(k)};xe.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("keydown",i=>{let u=i.target;(i.key==="Enter"||i.key===" ")&&u.closest('button[data-expand-header="true"]')&&(i.preventDefault(),Nf(i))}),xe.addEventListener("copy",i=>{let{clipboardData:u}=i;if(!u)return;let h=xe.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let k=x.toString(),W=jh(k);!W||W===k||(u.setData("text/plain",W),i.preventDefault())});let ac=new Map,_f=null,Uf="idle",Yb={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Zb=(i,u)=>{let{icon:h,label:x}=Yb[u];i.setAttribute("aria-label",x),i.title=x,i.setAttribute("aria-pressed",u==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",u!=="idle"),i.classList.toggle("persona-message-action-loading",u==="loading");let k=ae(h,14,"currentColor",2);k&&(i.innerHTML="",i.appendChild(k))},qf=()=>{xe.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let x=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Zb(u,x&&x===_f?Uf:"idle")})};xe.addEventListener("click",i=>{let h=i.target.closest(".persona-message-action-btn[data-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let k=x.getAttribute("data-actions-for");if(!k)return;let W=h.getAttribute("data-action");if(W==="copy"){let U=q.getMessages().find(j=>j.id===k);if(U&&gt.onCopy){let j=U.content||"";navigator.clipboard.writeText(j).then(()=>{h.classList.add("persona-message-action-success");let Y=ae("check",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let pe=ae("copy",14,"currentColor",2);pe&&(h.innerHTML="",h.appendChild(pe))},2e3)}).catch(Y=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",Y)}),gt.onCopy(U)}}else if(W==="read-aloud")q.toggleReadAloud(k);else if(W==="upvote"||W==="downvote"){let U=(ac.get(k)??null)===W,j=W==="upvote"?"thumbs-up":"thumbs-down";if(U){ac.delete(k),h.classList.remove("persona-message-action-active");let Y=ae(j,14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))}else{let Y=W==="upvote"?"downvote":"upvote",pe=x.querySelector(`[data-action="${Y}"]`);if(pe){pe.classList.remove("persona-message-action-active");let ct=ae(Y==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(pe.innerHTML="",pe.appendChild(ct))}ac.set(k,W),h.classList.add("persona-message-action-active");let le=ae(j,14,"currentColor",2);le&&(le.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(le)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ge=q.getMessages().find(ht=>ht.id===k);Ge&&gt.onFeedback&&gt.onFeedback({type:W,messageId:Ge.id,message:Ge})}}}),xe.addEventListener("click",i=>{let h=i.target.closest("button[data-approval-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let k=x.getAttribute("data-message-id");if(!k)return;let W=h.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",j=q.getMessages().find(pe=>pe.id===k);if(!j?.approval)return;let Y=x.querySelector("[data-approval-buttons]");Y&&Y.querySelectorAll("button").forEach(le=>{le.disabled=!0,le.style.opacity="0.5",le.style.cursor="not-allowed"}),j.approval.toolType==="webmcp"?q.resolveWebMcpApproval(k,z):q.resolveApproval(j.approval,z)});let Ke=null,Ha=null,Zo=()=>{},Ba="none",Vs=null,Pn={artifacts:[],selectedId:null},Xn=!1,Rn=!1,Da=!1,Fr=!1,Vf=()=>Fr||Pn.artifacts.some(i=>zn(o.features?.artifacts,i)==="panel"),zs=()=>Pn.artifacts.length>0&&!Xn&&Vf(),at={current:null},sc=(i,u)=>{let h=q.getArtifactById(u),x=h?.markdown,k=h?.title||"artifact",W=h?.file,z=h?.artifactType??"markdown";if(!x){let Y=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(Y){let le=q.getMessages().find(ye=>ye.id===Y);if(le?.rawContent)try{let ye=JSON.parse(le.rawContent);x=ye?.props?.markdown,k=ye?.props?.title||k,ye?.props?.file&&typeof ye.props.file=="object"&&(W=ye.props.file),!h&&typeof ye?.props?.artifactType=="string"&&(z=ye.props.artifactType)}catch{}}}return{markdown:x,title:k,file:W,artifactType:z}};xe.addEventListener("click",i=>{let h=i.target.closest("[data-download-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:W,title:z,file:U}=sc(h,x);if(!W)return;let{filename:j,mime:Y,content:pe}=kh({title:z,markdown:W,file:U}),le=new Blob([pe],{type:Y}),ye=URL.createObjectURL(le),Ge=document.createElement("a");Ge.href=ye,Ge.download=j,Ge.click(),URL.revokeObjectURL(ye)}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-artifact-custom-action]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let k=h.closest("[data-artifact-inline]"),W=k?null:h.closest("[data-open-artifact]"),z=k?k.getAttribute("data-artifact-inline"):W?.getAttribute("data-open-artifact")??null,j=(k?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===x);if(!j)return;let{markdown:Y,title:pe,file:le,artifactType:ye}=sc(h,z??""),Ge={artifactId:z,title:pe,artifactType:ye,markdown:Y,file:le};try{Promise.resolve(j.onClick(Ge)).catch(()=>{})}catch{}}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-copy-artifact]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let k=q.getArtifactById(x),W="";if(k)W=vs(k);else{let{markdown:z,file:U,artifactType:j}=sc(h,x);j==="markdown"&&(W=vs({id:x,artifactType:"markdown",status:"complete",markdown:z??"",...U?{file:U}:{}}))}W&&navigator.clipboard.writeText(W).then(()=>{let z=ae("check",16,"currentColor",2);z&&(h.replaceChildren(z),setTimeout(()=>{let U=ae("copy",16,"currentColor",2);U&&h.replaceChildren(U)},1500))}).catch(()=>{})}),xe.addEventListener("click",i=>{let h=i.target.closest("[data-expand-artifact-inline]");if(!h)return;i.preventDefault(),i.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Xn=!1,Fr=!0,Rn=!0,Da=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("click",i=>{let u=i.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let h=u.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(i.preventDefault(),i.stopPropagation(),Xn=!1,Fr=!0,q.selectArtifact(x),Jn())}),xe.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let u=i.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),u.click())});let Or=Te.composerOverlay,Nr=(i,u,h)=>{let x=u.trim();if(!x||!at.current)return;let k=i.getAttribute("data-tool-call-id")??"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:k,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Wo(Or,k);let z=at.current.getMessages().find(U=>U.toolCall?.id===k);z?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(z,h.structured??x):at.current.sendMessage(x)},er=i=>{let u=at.current;if(!u)return;let h=i.getAttribute("data-tool-call-id")??"",x=u.getMessages().find(k=>k.toolCall?.id===h);x&&u.persistAskUserQuestionProgress(x,{answers:Si(i,x),currentIndex:Sn(i)})},zf=i=>Object.entries(i).map(([u,h])=>`${u}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),ic=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=Sn(i),h=ra(i);if(u>=h-1)return;let x=at.current?.getMessages().find(k=>k.toolCall?.id===i.getAttribute("data-tool-call-id"));x&&(Mi(i,x,o,u+1),er(i))};Or.addEventListener("click",i=>{let h=i.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let k=h.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),k==="dismiss"){let W=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W);let z=at.current?.getMessages().find(U=>U.toolCall?.id===W);z?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(z),at.current?.resolveAskUserQuestion(z,"(dismissed)"));return}if(k==="pick"){let W=h.getAttribute("data-option-label");if(!W)return;let z=x.getAttribute("data-multi-select")==="true",U=Io(x);if(U&&z){let j=yr(x)[Sn(x)],Y=new Set(Array.isArray(j)?j:[]);Y.has(W)?Y.delete(W):Y.add(W),Ho(x,Array.from(Y)),er(x);return}if(U){Ho(x,W),er(x),ic(x);return}if(z){let j=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",j?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!j);let Y=x.querySelector('[data-ask-user-action="submit-multi"]');Y&&(Y.disabled=nd(x).length===0);return}Nr(x,W,{source:"pick",values:[W]});return}if(k==="submit-multi"){let W=nd(x);if(W.length===0)return;Nr(x,W.join(", "),{source:"multi",values:W});return}if(k==="open-free-text"){let W=x.querySelector('[data-ask-free-text-row="true"]');W&&(W.classList.remove("persona-hidden"),W.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(k==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(k==="submit-free-text"){let z=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!z.trim())return;if(Io(x)){Ho(x,z.trim()),er(x),ic(x);return}Nr(x,z,{source:"free-text"});return}if(k==="next"||k==="back"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(j){let le=yr(x)[Sn(x)];(typeof le!="string"||le!==j)&&Ho(x,j)}let Y=k==="next"?1:-1,pe=Sn(x)+Y;Mi(x,z,o,pe),er(x);return}if(k==="submit-all"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(le=>le.toolCall?.id===W);if(!z)return;let j=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";j&&Ho(x,j);let Y=Si(x,z);at.current.persistAskUserQuestionProgress(z,{answers:Y,currentIndex:Sn(x)});let pe=zf(Y);Nr(x,pe||"(submitted)",{source:"submit-all",structured:Y});return}if(k==="skip"){if(!at.current)return;let W=x.getAttribute("data-tool-call-id")??"",z=at.current.getMessages().find(ye=>ye.toolCall?.id===W);if(!z)return;let U=Io(x),j=Sn(x),Y=ra(x),pe=j>=Y-1;if(!U){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:W},bubbles:!0,composed:!0})),Wo(Or,W),z.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(z),at.current.resolveAskUserQuestion(z,"(dismissed)"));return}Ho(x,"");let le=x.querySelector('[data-ask-free-text-input="true"]');if(le&&(le.value=""),pe){let ye=Si(x,z),Ge=zf(ye);Nr(x,Ge||"(skipped)",{source:"submit-all",structured:ye});return}Mi(x,z,o,j+1),er(x);return}}),Or.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let h=i.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;i.preventDefault();let k=h.value;if(k.trim()){if(Io(x)){Ho(x,k.trim()),er(x),ic(x);return}Nr(x,k,{source:"free-text"})}});let $f=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let u=i.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let h=Or.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(i.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(i.preventDefault(),W.click())};document.addEventListener("keydown",$f);let yo=null,xt=null,Fa=null,$s=null,lc=()=>{},jf=!1,js="",Gs="";function cc(){$s?.(),$s=null}let Gf=()=>{if(!yo||!xt)return;let i=e.classList.contains("persona-artifact-welded-split"),u=e.ownerDocument.defaultView??window,h=u.innerWidth<=640;if(!i||e.classList.contains("persona-artifact-narrow-host")||h){xt.style.removeProperty("position"),xt.style.removeProperty("left"),xt.style.removeProperty("top"),xt.style.removeProperty("bottom"),xt.style.removeProperty("width"),xt.style.removeProperty("z-index");return}let x=yo.firstElementChild;if(!x||x===xt)return;let k=10;xt.style.position="absolute",xt.style.top="0",xt.style.bottom="0",xt.style.width=`${k}px`,xt.style.zIndex="5";let W=rf(yo,u),z=x.offsetWidth+W/2-k/2;xt.style.left=`${Math.max(0,z)}px`},Ks=()=>{},ex=()=>{let i=e.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!u||i.innerWidth>h?!1:P||St(o)},Xs=()=>!tn(o)||!zs()||e.classList.contains("persona-artifact-narrow-host")||ex()||(e.ownerDocument.defaultView??window).innerWidth<hS?"none":ef(o)?"detached":"welded",Jn=()=>{if(!Ke||!tn(o))return;Is(e,o),Ws(e,o),Ks();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=he.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=i);let h=zs();Ke.setVisible(h),Ke.update(Pn),Xn?(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1):Pn.artifacts.length>0&&Vf()?(Ke.element.classList.remove("persona-hidden"),Ke.setMobileOpen(!0)):(Ke.setMobileOpen(!1),Ke.element.classList.add("persona-hidden"),Ke.backdrop?.classList.add("persona-hidden"),Rn=!1,Da=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ke.setExpandToggleVisible(x),Ke.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ke.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ke.setTabFade(o.features?.artifacts?.layout?.tabFade),Ke.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Da&&(Rn=!1),Rn!==jf){let W=Ke.element;Rn?(js=W.style.width,Gs=W.style.maxWidth,W.style.removeProperty("width"),W.style.removeProperty("max-width")):(js&&(W.style.width=js),Gs&&(W.style.maxWidth=Gs),js="",Gs=""),jf=Rn}e.classList.toggle("persona-artifact-expanded",Rn),Ke.setExpanded(Rn);let k=Xs();k!==Ba&&(Ba=k,Zo()),lc()};if(tn(o)){he.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(be),Ke=qy(o,{onSelect:h=>at.current?.selectArtifact(h),onDismiss:()=>{Xn=!0,Jn()},onToggleExpand:()=>{let h=!Rn,x=Pn.selectedId??Pn.artifacts[Pn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(Rn=h,h||(Da=!1),Jn())}}),Ke.element.classList.add("persona-hidden"),yo=u,u.appendChild(i),u.appendChild(Ke.element),Ke.backdrop&&he.appendChild(Ke.backdrop),he.appendChild(u),lc=()=>{if(!yo||!Ke)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke.element.style.removeProperty("width"),Ke.element.style.removeProperty("maxWidth");return}if(!xt){let x=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let k=e.ownerDocument,W=k.defaultView??window,z=U=>{if(!Ke||U.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||W.innerWidth<=640)return;U.preventDefault(),cc();let j=U.clientX,Y=Ke.element.getBoundingClientRect().width,pe=o.features?.artifacts?.layout,le=Ge=>{let ht=yo.getBoundingClientRect().width,ct=e.classList.contains("persona-artifact-welded-split"),un=rf(yo,W),Mt=ct?0:x.getBoundingClientRect().width||6,It=Y-(Ge.clientX-j),_=Qy(It,ht,un,Mt,pe?.resizableMinWidth,pe?.resizableMaxWidth);Ke.element.style.width=`${_}px`,Ke.element.style.maxWidth="none",Gf()},ye=()=>{k.removeEventListener("pointermove",le),k.removeEventListener("pointerup",ye),k.removeEventListener("pointercancel",ye),$s=null;try{x.releasePointerCapture(U.pointerId)}catch{}};$s=ye,k.addEventListener("pointermove",le),k.addEventListener("pointerup",ye),k.addEventListener("pointercancel",ye);try{x.setPointerCapture(U.pointerId)}catch{}};x.addEventListener("pointerdown",z),xt=x,yo.insertBefore(x,Ke.element),Fa=()=>{x.removeEventListener("pointerdown",z)}}if(xt){let x=zs();xt.classList.toggle("persona-hidden",!x),Gf()}},Ks=()=>{if(!P||!Ke||(o.launcher?.sidebarMode??!1)||St(o)&&ln(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W||!$y(o,P))return;let z=o.launcher?.width??o.launcherWidth??mn,U=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";zs()?(he.style.width=U,he.style.maxWidth=U):(he.style.width=z,he.style.maxWidth=z)},typeof ResizeObserver<"u"&&(Ha=new ResizeObserver(()=>{Jn()}),Ha.observe(he))}else he.appendChild(be);Q()&&tt&&(Te.peekBanner&&tt.appendChild(Te.peekBanner),tt.appendChild(we)),e.appendChild(Le),tt&&e.appendChild(tt);let dc=()=>{if(Q()){he.style.width="100%",he.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},an=Le.dataset.state==="expanded",fi=Lt.expandedSize??"anchored";if(!(an&&fi!=="fullscreen")){be.style.background="",be.style.border="",be.style.borderRadius="",be.style.overflow="",be.style.boxShadow="";return}let Ya=o.theme?.components?.panel,mi=Uo(o),Qr=(oo,gr)=>oo==null||oo===""?gr:en(mi,oo)??oo,gi="1px solid var(--persona-border)",Vc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mr="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";be.style.background="var(--persona-surface, #ffffff)",be.style.border=Qr(Ya?.border,gi),be.style.borderRadius=Qr(Ya?.borderRadius,mr),be.style.boxShadow=Qr(Ya?.shadow,Vc),be.style.overflow="hidden";return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=i||u||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,k=o.launcher?.detachedPanel===!0,W=o.theme?.components?.panel,z=Uo(o),U=(Lt,an)=>Lt==null||Lt===""?an:en(z,Lt)??Lt,j=e.ownerDocument.defaultView??window,Y=o.launcher?.mobileFullscreen??!0,pe=o.launcher?.mobileBreakpoint??640,le=j.innerWidth<=pe,ye=Y&&le&&P,Ge=i&&Y&&le,ht=o.launcher?.position??"bottom-left",ct=ht==="bottom-left"||ht==="top-left",un=o.launcher?.zIndex??Ut,Mt="var(--persona-panel-border, 1px solid var(--persona-border))",It="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=k&&!ye&&!Ge;Re?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let Fe=Re?Mt:u||ye?"none":Mt,Ee=Re?It:ye?"none":u?ct?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":x?"none":It;i&&!ye&&!Re&&(Ee="none",Fe="none");let At=Re?_:u||ye?"0":_,dt=U(W?.border,Fe),Ot=U(W?.shadow,Ee),pt=U(W?.borderRadius,At),rn=Xs(),Wt=rn==="detached",Ie=rn==="welded";e.classList.toggle("persona-artifact-detached-split",Wt),e.classList.toggle("persona-artifact-welded-split",Ie);let Oe="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)))))",Ct=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&tn(o)&&ef(o)&&x&&!i;e.classList.toggle("persona-artifact-chat-flush",Ct);let st=Wt||Ct?"none":Ot,ft=Wt?Mt:Ie?"none":dt,Xe=Wt?_:pt;Ct&&(ft="none",Xe="0");let He=W?.borderRadius!=null&&W.borderRadius!=="",yt=Ct&&!He?"0":pt,jt=re.scrollTop;e.style.cssText="",Le.style.cssText="",he.style.cssText="",be.style.cssText="",re.style.cssText="",we.style.cssText="",Me&&(re.style.display="none"),(h||x)&&(e.style.minWidth="0");let An=()=>{if(jt<=0)return;(re.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(re.scrollTop===jt)return;let an=re.scrollHeight-re.clientHeight;an<=0||(re.scrollTop=Math.min(jt,an))})};if(ye){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=`
50
50
  position: fixed !important;
51
51
  inset: 0 !important;
52
52
  width: 100% !important;
@@ -56,9 +56,9 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
56
56
  padding: 0 !important;
57
57
  display: flex !important;
58
58
  flex-direction: column !important;
59
- z-index: ${dn} !important;
59
+ z-index: ${un} !important;
60
60
  background-color: var(--persona-surface, #ffffff) !important;
61
- `,ce.style.cssText=`
61
+ `,he.style.cssText=`
62
62
  position: relative !important;
63
63
  display: flex !important;
64
64
  flex-direction: column !important;
@@ -71,7 +71,7 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
71
71
  padding: 0 !important;
72
72
  box-shadow: none !important;
73
73
  border-radius: 0 !important;
74
- `,ue.style.cssText=`
74
+ `,be.style.cssText=`
75
75
  display: flex !important;
76
76
  flex-direction: column !important;
77
77
  flex: 1 1 0% !important;
@@ -82,33 +82,33 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
82
82
  overflow: hidden !important;
83
83
  border-radius: 0 !important;
84
84
  border: none !important;
85
- `,ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Y.style.flexShrink="0",j=!0,bn();return}let Us=o?.launcher?.width??o?.launcherWidth??pn;if(!m&&!i)v&&y?(ce.style.width="100%",ce.style.maxWidth="100%"):(ce.style.width=Us,ce.style.maxWidth=Us);else if(i)if(rn(o).reveal==="emerge"&&!L){let nn=rn(o).width;ce.style.width=nn,ce.style.maxWidth=nn}else ce.style.width="100%",ce.style.maxWidth="100%";if(ws(),ce.style.boxShadow=dt,ce.style.borderRadius=yt,Rt?ce.style.border="none":Ee&&(ce.style.border=ut),ue.style.border=gt,ue.style.borderRadius=Ze,ue.style.boxShadow=Rt&&!vt?Ne:"",vt&&(ue.style.background="transparent",ae.style.background="transparent",Y.style.background="transparent",Y.style.borderTop="none"),Ee){let Tt=o.features?.artifacts?.layout;ys=Tt?.unifiedSplitOuterRadius?.trim()||Tt?.paneBorderRadius?.trim()||ft}else ys=null;if(i&&!xe&&!Te&&!Rt&&!Ee&&I?.border===void 0&&(ue.style.border="none",rn(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),i&&!xe&&Ee&&I?.border===void 0&&(rn(o).side==="right"?ce.style.borderLeft="1px solid var(--persona-border)":ce.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",v&&(e.style.width="100%"),He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.height="100%",v&&(He.style.overflow="hidden"),ce.style.display="flex",ce.style.flexDirection="column",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.maxHeight="100%",ce.style.height="100%",Rt||(ce.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",ae.style.flex="1 1 0%",ae.style.minHeight="0",ae.style.overflowY="auto",Y.style.flexShrink="0"),v&&(Te||Rt||vt)&&!i&&(vt||(He.style.padding="var(--persona-panel-inset)"),He.style.background="var(--persona-panel-canvas-bg)"),He.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!v&&!i&&(Pn[pt]??Pn["bottom-right"]).split(" ").forEach(nn=>He.classList.add(nn)),m){let Tt=o.launcher?.sidebarWidth??"420px";L?He.style.cssText=`
85
+ `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",we.style.flexShrink="0",G=!0,An();return}let ui=o?.launcher?.width??o?.launcherWidth??mn;if(!u&&!i)x&&h?(he.style.width="100%",he.style.maxWidth="100%"):(he.style.width=ui,he.style.maxWidth=ui);else if(i)if(ln(o).reveal==="emerge"&&!k){let an=ln(o).width;he.style.width=an,he.style.maxWidth=an}else he.style.width="100%",he.style.maxWidth="100%";if(Ks(),he.style.boxShadow=st,he.style.borderRadius=yt,Wt?he.style.border="none":Ie&&(he.style.border=dt),be.style.border=ft,be.style.borderRadius=Xe,be.style.boxShadow=Wt&&!Ct?Oe:"",Ct&&(be.style.background="transparent",re.style.background="transparent",we.style.background="transparent",we.style.borderTop="none"),Ie){let Lt=o.features?.artifacts?.layout;Vs=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||pt}else Vs=null;if(i&&!ye&&!Re&&!Wt&&!Ie&&W?.border===void 0&&(be.style.border="none",ln(o).side==="right"?be.style.borderLeft="1px solid var(--persona-border)":be.style.borderRight="1px solid var(--persona-border)"),i&&!ye&&Ie&&W?.border===void 0&&(ln(o).side==="right"?he.style.borderLeft="1px solid var(--persona-border)":he.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),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%",x&&(Le.style.overflow="hidden"),he.style.display="flex",he.style.flexDirection="column",he.style.flex="1 1 0%",he.style.minHeight="0",he.style.maxHeight="100%",he.style.height="100%",Wt||(he.style.overflow="hidden"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",we.style.flexShrink="0"),x&&(Re||Wt||Ct)&&!i&&(Ct||(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&&!x&&!i&&(gn[ht]??gn["bottom-right"]).split(" ").forEach(an=>Le.classList.add(an)),u){let Lt=o.launcher?.sidebarWidth??"420px";k?Le.style.cssText=`
86
86
  position: fixed !important;
87
87
  top: var(--persona-panel-inset) !important;
88
88
  bottom: var(--persona-panel-inset) !important;
89
- width: ${Tt} !important;
89
+ width: ${Lt} !important;
90
90
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
91
91
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
92
92
  margin: 0 !important;
93
93
  padding: 0 !important;
94
94
  display: flex !important;
95
95
  flex-direction: column !important;
96
- z-index: ${dn} !important;
97
- ${nt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
98
- `:He.style.cssText=`
96
+ z-index: ${un} !important;
97
+ ${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
98
+ `:Le.style.cssText=`
99
99
  position: fixed !important;
100
100
  top: 0 !important;
101
101
  bottom: 0 !important;
102
- width: ${Tt} !important;
102
+ width: ${Lt} !important;
103
103
  height: 100vh !important;
104
104
  max-height: 100vh !important;
105
105
  margin: 0 !important;
106
106
  padding: 0 !important;
107
107
  display: flex !important;
108
108
  flex-direction: column !important;
109
- z-index: ${dn} !important;
110
- ${nt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
111
- `,ce.style.cssText=`
109
+ z-index: ${un} !important;
110
+ ${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
111
+ `,he.style.cssText=`
112
112
  position: relative !important;
113
113
  display: flex !important;
114
114
  flex-direction: column !important;
@@ -119,10 +119,10 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
119
119
  min-height: 0 !important;
120
120
  margin: 0 !important;
121
121
  padding: 0 !important;
122
- box-shadow: ${dt} !important;
122
+ box-shadow: ${st} !important;
123
123
  border-radius: ${yt} !important;
124
- ${Rt?"border: none !important;":Ee?`border: ${ut} !important;`:""}
125
- `,ce.style.setProperty("width","100%","important"),ce.style.setProperty("max-width","100%","important"),ue.style.cssText=`
124
+ ${Wt?"border: none !important;":Ie?`border: ${dt} !important;`:""}
125
+ `,he.style.setProperty("width","100%","important"),he.style.setProperty("max-width","100%","important"),be.style.cssText=`
126
126
  display: flex !important;
127
127
  flex-direction: column !important;
128
128
  flex: 1 1 0% !important;
@@ -131,32 +131,32 @@ _Details: ${n.message}_`:o}var Ua=e=>({isError:!0,content:[{type:"text",text:e}]
131
131
  min-height: 0 !important;
132
132
  max-height: 100% !important;
133
133
  overflow: hidden !important;
134
- border-radius: ${Ze} !important;
135
- border: ${gt} !important;
136
- ${Rt&&!vt?`box-shadow: ${Ne} !important;`:""}
137
- ${vt?"background: transparent !important;":""}
138
- `,Y.style.cssText=`
134
+ border-radius: ${Xe} !important;
135
+ border: ${ft} !important;
136
+ ${Wt&&!Ct?`box-shadow: ${Oe} !important;`:""}
137
+ ${Ct?"background: transparent !important;":""}
138
+ `,we.style.cssText=`
139
139
  flex-shrink: 0 !important;
140
140
  border-top: none !important;
141
141
  padding: 8px 16px 12px 16px !important;
142
- ${vt?"background: transparent !important;":""}
143
- `}if(!v&&!i){let Tt="max-height: -moz-available !important; max-height: stretch !important;",nn=m?"":"padding-top: 1.25em !important;",qs=m?"":`z-index: ${o.launcher?.zIndex??Gt} !important;`;He.style.cssText+=Tt+nn+qs}bn()};Ss(),rr(e,o),as(e,o),ss(e,o),sa=()=>{Ss(),rr(e,o),as(e,o),ss(e,o),ys?e.style.setProperty("--persona-artifact-welded-outer-radius",ys):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",qu)}),Ve.push(()=>{oa!==null&&clearTimeout(oa)});let Rn=null,In=null;Ve.push(()=>{Rn?.(),Rn=null,In?.(),In=null}),aa&&Ve.push(()=>{aa?.disconnect(),aa=null}),Ve.push(()=>{da?.(),da=null,Rl(),bt&&(bt.remove(),bt=null),Ye?.element.style.removeProperty("width"),Ye?.element.style.removeProperty("maxWidth")}),le&&Ve.push(()=>{Me!==null&&(cancelAnimationFrame(Me),Me=null),Xe?.destroy(),Xe=null,We?.destroy(),We=null,Se=null});let _o=null,$u=()=>{_o&&(_o(),_o=null),o.colorScheme==="auto"&&(_o=Nr(()=>{rr(e,o)}))};$u(),Ve.push(()=>{_o&&(_o(),_o=null)}),Ve.push(l);let Ms=o.features?.streamAnimation;if(Ms?.type&&Ms.type!=="none"){let i=zr(Ms.type,Ms.plugins);i&&(Qi(i,e),Ve.push(()=>Ng(e)))}let Ts=sh(it),Uo=null,z,Il=i=>{if(!z)return;let m=i??z.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?oi(m):null;y?Ts.render(y,z,pe,m,o.suggestionChipsConfig,{agentPushed:!0}):m.some(v=>v.role==="user")?Ts.render([],z,pe,m):Ts.render(o.suggestionChips,z,pe,m,o.suggestionChipsConfig)},wn=!1,qo=Lg(),xr=new Map,Vo=new Map,so=new Map,Wl=0,Sy=Gn()!==null,sn=$i(),mn=0,io=null,gn=!1,Es=!1,lo=0,An=null,zo=null,Hl=!1,ks=!1,ca=null,pa=!0,Ls=!1,Ps=null,Rs=!1,$o=()=>{Rs=!0},Bl=null,My=4,Is=24,Ty=80,Dl=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ju=o.voiceRecognition?.autoResume??!1,qn=i=>{p.emit("voice:state",{active:Ke.active,source:i,timestamp:Date.now()})},Sn=()=>{E(i=>({...i,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Ey=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=pu(u.voiceState),m=!!i.active,y=Number(i.timestamp??0);Ke.manuallyDeactivated=!!i.manuallyDeactivated,m&&Date.now()-y<lw&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("restore"),z.isVoiceActive()&&Sr()}):Fs("restore"))},1e3)},ky=()=>z?Ph(z.getMessages()).filter(i=>!i.__skipPersist):[],Ws=null,Gu=(i,m)=>{typeof console<"u"&&console.error(i,m)},Fl=(i,m)=>{let y=()=>{try{let J=i();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(V=>{Gu(m,V)})}catch(J){return Gu(m,J),null}},v=Ws,L=v?v.then(()=>y()??void 0):y();if(!L)return;let I=L.finally(()=>{Ws===I&&(Ws=null)});Ws=I};function Ol(i){if(!d?.save)return;let y={messages:i?Ph(i):z?ky():[],metadata:u,artifacts:vn.artifacts,selectedArtifactId:vn.selectedId};Fl(()=>d.save(y),"[AgentWidget] Failed to persist state:")}let vr=null,Ku=()=>He.querySelector("#persona-scroll-container")||ae,ua=()=>{vr!==null&&(cancelAnimationFrame(vr),vr=null),gn=!1},Xu=()=>{io!==null&&(cancelAnimationFrame(io),io=null),Es=!1,ua()},Ly=()=>wn&&_l()&&(fn()!=="anchor-top"||Lu()),Nl=()=>{let i=Do()||"Jump to latest",m=Ly();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),lo>0?(Fo.textContent=String(lo),Fo.style.display="",kt.setAttribute("aria-label",`${i} (${lo} new)`)):(Fo.textContent="",Fo.style.display="none",kt.setAttribute("aria-label",m?`${i} (response streaming below)`:i))},Ju=()=>{lo!==0&&(lo=0,Nl())},_l=()=>no()?!sn.isFollowing():!Wo(ae,Is),ln=()=>{if(!gs()||$e){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==ue&&ue.appendChild(kt),gr();let m=Fn(ae)>0&&_l();m?Nl():Ju(),kt.style.display=m?"":"none"},fa=()=>{sn.pause()&&(Xu(),ln())},co=()=>{sn.resume(),Ju(),ln()},po=(i=!1)=>{no()&&sn.isFollowing()&&(!i&&!wn||(io!==null&&(cancelAnimationFrame(io),io=null),Es=!0,io=requestAnimationFrame(()=>{io=null,Es=!1,sn.isFollowing()&&Py(Ku(),i?220:140)})))},Qu=(i,m,y,v=()=>!0)=>{let L=i.scrollTop,I=m(),J=I-L;if(ua(),Math.abs(J)<1){gn=!0,i.scrollTop=I,mn=i.scrollTop,gn=!1;return}let V=performance.now();gn=!0;let X=fe=>1-Math.pow(1-fe,3),se=fe=>{if(!v()){ua();return}let re=m();re!==I&&(I=re,J=I-L);let xe=fe-V,ze=Math.min(xe/y,1),pt=X(ze),nt=L+J*pt;i.scrollTop=nt,mn=i.scrollTop,ze<1?vr=requestAnimationFrame(se):(i.scrollTop=I,mn=i.scrollTop,vr=null,gn=!1)};vr=requestAnimationFrame(se)},Py=(i,m=500)=>{let y=Fn(i)-i.scrollTop;if(Math.abs(y)<1){mn=i.scrollTop;return}if(Math.abs(y)>=Ty){ua(),gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1;return}Qu(i,()=>Fn(i),m,()=>sn.isFollowing())},Yu=()=>{let i=Ku();gn=!0,i.scrollTop=Fn(i),mn=i.scrollTop,gn=!1,ln()},Zu=i=>{let m=0,y=i;for(;y&&y!==ae;)m+=y.offsetTop,y=y.offsetParent;return m},Ry=()=>{let i=ae.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??ae.ownerDocument.getSelection()},Hs=()=>Hg(Ry(),ae),ef=()=>{if(yy()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let m=[...i].reverse().find(I=>I.role==="user");if(!m)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ae.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let L=Math.min(Math.max(0,Zu(v)-Eu()),Fn(ae));return gn=!0,ae.scrollTop=L,mn=ae.scrollTop,gn=!1,fn()==="follow"&&!Wo(ae,Is)&&sn.pause(),ln(),!0},tf=i=>{oo.style.height=`${Math.max(0,Math.round(i))}px`,An&&(An.spacerHeight=Math.max(0,i))},ma=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),ua(),An=null,oo.style.height="0px"},nf=i=>{zo!==null&&cancelAnimationFrame(zo),zo=requestAnimationFrame(()=>{zo=null;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ae.querySelector(`[data-message-id="${m}"]`);if(!y)return;let v=Zu(y),L=An?.spacerHeight??0,I=ae.scrollHeight-L,{targetScrollTop:J,spacerHeight:V}=Bg({anchorOffsetTop:v,topOffset:Eu(),viewportHeight:ae.clientHeight,contentHeight:I});An={initialSpacerHeight:V,contentHeightAtAnchor:I,spacerHeight:V},tf(V),Qu(ae,()=>J,220)})},Iy=()=>{if(no()){if(!sn.isFollowing()||Wo(ae,1))return;po(!wn);return}if(An&&An.initialSpacerHeight>0){let i=ae.scrollHeight-An.spacerHeight,m=Dg({initialSpacerHeight:An.initialSpacerHeight,contentHeightAtAnchor:An.contentHeightAtAnchor,currentContentHeight:i});m!==An.spacerHeight&&tf(m)}ln()},Wy=i=>{let m=fn();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(pa=!1,Ls=!0,Rs=!1,Ps=i,nf(i))},Hy=()=>{if(fn()==="anchor-top"){if(Ls){pa=!1;return}pa=!0,ma(),co(),po(!0)}},By=i=>{if(fn()!=="anchor-top"||!Ls||Rs||Hs())return;let m=ca===null;for(let y of i){if(!m){y.id===ca&&(m=!0);continue}if(Wg(y)){if(y.id===Ps)return;Ps=y.id,nf(y.id);return}}},Dy=i=>{let m=new Map;i.forEach(y=>{let v=Dl.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(p.emit("assistant:message",y),!ks&&(fn()!=="anchor-top"||Lu())&&_l()&&(lo+=1,Nl(),ln(),Ru(lo===1?"1 new message below.":`${lo} new messages below.`))),y.role==="assistant"&&v?.streaming&&y.streaming===!1&&p.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(v?y.approval.status!=="pending"&&p.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):p.emit("approval:requested",{approval:y.approval,message:y}))}),Dl.clear(),m.forEach((y,v)=>{Dl.set(v,y)})},Bs=(i,m)=>{let y=m==="user"?"user":"assistant",v=o.layout?.messages?.[y],L=v?.width??"content",I=v?.maxWidth??(L==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${m}`,`persona-message-width-${L}`),i.classList.toggle("persona-justify-end",m==="user"),i.setAttribute("data-message-role",m),i.setAttribute("data-message-width",L),i.style.setProperty("--persona-message-row-max-width",I)},jo=(i,m)=>{let y=document.createElement("div");return y.className="persona-flex",y.id=`wrapper-${i}`,y.setAttribute("data-wrapper-id",i),Bs(y,m),y},Fy=(i,m,y)=>{let v=document.createElement("div"),I=(()=>{let N=a.find(Te=>Te.renderLoadingIndicator);if(N?.renderLoadingIndicator)return N.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(N,Te)=>Te==null?!1:typeof Te=="string"?(N.textContent=Te,!0):(N.appendChild(Te),!0),V=new Set,X=new Map,se=new Set,fe=a.some(N=>N.renderAskUserQuestion),re=[],xe=[],ze=o.enableComponentStreaming!==!1,pt=o.approval!==!1,nt=[];if(m.forEach(N=>{V.add(N.id),X.set(N.id,N.role);let Te=fe&&Xn(N),Oe=pt&&N.variant==="approval"&&!!N.approval,Ce=!Te&&N.role==="assistant"&&!N.variant&&ze&&ps(N);!Oe&&so.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id)),!Ce&&Vo.has(N.id)&&(i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),Vo.delete(N.id));let Ct=Xn(N)?`:${N.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${N.agentMetadata?.askUserQuestionAnswers?Object.keys(N.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=kg(N,Wl)+Ct,Ft=Te||Oe||Ce?null:Pg(qo,N.id,ut);if(Ft){v.appendChild(Ft.cloneNode(!0)),Xn(N)&&N.toolCall?.id&&N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let ft=null,tn=a.find(Ne=>!!(N.variant==="reasoning"&&Ne.renderReasoning||N.variant==="tool"&&Ne.renderToolCall||!N.variant&&Ne.renderMessage)),Rt=o.layout?.messages;if(Xn(N)&&N.agentMetadata?.askUserQuestionAnswered===!0){xr.delete(N.id),i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime");return}if(Ba(N)&&o.features?.suggestReplies?.enabled!==!1)return;if(Xn(N)&&o.features?.askUserQuestion?.enabled!==!1){let Ne=a.find(qt=>typeof qt.renderAskUserQuestion=="function");if(Ne&&lt.current){let qt=xr.get(N.id),Vt=qt!==ut,vt=null;if(Vt){let{payload:Ze,complete:Ie}=Jn(N),yt=N.id,zt=()=>lt.current?.getMessages().find(bn=>bn.id===yt);vt=Ne.renderAskUserQuestion({message:N,payload:Ze,complete:Ie,resolve:bn=>{let Sa=zt();Sa&&lt.current?.resolveAskUserQuestion(Sa,bn)},dismiss:()=>{let bn=zt();bn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(bn),lt.current?.resolveAskUserQuestion(bn,"(dismissed)"))},config:o})}let dt=qt!=null;if(Vt&&vt===null&&!dt){N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}let gt=jo(N.id,N.role);gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),re.push({messageId:N.id,fingerprint:ut,bubble:vt});return}else{N.agentMetadata?.awaitingLocalTool===!0&&!N.agentMetadata?.askUserQuestionAnswered&&(se.add(N.toolCall.id),Wr(N,o,Pe.composerOverlay));return}}else if(Oe){let Ne=a.find(dt=>typeof dt.renderApproval=="function")??s,Vt=so.get(N.id)!==ut,vt=null;if(Vt&&Ne?.renderApproval){let dt=N.id,gt=(Ze,Ie)=>{let yt=lt.current?.getMessages().find(zt=>zt.id===dt);yt?.approval&&(yt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(yt.id,Ze):lt.current?.resolveApproval(yt.approval,Ze,Ie))};vt=Ne.renderApproval({message:N,defaultRenderer:()=>ll(N,o),config:o,approve:Ze=>gt("approved",Ze),deny:Ze=>gt("denied",Ze)})}if(Vt&&vt===null)i.querySelector(`#wrapper-${N.id}`)?.removeAttribute("data-preserve-runtime"),so.delete(N.id),ft=ll(N,o);else{let dt=jo(N.id,N.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),v.appendChild(dt),nt.push({messageId:N.id,fingerprint:ut,bubble:vt});return}}else if(tn)if(N.variant==="reasoning"&&N.reasoning&&tn.renderReasoning){if(!ge)return;ft=tn.renderReasoning({message:N,defaultRenderer:()=>Jp(N,o),config:o})}else if(N.variant==="tool"&&N.toolCall&&tn.renderToolCall){if(!ne)return;ft=tn.renderToolCall({message:N,defaultRenderer:()=>Yp(N,o),config:o})}else tn.renderMessage&&(ft=tn.renderMessage({message:N,defaultRenderer:()=>{let Ne=Gr(N,y,Rt,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o});return N.role!=="user"&&lu(Ne,N,o,z),Ne},config:o}));if(!ft&&Ce){let Ne=hl(N);if(Ne){let qt=Vo.get(N.id),Vt=qt!==ut,vt=o.wrapComponentDirectiveInBubble!==!1&&Ln.getOptions(Ne.component)?.bubbleChrome!==!1,dt=null;if(Vt){let gt=gl(Ne,{config:o,message:N,transform:y});if(gt&&Ne.component==="PersonaArtifactInline"){let Ze=gt.hasAttribute("data-artifact-inline")?gt:gt.querySelector("[data-artifact-inline]"),Ie=Ze?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ie):Ie,zt=Ie?i.querySelector(`#wrapper-${N.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Ze&&zt&&zt!==Ze&&wg(zt)&&(Ze===gt?gt=zt:Ze.replaceWith(zt))}if(gt)if(vt){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${N.id}`,Ze.setAttribute("data-message-id",N.id),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${N.id}`,Ze.setAttribute("data-message-id",N.id),Ze.setAttribute("data-persona-component-directive","true"),N.content&&N.content.trim()){let Ie=document.createElement("div");Ie.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ie.innerHTML=y({text:N.content,message:N,streaming:!!N.streaming,raw:N.rawContent}),Ze.appendChild(Ie)}Ze.appendChild(gt),dt=Ze}}if(dt||qt!=null){let gt=jo(N.id,N.role);gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),v.appendChild(gt),xe.push({messageId:N.id,fingerprint:ut,bubble:dt});return}}}if(!ft)if(N.variant==="reasoning"&&N.reasoning){if(!ge)return;ft=Jp(N,o)}else if(N.variant==="tool"&&N.toolCall){if(!ne)return;ft=Yp(N,o)}else if(N.variant==="approval"&&N.approval){if(o.approval===!1)return;ft=ll(N,o)}else{let Ne=o.layout?.messages;Ne?.renderUserMessage&&N.role==="user"?ft=Ne.renderUserMessage({message:N,config:o,streaming:!!N.streaming}):Ne?.renderAssistantMessage&&N.role==="assistant"?ft=Ne.renderAssistantMessage({message:N,config:o,streaming:!!N.streaming}):ft=Gr(N,y,Ne,o.messageActions,Je,{loadingIndicatorRenderer:I,widgetConfig:o}),N.role!=="user"&&ft&&lu(ft,N,o,z)}let Ee=jo(N.id,N.role);Ee.appendChild(ft),Rg(qo,N.id,ut,Ee),v.appendChild(Ee)}),Pe.composerOverlay&&Pe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Te=>{let Oe=Te.getAttribute("data-persona-ask-sheet-for");Oe&&!se.has(Oe)&&Co(Pe.composerOverlay,Oe)}),o.features?.toolCallDisplay?.grouped){let N=[],Te=[],Oe=o.features.toolCallDisplay.groupedMode==="summary";m.forEach(Ce=>{if(Ce.variant==="tool"&&Ce.toolCall&&ne){Te.push(Ce);return}Ce.variant==="reasoning"&&!ge||((Te.length>1||Oe&&Te.length>0)&&N.push(Te),Te=[])}),(Te.length>1||Oe&&Te.length>0)&&N.push(Te),N.forEach(Ce=>{let Ct=Ce.map(Ne=>Array.from(v.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===Ne.id)).filter(Ne=>!!Ne);if(Ct.length<(Oe?1:2))return;let ut=jo(`tool-group-${Ce[0].id}`,"assistant");ut.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 ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Ce[0].id}`;let tn=`Called ${Ce.length} ${Ce.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Ce,toolCalls:Ce.map(Ne=>Ne.toolCall).filter(Ne=>!!Ne),defaultSummary:tn,config:o});J(ft,Rt)||(ft.textContent=tn);let Ee=document.createElement("div");Ee.className="persona-tool-group-stack persona-flex persona-flex-col",Ee.id=`tool-group-stack-${Ce[0].id}`,Ee.setAttribute("data-persona-tool-group-stack","true"),Ft.appendChild(ft),Oe||Ft.appendChild(Ee),ut.appendChild(Ft),Ct[0].before(ut),Ct.forEach((Ne,qt)=>{if(Oe){Ne.remove();return}Ne.style.setProperty("--persona-message-row-max-width","100%");let Vt=document.createElement("div");Vt.className="persona-tool-group-item persona-relative",Vt.setAttribute("data-persona-tool-group-item","true"),qt<Ct.length-1&&Vt.setAttribute("data-persona-tool-group-connector","true"),Vt.appendChild(Ne),Ee.appendChild(Vt)})})}Ig(qo,V);let dn=m.some(N=>N.role==="assistant"&&N.streaming),St=m[m.length-1],Pt=St?.role==="assistant"&&!St.streaming&&St.variant!=="approval";if(wn&&m.some(N=>N.role==="user")&&!dn&&!Pt){let N={config:o,streaming:!0,location:"standalone",defaultRenderer:lr},Te=a.find(Ce=>Ce.renderLoadingIndicator),Oe=null;if(Te?.renderLoadingIndicator&&(Oe=Te.renderLoadingIndicator(N)),Oe===null&&o.loadingIndicator?.render&&(Oe=o.loadingIndicator.render(N)),Oe===null&&(Oe=lr()),Oe){let Ce=document.createElement("div"),Ct=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Ce.className=Ct?Kp("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ce.setAttribute("data-typing-indicator","true"),Ct&&(Ce.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Ce.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ce.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ce.appendChild(Oe);let Ft=jo("typing-indicator","assistant");Ft.appendChild(Ce),v.appendChild(Ft)}}if(!wn&&m.length>0){let N=m[m.length-1],Te={config:o,lastMessage:N,messageCount:m.length},Oe=a.find(Ct=>Ct.renderIdleIndicator),Ce=null;if(Oe?.renderIdleIndicator&&(Ce=Oe.renderIdleIndicator(Te)),Ce===null&&o.loadingIndicator?.renderIdle&&(Ce=o.loadingIndicator.renderIdle(Te)),Ce){let Ct=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Ct.className=ut?["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(" "),Ct.setAttribute("data-idle-indicator","true"),Ct.appendChild(Ce);let Ft=jo("idle-indicator","assistant");Ft.appendChild(Ct),v.appendChild(Ft)}}if(em(v),zi(i,v),od(i),re.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of re){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),xr.set(N,Te)))}if(xr.size>0)for(let N of xr.keys())V.has(N)||xr.delete(N);if(xe.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of xe){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),Vo.set(N,Te)))}if(Vo.size>0)for(let N of Vo.keys())V.has(N)||Vo.delete(N);if(nt.length>0)for(let{messageId:N,fingerprint:Te,bubble:Oe}of nt){let Ce=i.querySelector(`#wrapper-${N}`);Ce&&(Bs(Ce,X.get(N)??"assistant"),Oe!==null&&(Ce.replaceChildren(Oe),Ce.setAttribute("data-bubble-fp",Te),so.set(N,Te)))}if(so.size>0)for(let N of so.keys())V.has(N)||so.delete(N)},ga=(i,m,y)=>{Fy(i,m,y),Nu()},ha=null,Oy=()=>{if(ha)return;let i=y=>{let v=y.composedPath();v.includes(He)||et&&v.includes(et)||ct(!1,"user")};ha=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},of=()=>{if(!ha)return;(e.ownerDocument??document).removeEventListener("pointerdown",ha,!0),ha=null};Ve.push(()=>of());let ya=null,Ny=()=>{if(ya)return;let i=y=>{y.key==="Escape"&&(y.isComposing||ct(!1,"user"))};ya=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},rf=()=>{if(!ya)return;(e.ownerDocument??document).removeEventListener("keydown",ya,!0),ya=null};Ve.push(()=>rf());let ba=!1,af=new Set,_y=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},Cr=()=>{if(!O())return;let i=Pe.peekBanner,m=Pe.peekTextNode;if(!i||!m)return;if(Q){i.classList.remove("persona-pill-peek--visible");return}let y=z?.getMessages()??[],v;for(let St=y.length-1;St>=0;St--){let Pt=y[St];if(Pt.role==="assistant"&&Pt.content){v=Pt;break}}if(!v){i.classList.remove("persona-pill-peek--visible");return}let L=v.content,I=!!v.streaming,J=_y(),V=Ki(J),X=V.type!=="none"?zr(V.type,J?.plugins):null,se=X?.isAnimating?.(v)===!0,fe=X!==null&&(I||se);fe&&X&&!af.has(X.name)&&(Qi(X,e),af.add(X.name));let re=fe&&X?.containerClass?X.containerClass:null,xe=m.dataset.personaPeekStreamClass??null;xe&&xe!==re&&(m.classList.remove(xe),delete m.dataset.personaPeekStreamClass),re&&xe!==re&&(m.classList.add(re),m.dataset.personaPeekStreamClass=re),fe?(m.style.setProperty("--persona-stream-step",`${V.speed}ms`),m.style.setProperty("--persona-stream-duration",`${V.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let ze=fe?Xi(L,V.buffer,X,v,I):L;if(fe&&V.placeholder==="skeleton"&&I&&(!ze||!ze.trim())){let St=document.createElement("div"),Pt=Za();Pt.classList.add("persona-pill-peek__skeleton"),St.appendChild(Pt),zi(m,St)}else{let St=Math.max(0,ze.length-100),Pt=ze.length>100?ze.slice(-100):ze,N=Hn(Pt);if(!fe||!X){let Te=ze.length>100?`\u2026${Pt}`:Pt;m.textContent!==Te&&(m.textContent=Te)}else{let Te=N;(X.wrap==="char"||X.wrap==="word")&&(Te=Ya(N,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:St}));let Oe=document.createElement("div");if(Oe.innerHTML=Te,X.useCaret&&Pt.length>0){let Ce=Ji(),Ct=Oe.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=Ct[Ct.length-1];ut?.parentNode?ut.parentNode.insertBefore(Ce,ut.nextSibling):Oe.appendChild(Ce)}zi(m,Oe),X.onAfterRender?.({container:m,bubble:i,messageId:v.id,message:v,speed:V.speed,duration:V.duration})}}let dn=wn||ba;i.classList.toggle("persona-pill-peek--visible",dn)};if(O()){let i=Pe.peekBanner;if(i){let v=L=>{L.preventDefault(),L.stopPropagation(),ct(!0,"user")};i.addEventListener("pointerdown",v),Ve.push(()=>{i.removeEventListener("pointerdown",v)})}let m=()=>{ba||(ba=!0,Cr())},y=()=>{ba&&(ba=!1,Cr())};ce.addEventListener("pointerenter",m),ce.addEventListener("pointerleave",y),Ve.push(()=>{ce.removeEventListener("pointerenter",m),ce.removeEventListener("pointerleave",y)}),et&&(et.addEventListener("pointerenter",m),et.addEventListener("pointerleave",y),Ve.push(()=>{et.removeEventListener("pointerenter",m),et.removeEventListener("pointerleave",y)}))}let Uy=i=>{let m=o.launcher?.composerBar??{},y=m.expandedSize??"anchored",v=m.bottomOffset??"16px",L=m.collapsedMaxWidth,I=m.expandedMaxWidth??"880px",J=m.expandedTopOffset??"5vh",V=m.modalMaxWidth??"880px",X=m.modalMaxHeight??"min(90vh, 800px)",se="calc(100vw - 32px)",fe="var(--persona-pill-area-height, 80px)",re=He.style;if(re.left="",re.right="",re.top="",re.bottom="",re.transform="",re.width="",re.maxWidth="",re.height="",re.maxHeight="",et){let xe=et.style;xe.bottom=v,xe.width=L??""}if(i&&y!=="fullscreen"){if(y==="modal"){re.top="50%",re.left="50%",re.transform="translate(-50%, -50%)",re.bottom="auto",re.right="auto",re.width=V,re.maxWidth=se,re.maxHeight=X,re.height=X;return}re.left="50%",re.transform="translateX(-50%)",re.bottom=`calc(${v} + ${fe})`,re.top=J,re.width=I,re.maxWidth=se}},xa=()=>{if(!q())return;if(O()){let se=(o.launcher?.composerBar??{}).expandedSize??"anchored",fe=Q?"expanded":"collapsed";He.dataset.state=fe,He.dataset.expandedSize=se,et&&(et.dataset.state=fe,et.dataset.expandedSize=se),He.style.removeProperty("display"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Uy(Q),ue.style.display=Q?"flex":"none",Ss(),Q?(Oy(),Ny()):(of(),rf()),Cr();return}let i=Et(o),m=e.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,L=m.innerWidth<=y,I=v&&L&&C,J=rn(o).reveal;Q?(He.style.removeProperty("display"),He.style.display=i?"flex":"",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-95","persona-opacity-0"),ce.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Xt&&(Xt.style.display="none")):(i?i&&(J==="overlay"||J==="push")&&!I?(He.style.removeProperty("display"),He.style.display="flex",He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.setProperty("display","none","important"),He.classList.remove("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(He.style.display="",He.classList.add("persona-pointer-events-none","persona-opacity-0"),ce.classList.remove("persona-scale-100","persona-opacity-100"),ce.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=i?"none":"":Xt&&(Xt.style.display=i?"none":""))},ct=(i,m="user")=>{if(!q()||Q===i)return;let y=Q;Q=i,xa();let v=(()=>{let I=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,V=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,se=J.innerWidth<=X,fe=Et(o)&&V&&se,re=O()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return I||V&&se&&C||fe||re})();if(Q&&v){if(!Rn){let I=e.getRootNode(),J=I instanceof ShadowRoot?I.host:e.closest(".persona-host");J&&(Rn=Op(J,o.launcher?.zIndex??Gt))}In||(In=Np(e.ownerDocument))}else Q||(Rn?.(),Rn=null,In?.(),In=null);Q&&(wa(),ef()||(fn()==="follow"?po(!0):Yu()));let L={open:Q,source:m,timestamp:Date.now()};Q&&!y?p.emit("widget:opened",L):!Q&&y&&p.emit("widget:closed",L),p.emit("widget:state",{open:Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()})},Ul=i=>{rt(i?"stop":"send"),G&&(G.disabled=i),Ts.buttons.forEach(m=>{m.disabled=i}),Y.dataset.personaComposerStreaming=i?"true":"false",Y.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=i)})},ql=()=>{Ke.active||pe&&pe.focus()};p.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ql(),200)});let sf=()=>{x.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",H.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",pe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let i=ae.querySelector("[data-persona-intro-card]");if(i){let y=o.copy?.showWelcomeCard!==!1;i.style.display=y?"":"none",y?(ae.classList.remove("persona-gap-3"),ae.classList.add("persona-gap-6")):(ae.classList.remove("persona-gap-6"),ae.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(ve.textContent=o.copy?.sendButtonLabel??"Send"),pe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',pe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=u.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{E(m=>({...m,sessionId:i}))}});let Go=null,qy=()=>{Go==null&&(Go=setInterval(()=>{let i=Le.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(Go),Go=null;return}let m=Date.now();i.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=ai(m-v))})},100))},Vl=(i,m)=>{if(Object.is(i,m))return!0;if(i===null||m===null||typeof i!="object"||typeof m!="object")return!1;if(Array.isArray(i)||Array.isArray(m))return!Array.isArray(i)||!Array.isArray(m)||i.length!==m.length?!1:i.every((J,V)=>Vl(J,m[V]));let y=i,v=m,L=Object.keys(y),I=Object.keys(v);return L.length===I.length&&L.every(J=>Object.prototype.hasOwnProperty.call(v,J)&&Vl(y[J],v[J]))},lf=i=>{let{content:m,rawContent:y,llmContent:v,...L}=i;return L},zl=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!ps(i),Vy=(i,m,y)=>{if(i.length!==m.length)return!1;let v=i[y.index],L=m[y.index];return!v||!L||v.id!==y.id||L.id!==y.id?!1:(!Object.is(v.content,L.content)||!Object.is(v.rawContent,L.rawContent)||!Object.is(v.llmContent,L.llmContent))&&zl(v)&&zl(L)&&Vl(lf(v),lf(L))},df=null,wr=null,Ko=null,Vn=null,Ds=i=>{df=i;let m,y;wr=null;for(let L=i.length-1;L>=0;L-=1){let I=i[L];if(!m&&I.role==="user"&&(m=I),!y&&I.role==="assistant"&&(y=I),!wr&&zl(I)&&(wr={index:L,id:I.id}),m&&y&&wr)break}ga(Le,i,ie),Pp(Le,vn.artifacts,{suppressTransition:wn}),qy(),Il(i),po(!wn),Dy(i),i.length===0&&(ma(),pa=!0,Ls=!1,Ps=null,Rs=!1),!Hl||ks?(Hl=!0,ca=m?.id??null,Bl=y?.id??null):m&&m.id!==ca?(ca=m.id,Wy(m.id)):y&&y.id!==Bl&&Hy(),y&&(Bl=y.id),By(i);let v=Ke.lastUserMessageId;m&&m.id!==v&&(Ke.lastUserMessageId=m.id,p.emit("user:message",m)),Ke.lastUserMessageWasVoice=!!m?.viaVoice,Ol(i),Cr()},$l=()=>{Vn!==null&&(cancelAnimationFrame(Vn),Vn=null);let i=Ko;Ko=null,i&&Ds(i)},cf=()=>{Vn!==null&&cancelAnimationFrame(Vn),Vn=null,Ko=null},zy=i=>{let m=Ko??df;if(wn&&m&&wr&&Vy(m,i,wr)){Ko=i,Vn===null&&(Vn=requestAnimationFrame(()=>{Vn=null;let y=Ko;Ko=null,y&&Ds(y)}));return}if(i.length===0){cf(),Ds(i);return}$l(),Ds(i)};z=new Fr(o,{onMessagesChanged(i){zy(i)},onStatusChanged(i){let m=o.statusIndicator??{};Kt(U,(v=>v==="idle"?m.idleText??It.idle:v==="connecting"?m.connectingText??It.connecting:v==="connected"?m.connectedText??It.connected:v==="error"?m.errorText??It.error:v==="paused"?m.pausedText??It.paused:v==="resuming"?m.resumingText??It.resuming:It[v])(i),m,i)},onStreamingChanged(i){i||(z?.getMessages().length===0?cf():$l()),wn=i,Ul(i),z&&ga(Le,z.getMessages(),ie),i||po(!0),ln(),Ru(i?"Responding\u2026":"Response complete."),Cr()},onVoiceStatusChanged(i){if(p.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":zn(),Sr();break;case"processing":zn(),tb();break;case"speaking":zn(),nb();break;default:i==="idle"&&z.isBargeInActive()?(zn(),Sr(),G?.setAttribute("aria-label","End voice session")):(Ke.active=!1,zn(),qn("system"),Sn());break}},onArtifactsState(i){vn=i,i.artifacts.length===0&&(hr=!1),Pp(Le,i.artifacts,{suppressTransition:wn}),Un(),Ol()},onReconnect(i){let{executionId:m,lastEventId:y}=i.handle;i.phase==="paused"?p.emit("stream:paused",{executionId:m,after:y}):i.phase==="resuming"?p.emit("stream:resuming",{executionId:m,after:y,attempt:i.attempt??1}):p.emit("stream:resumed",{executionId:m,after:y})}}),lt.current=z,Ve.push(()=>z.cancel());let jl=null;if(z.onReadAloudChange((i,m)=>{Fu=i,Ou=m,Nu();let y=i??jl;i&&(jl=i);let v=y?z.getMessages().find(L=>L.id===y)??null:null;p.emit("message:read-aloud",{messageId:y,message:v,state:m,timestamp:Date.now()}),m==="idle"&&(jl=null)}),Hl=!0,o.voiceRecognition?.provider?.type==="runtype")try{z.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&z.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(We||o.onSSEEvent)&&z.setSSEEventCallback((i,m)=>{o.onSSEEvent?.(i,m),_e?.processEvent(i,m),We?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(m)})});let pf=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};g?g.then(i=>{if(i){if(i.metadata&&(u=pu(i.metadata),S.syncFromMetadata()),i.messages?.length){ks=!0;try{z.hydrateMessages(i.messages)}finally{ks=!1}}i.artifacts?.length&&z.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>pf()):pf();let uf=()=>{!O()||Q||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ct(!0,"auto")},$y=(i,m)=>i?m?{refs:[...i.refs,...m.refs],finalize:async()=>{let[y,v]=await Promise.allSettled([i.finalize(),m.finalize()]),L=[];return y.status==="fulfilled"?L.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),v.status==="fulfilled"?L.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),gw(L)}}:i:m,jy=()=>{let m=pe.getInlineMessageFields?.();return m&&m.contentSegments.some(v=>v.kind==="mention")?m.contentSegments:void 0},va=!1,Gy=async i=>{let m=pe.value.trim(),y=At?.hasAttachments()??!1,v=m?await(an?.takeInlineCommand(m)??Promise.resolve(null)):null;if(v?.kind==="action"){pe.value="",pe.style.height="auto",Ca(),an?.clear();return}let L=an?.collectForSubmit()??null,I=v?.kind==="server"?v.mentions:null,J=$y(L,I),V=v?.kind==="prompt"?v.sendText:m,X=!!L&&L.refs.length>0;if(!V&&!y&&!X&&!I)return;uf();let se;y&&(se=[],se.push(...At.getContentParts()),V&&se.push(Mo(V)));let fe=v?.kind==="prompt"?void 0:jy();pe.value="",pe.style.height="auto",Ca(),z.sendMessage(V,{contentParts:se,mentions:J??void 0,contentSegments:fe,viaVoice:i?.viaVoice}),y&&At.clearAttachments(),L&&an?.clear()},Gl=async i=>{if(!va){va=!0;try{await Gy(i)}finally{va=!1}}},ff=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),_e?.reset(),Xe?.update();return}va||Gl()},Ky=()=>o.features?.composerHistory!==!1,Kl={...Wp},Xl=!1,Ca=()=>{Kl={...Wp}},Xy=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Jy=i=>{if(!pe)return;Xl=!0,pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),Xl=!1;let m=pe.value.length;pe.setSelectionRange(m,m)},Qy=i=>{Xl||(i.isComposing||an?.handleInput(i.inputType??void 0),Ca())},Yy=i=>{if(pe&&!(!i.isComposing&&an?.handleKeydown(i))){if(Ky()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let m=pe.selectionStart===0&&pe.selectionEnd===0,y=Eg({direction:i.key==="ArrowUp"?"up":"down",history:Xy(),currentValue:pe.value,atStart:m,state:Kl});if(Kl=y.state,y.handled){i.preventDefault(),y.value!==void 0&&Jy(y.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(va){i.preventDefault();return}Ca(),i.preventDefault(),ve.click()}}},mf=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(ue)&&(z.cancel(),_e?.reset(),Xe?.update(),Ca(),i.preventDefault(),i.stopImmediatePropagation())},Zy=async i=>{if(o.attachments?.enabled!==!0||!At)return;let m=pw(i.clipboardData);m.length!==0&&(i.preventDefault(),await At.handleFiles(m))},hn=null,Wn=!1,Ar=null,xt=null,gf=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fs=(i="user")=>{if(Wn||z.isStreaming())return;let m=gf();if(!m)return;hn=new m;let v=(o.voiceRecognition??{}).pauseDuration??2e3;hn.continuous=!0,hn.interimResults=!0,hn.lang="en-US";let L=pe.value;hn.onresult=I=>{let J="",V="";for(let se=0;se<I.results.length;se++){let fe=I.results[se],re=fe[0].transcript;fe.isFinal?J+=re+" ":V=re}let X=L+J+V;pe.value=X,Ar&&clearTimeout(Ar),(J||V)&&(Ar=window.setTimeout(()=>{pe.value.trim()&&hn&&Wn&&(uo(),Gl({viaVoice:!0}))},v))},hn.onerror=I=>{I.error!=="no-speech"&&uo()},hn.onend=()=>{if(Wn){let I=pe.value.trim();I&&I!==L.trim()&&Gl({viaVoice:!0}),uo()}};try{if(hn.start(),Wn=!0,Ke.active=!0,i!=="system"&&(Ke.manuallyDeactivated=!1),qn(i),Sn(),G){let I=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:I.iconName??"mic",iconSize:parseFloat(I.iconSize??o.sendButton?.size??"40")||24};let J=I.recordingBackgroundColor,V=I.recordingIconColor,X=I.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=V??"var(--persona-voice-recording-indicator, #ffffff)",V){let se=G.querySelector("svg");se&&se.setAttribute("stroke",V)}X&&(G.style.borderColor=X),G.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(i="user")=>{if(Wn){if(Wn=!1,Ar&&(clearTimeout(Ar),Ar=null),hn){try{hn.stop()}catch{}hn=null}if(Ke.active=!1,qn(i),Sn(),G){if(G.classList.remove("persona-voice-recording"),xt){G.style.backgroundColor=xt.backgroundColor,G.style.color=xt.color,G.style.borderColor=xt.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",xt.color||"currentColor"),xt=null}G.setAttribute("aria-label","Start voice recognition")}}},eb=(i,m)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=i?.provider?.type==="runtype",L=i?.provider?.type==="custom";if(!(y||v||L))return null;let J=b("div","persona-send-button-wrapper"),V=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");V.type="button";let X=i?.tooltipText??"Start voice recognition";V.setAttribute("aria-label",X);let se=i?.iconName??"mic",fe=m?.size??"40px",re=i?.iconSize??fe,xe=parseFloat(re)||24,ze=i?.backgroundColor??m?.backgroundColor,pt=i?.iconColor??m?.textColor;V.style.width=re,V.style.height=re,V.style.minWidth=re,V.style.minHeight=re,V.style.fontSize="18px",V.style.lineHeight="1",pt?V.style.color=pt:V.style.color="var(--persona-text, #111827)";let dn=oe(se,xe,pt||"currentColor",1.5);dn?V.appendChild(dn):V.textContent="\u{1F3A4}",ze?V.style.backgroundColor=ze:V.style.backgroundColor="",i?.borderWidth&&(V.style.borderWidth=i.borderWidth,V.style.borderStyle="solid"),i?.borderColor&&(V.style.borderColor=i.borderColor),i?.paddingX&&(V.style.paddingLeft=i.paddingX,V.style.paddingRight=i.paddingX),i?.paddingY&&(V.style.paddingTop=i.paddingY,V.style.paddingBottom=i.paddingY),J.appendChild(V);let St=i?.showTooltip??!1;return Ut({anchor:V,trigger:J,text:()=>V.getAttribute("aria-label")??X,enabled:St}),{micButton:V,micButtonWrapper:J}},Jl=()=>{if(!G||xt)return;let i=o.voiceRecognition??{};xt={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Ql=(i,m)=>{if(!G)return;let y=G.querySelector("svg");y&&y.remove();let v=xt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),L=oe(i,v,m,1.5);L&&G.appendChild(L)},Os=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Sr=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=i.recordingBackgroundColor,y=i.recordingIconColor,v=i.recordingBorderColor;if(Os(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m??"var(--persona-voice-recording-bg, #ef4444)",G.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let L=G.querySelector("svg");L&&L.setAttribute("stroke",y)}v&&(G.style.borderColor=v),G.setAttribute("aria-label","Stop voice recognition")},tb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=i.processingIconName??"loader",v=i.processingIconColor??xt?.color??"",L=i.processingBackgroundColor??xt?.backgroundColor??"",I=i.processingBorderColor??xt?.borderColor??"";Os(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=L,G.style.borderColor=I;let J=v||"currentColor";G.style.color=J,Ql(y,J),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},nb=()=>{if(!G)return;Jl();let i=o.voiceRecognition??{},m=z.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",v=i.speakingIconName??y,L=i.speakingIconColor??(m==="barge-in"?i.recordingIconColor??xt?.color??"":xt?.color??""),I=i.speakingBackgroundColor??(m==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":xt?.backgroundColor??""),J=i.speakingBorderColor??(m==="barge-in"?i.recordingBorderColor??"":xt?.borderColor??"");Os(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=I,G.style.borderColor=J;let V=L||"currentColor";G.style.color=V,Ql(v,V);let X=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",X),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},zn=()=>{G&&(Os(),xt&&(G.style.backgroundColor=xt.backgroundColor??"",G.style.color=xt.color??"",G.style.borderColor=xt.borderColor??"",Ql(xt.iconName,xt.color||"currentColor"),xt=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ns=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=z.getVoiceStatus(),m=z.getVoiceInterruptionMode();if(m==="none"&&(i==="processing"||i==="speaking"))return;if(m==="cancel"&&(i==="processing"||i==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()});return}z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),Ke.manuallyDeactivated=!z.isVoiceActive(),Sn(),qn("user"),z.isVoiceActive()?Sr():zn()});return}if(Wn){let i=pe.value.trim();Ke.manuallyDeactivated=!0,Sn(),uo("user"),i&&(pe.value="",pe.style.height="auto",z.sendMessage(i))}else Ke.manuallyDeactivated=!1,Sn(),Fs("user")};Wu=Ns,G&&(G.addEventListener("click",Ns),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),zn()):uo("system"),G&&G.removeEventListener("click",Ns)}));let ob=p.on("assistant:complete",()=>{ju&&(Ke.active||Ke.manuallyDeactivated||ju==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("auto"),z.isVoiceActive()&&Sr()}):Fs("auto"))},600))});Ve.push(ob);let rb=p.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});Ve.push(rb);let hf=()=>{ct(!Q,"user")},Ot=null,Xt=null;if(C&&!O()){let{instance:i,element:m}=zp({config:o,plugins:a,onToggle:hf});Ot=i,i||(Xt=m)}Ot?e.appendChild(Ot.element):Xt&&e.appendChild(Xt),xa(),Il(),sf(),Ul(z.isStreaming()),ef()||(fn()==="follow"?po(!0):Yu()),Ey(),W&&(!C||O()?setTimeout(()=>ql(),0):Q&&setTimeout(()=>ql(),200));let wa=()=>{if(O()){gr(),xa();return}let i=Et(o),m=o.launcher?.sidebarMode??!1,y=i||m||(o.launcher?.fullHeight??!1),v=e.ownerDocument.defaultView??window,L=o.launcher?.mobileFullscreen??!0,I=o.launcher?.mobileBreakpoint??640,J=v.innerWidth<=I,V=L&&J&&C;try{if(V){sa(),ia=As();return}let X=!1;j&&(j=!1,sa(),X=!0);let se=As();if(!X&&se!==ia&&(sa(),X=!0),ia=se,X&&Pl(),!C&&!i){ce.style.height="",ce.style.width="";return}if(!m&&!i){let re=o?.launcher?.width??o?.launcherWidth??pn;ce.style.width=re,ce.style.maxWidth=re}if(ws(),!y){let fe=v.innerHeight,re=64,xe=o.launcher?.heightOffset??0,ze=Math.max(200,fe-re),pt=Math.min(640,ze),nt=Math.max(200,pt-xe);ce.style.height=`${nt}px`}}finally{if(gr(),xa(),Q&&C){let se=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),fe=o.launcher?.sidebarMode??!1,re=o.launcher?.mobileFullscreen??!0,xe=Et(o)&&re&&se,ze=fe||re&&se&&C||xe;if(ze&&!In){let pt=e.getRootNode(),nt=pt instanceof ShadowRoot?pt.host:e.closest(".persona-host");nt&&!Rn&&(Rn=Op(nt,o.launcher?.zIndex??Gt)),In=Np(e.ownerDocument)}else ze||(Rn?.(),Rn=null,In?.(),In=null)}}};wa();let yf=e.ownerDocument.defaultView??window;if(yf.addEventListener("resize",wa),Ve.push(()=>yf.removeEventListener("resize",wa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gr()});i.observe(Y),Ve.push(()=>i.disconnect())}mn=ae.scrollTop;let bf=Fn(ae),xf=()=>{let i=ae.scrollTop,m=Fn(ae),y=m<bf;if(bf=m,!no()){mn=i,ln();return}let{action:v,nextLastScrollTop:L}=ji({following:sn.isFollowing(),currentScrollTop:i,lastScrollTop:mn,nearBottom:Wo(ae,Is),userScrollThreshold:My,isAutoScrolling:gn||Es||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(mn=L,v==="resume"){Hs()||co();return}v==="pause"&&fa()};if(ae.addEventListener("scroll",xf,{passive:!0}),Ve.push(()=>ae.removeEventListener("scroll",xf)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Iy(),od(Le)});i.observe(Le),i.observe(ae),Ve.push(()=>i.disconnect())}let vf=()=>{no()&&sn.isFollowing()&&Hs()&&fa()},Cf=ae.ownerDocument;Cf.addEventListener("selectionchange",vf),Ve.push(()=>{Cf.removeEventListener("selectionchange",vf)});let ab=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),wf=i=>{ab.has(i.key)&&($o(),ku()&&no()&&sn.isFollowing()&&fa())},Af=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&($o(),ku()&&no()&&sn.isFollowing()&&fa())};ae.addEventListener("keydown",wf),ae.addEventListener("focusin",Af),Ve.push(()=>{ae.removeEventListener("keydown",wf),ae.removeEventListener("focusin",Af)});let Sf=i=>{if(i.deltaY!==0&&$o(),!no())return;let m=Gi({following:sn.isFollowing(),deltaY:i.deltaY,nearBottom:Wo(ae,Is),resumeWhenNearBottom:!0});m==="pause"?fa():m==="resume"&&!Hs()&&co()};ae.addEventListener("wheel",Sf,{passive:!0}),ae.addEventListener("touchmove",$o,{passive:!0}),ae.addEventListener("pointerdown",$o,{passive:!0}),Ve.push(()=>{ae.removeEventListener("touchmove",$o),ae.removeEventListener("pointerdown",$o)}),Ve.push(()=>ae.removeEventListener("wheel",Sf)),kt.addEventListener("click",()=>{ma(),ae.scrollTop=ae.scrollHeight,mn=ae.scrollTop,co(),po(!0),ln()}),Ve.push(()=>kt.remove()),Ve.push(()=>{Xu(),ma()});let Mf=()=>{R&&(Uo&&(R.removeEventListener("click",Uo),Uo=null),q()?(R.style.display="",Uo=()=>{ct(!1,"user")},R.addEventListener("click",Uo)):R.style.display="none")};Mf(),(()=>{let{clearChatButton:i}=Pe;i&&i.addEventListener("click",()=>{z.clearMessages(),qo.clear(),co(),Co(Pe.composerOverlay);try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),d?.clear&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()})})(),P&&P.addEventListener("submit",ff);let Tf=[["keydown",Yy],["input",Qy],["paste",Zy],["focus",vy]],Ef=i=>{if(i)for(let[m,y]of Tf)i.addEventListener(m,y)},kf=i=>{if(i)for(let[m,y]of Tf)i.removeEventListener(m,y)};Ef(pe),an?.onComposerSwap((i,m)=>{kf(m),pe=i,Ef(i)});let Lf=e.ownerDocument??document;Lf.addEventListener("keydown",mf,!0);let Pf="persona-attachment-drop-active",Aa=0,Yl=()=>{Aa=0,ue.classList.remove(Pf)},Mr=()=>o.attachments?.enabled===!0&&At!==null,Rf=i=>{!xl(i.dataTransfer)||!Mr()||(Aa++,Aa===1&&ue.classList.add(Pf))},If=i=>{!xl(i.dataTransfer)||!Mr()||(Aa--,Aa<=0&&Yl())},Wf=i=>{!xl(i.dataTransfer)||!Mr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},Hf=i=>{if(!xl(i.dataTransfer)||!Mr())return;i.preventDefault(),i.stopPropagation(),Yl();let m=Array.from(i.dataTransfer.files??[]);m.length!==0&&At.handleFiles(m)},fo=!0;ue.addEventListener("dragenter",Rf,fo),ue.addEventListener("dragleave",If,fo),e.addEventListener("dragover",Wf,fo),e.addEventListener("drop",Hf,fo);let _s=e.ownerDocument,Bf=i=>{Mr()&&i.preventDefault()},Df=i=>{Mr()&&i.preventDefault()};_s.addEventListener("dragover",Bf),_s.addEventListener("drop",Df),Ve.push(()=>{P&&P.removeEventListener("submit",ff),kf(pe),Lf.removeEventListener("keydown",mf,!0),an?.destroy()}),Ve.push(()=>{ue.removeEventListener("dragenter",Rf,fo),ue.removeEventListener("dragleave",If,fo),e.removeEventListener("dragover",Wf,fo),e.removeEventListener("drop",Hf,fo),_s.removeEventListener("dragover",Bf),_s.removeEventListener("drop",Df),Yl()}),Ve.push(()=>{z.cancel()}),Ot?Ve.push(()=>{Ot?.destroy()}):Xt&&Ve.push(()=>{Xt?.remove()});let Lt={update(i){let m=o.toolCall,y=o.messageActions,v=o.layout?.messages,L=o.colorScheme,I=o.loadingIndicator,J=o.iterationDisplay,V=o.features?.showReasoning,X=o.features?.showToolCalls,se=o.features?.toolCallDisplay,fe=o.features?.reasoningDisplay,re=o.features?.streamAnimation?.type;o=ul({...o,features:r},i),r=o.features,o=is(o),Ss(),rr(e,o),as(e,o),ss(e,o),Un(),o.colorScheme!==L&&$u();let xe=ls.getForInstance(o.plugins);a.length=0,a.push(...xe),C=o.launcher?.enabled??!0,T=o.launcher?.autoExpand??!1,ge=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,Z=o.features?.scrollToBottom??{};let ze=fn();me=o.features?.scrollBehavior??{},ze!==fn()&&(ma(),co()),Iu(),ln();let pt=le;if(le=o.features?.showEventStreamToggle??!1,le&&!pt){if(We||(Se=new os(we),We=new ns(mt,Se),_e=_e??new rs,Se.open().then(()=>We?.restore()).catch(()=>{}),z.setSSEEventCallback((te,Ge)=>{o.onSSEEvent?.(te,Ge),_e?.processEvent(te,Ge),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!tt&&$){let te=o.features?.eventStream?.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te?.toggleButton?" "+te.toggleButton:"");tt=b("button",Ge),tt.style.width="28px",tt.style.height="28px",tt.style.color=Yt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let ht=oe("activity","18px","currentColor",1.5);ht&&tt.appendChild(ht);let ot=Pe.clearChatButtonWrapper,at=Pe.closeButtonWrapper,$t=ot||at;$t&&$t.parentNode===$?$.insertBefore(tt,$t):$.appendChild(tt),tt.addEventListener("click",()=>{$e?ra():Tl()})}}else!le&&pt&&(ra(),tt&&(tt.remove(),tt=null),We?.clear(),Se?.destroy(),We=null,Se=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Xt&&(Xt.remove(),Xt=null),o.launcher?.enabled!==!1&&!Ot&&!Xt){let{instance:te,element:Ge}=zp({config:o,plugins:a,onToggle:hf});Ot=te,te||(Xt=Ge),e.appendChild(Ge)}Ot&&Ot.update(o),K&&o.launcher?.title!==void 0&&(K.textContent=o.launcher.title),_&&o.launcher?.subtitle!==void 0&&(_.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==F&&$){let te=nt?$r(o,nt,{showClose:q(),onClose:()=>ct(!1,"user")}):eo({config:o,showClose:q(),onClose:()=>ct(!1,"user")});wt.replaceHeader(te),$=wt.header.element,B=wt.header.iconHolder,K=wt.header.headerTitle,_=wt.header.headerSubtitle,R=wt.header.closeButton,F=nt?.layout}else if(nt){if(B&&(B.style.display=nt.showIcon===!1?"none":""),K&&(K.style.display=nt.showTitle===!1?"none":""),_&&(_.style.display=nt.showSubtitle===!1?"none":""),R){let te=q()&&nt.showCloseButton!==!1;R.style.display=te?"":"none"}if(Pe.clearChatButtonWrapper){let te=nt.showClearChat;if(te!==void 0){Pe.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Ge}=Pe;Ge&&!Ge.classList.contains("persona-absolute")&&(te?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let St=o.layout?.showHeader!==!1;$&&($.style.display=St?"":"none");let Pt=o.layout?.showFooter!==!1;Y&&(Y.style.display=Pt?"":"none"),gr(),ln(),C!==D?C?ct(T,"auto"):(Q=!0,xa()):T!==w&&ct(T,"auto"),w=T,D=C,wa(),Mf();let Oe=JSON.stringify(o.toolCall)!==JSON.stringify(m),Ce=JSON.stringify(o.messageActions)!==JSON.stringify(y),Ct=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),ut=o.loadingIndicator?.render!==I?.render||o.loadingIndicator?.renderIdle!==I?.renderIdle||o.loadingIndicator?.showBubble!==I?.showBubble,Ft=o.iterationDisplay!==J,ft=(o.features?.showReasoning??!0)!==(V??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(se)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(fe);(Oe||Ce||Ct||ut||Ft||ft)&&z&&(Wl++,ga(Le,z.getMessages(),ie));let Rt=o.features?.streamAnimation?.type;if(Rt!==re&&Rt&&Rt!=="none"){let te=zr(Rt,o.features?.streamAnimation?.plugins);te&&Qi(te,e)}let Ee=o.launcher??{},Ne=Ee.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Vt=Ne||qt===!1,vt=Ee.headerIconName,dt=Ee.headerIconSize??"48px";if(B){let te=ue.querySelector(".persona-border-b-persona-divider"),Ge=te?.querySelector(".persona-flex-col");if(Vt)B.style.display="none",te&&Ge&&!te.contains(Ge)&&te.insertBefore(Ge,te.firstChild);else{if(B.style.display="",B.style.height=dt,B.style.width=dt,te&&Ge&&(te.contains(B)?B.nextSibling!==Ge&&(B.remove(),te.insertBefore(B,Ge)):te.insertBefore(B,Ge)),vt){let ot=parseFloat(dt)||24,at=oe(vt,ot*.6,"currentColor",1);at?B.replaceChildren(at):B.textContent=Ee.agentIconText??"\u{1F4AC}"}else if(Ee.iconUrl){let ot=B.querySelector("img");if(ot)ot.src=Ee.iconUrl,ot.style.height=dt,ot.style.width=dt;else{let at=document.createElement("img");at.src=Ee.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=dt,at.style.width=dt,B.replaceChildren(at)}}else{let ot=B.querySelector("svg"),at=B.querySelector("img");(ot||at)&&B.replaceChildren(),B.textContent=Ee.agentIconText??"\u{1F4AC}"}let ht=B.querySelector("img");ht&&(ht.style.height=dt,ht.style.width=dt)}}let gt=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(K&&(K.style.display=gt===!1?"none":""),_&&(_.style.display=Ze===!1?"none":""),R){let te=q()&&o.layout?.header?.showCloseButton!==!1;R.style.display=te?"":"none";let Ge=Ee.closeButtonSize??"32px",ht=Ee.closeButtonPlacement??"inline";R.style.height=Ge,R.style.width=Ge;let{closeButtonWrapper:ot}=Pe,at=ht==="top-right",$t=ot?.classList.contains("persona-absolute");if(ot&&at!==$t)if(ot.remove(),at)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ot);else{let go=Ee.clearChat?.placement??"inline",Ta=Ee.clearChat?.enabled??!0;ot.className=Ta&&go==="inline"?"":"persona-ml-auto";let Ff=ue.querySelector(".persona-border-b-persona-divider");Ff&&Ff.appendChild(ot)}if(R.style.color=Ee.closeButtonColor||Yt.actionIconColor,Ee.closeButtonBackgroundColor?(R.style.backgroundColor=Ee.closeButtonBackgroundColor,R.classList.remove("hover:persona-bg-gray-100")):(R.style.backgroundColor="",R.classList.add("hover:persona-bg-gray-100")),Ee.closeButtonBorderWidth||Ee.closeButtonBorderColor){let go=Ee.closeButtonBorderWidth||"0px",Ta=Ee.closeButtonBorderColor||"transparent";R.style.border=`${go} solid ${Ta}`,R.classList.remove("persona-border-none")}else R.style.border="",R.classList.add("persona-border-none");Ee.closeButtonBorderRadius?(R.style.borderRadius=Ee.closeButtonBorderRadius,R.classList.remove("persona-rounded-full")):(R.style.borderRadius="",R.classList.add("persona-rounded-full")),Ee.closeButtonPaddingX?(R.style.paddingLeft=Ee.closeButtonPaddingX,R.style.paddingRight=Ee.closeButtonPaddingX):(R.style.paddingLeft="",R.style.paddingRight=""),Ee.closeButtonPaddingY?(R.style.paddingTop=Ee.closeButtonPaddingY,R.style.paddingBottom=Ee.closeButtonPaddingY):(R.style.paddingTop="",R.style.paddingBottom="");let cn=Ee.closeButtonIconName??"x",Mn=Ee.closeButtonIconText??"\xD7";R.innerHTML="";let Nt=oe(cn,"28px","currentColor",1);Nt?(Nt.style.display="block",R.appendChild(Nt)):R.textContent=Mn;let jt=Ee.closeButtonTooltipText??"Close chat",jn=Ee.closeButtonShowTooltip??!0;R.setAttribute("aria-label",jt),ot&&Ut({anchor:R,trigger:ot,text:()=>R?.getAttribute("aria-label")??jt,enabled:jn})}let{clearChatButton:Ie,clearChatButtonWrapper:yt}=Pe;if(Ie){let te=Ee.clearChat??{},Ge=te.enabled??!0,ht=o.layout?.header?.showClearChat,ot=ht!==void 0?ht:Ge,at=te.placement??"inline";if(yt){yt.style.display=ot?"":"none";let{closeButtonWrapper:$t}=Pe;!O()&&$t&&!$t.classList.contains("persona-absolute")&&(ot?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let cn=at==="top-right",Mn=yt.classList.contains("persona-absolute");if(!O()&&cn!==Mn&&ot){if(yt.remove(),cn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",ue.style.position="relative",ue.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let jt=ue.querySelector(".persona-border-b-persona-divider"),jn=Pe.closeButtonWrapper;jt&&jn&&jn.parentElement===jt?jt.insertBefore(yt,jn):jt&&jt.appendChild(yt)}let Nt=Pe.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(cn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(ot){if(!O()){let go=te.size??"32px";Ie.style.height=go,Ie.style.width=go}let $t=te.iconName??"refresh-cw",cn=te.iconColor??"";Ie.style.color=cn||Yt.actionIconColor,Ie.innerHTML="";let Mn=O()?"14px":"20px",Nt=oe($t,Mn,"currentColor",1);if(Nt&&(Nt.style.display="block",Ie.appendChild(Nt)),te.backgroundColor?(Ie.style.backgroundColor=te.backgroundColor,Ie.classList.remove("hover:persona-bg-gray-100")):(Ie.style.backgroundColor="",Ie.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let go=te.borderWidth||"0px",Ta=te.borderColor||"transparent";Ie.style.border=`${go} solid ${Ta}`,Ie.classList.remove("persona-border-none")}else Ie.style.border="",Ie.classList.add("persona-border-none");te.borderRadius?(Ie.style.borderRadius=te.borderRadius,Ie.classList.remove("persona-rounded-full")):(Ie.style.borderRadius="",Ie.classList.add("persona-rounded-full")),te.paddingX?(Ie.style.paddingLeft=te.paddingX,Ie.style.paddingRight=te.paddingX):(Ie.style.paddingLeft="",Ie.style.paddingRight=""),te.paddingY?(Ie.style.paddingTop=te.paddingY,Ie.style.paddingBottom=te.paddingY):(Ie.style.paddingTop="",Ie.style.paddingBottom="");let jt=te.tooltipText??"Clear chat",jn=te.showTooltip??!0;Ie.setAttribute("aria-label",jt),yt&&Ut({anchor:Ie,trigger:yt,text:()=>Ie?.getAttribute("aria-label")??jt,enabled:jn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[ds],bn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mr.message,mr.messageAndClick];S=cs({parsers:zt,handlers:bn,getSessionMetadata:A,updateSessionMetadata:E,emit:p.emit,documentRef:typeof document<"u"?document:null}),ie=Rh(o,S,De),z.updateConfig(o),ga(Le,z.getMessages(),ie),Il(),sf(),Ul(z.isStreaming());let Sa=o.voiceRecognition?.enabled===!0,Us=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Tt=o.voiceRecognition?.provider?.type==="runtype";if(Sa&&(Us||Tt))if(!G||!Ue){let te=eb(o.voiceRecognition,o.sendButton);te&&(G=te.micButton,Ue=te.micButtonWrapper,Re.insertBefore(Ue,ee),G.addEventListener("click",Ns),G.disabled=z.isStreaming())}else{let te=o.voiceRecognition??{},Ge=o.sendButton??{},ht=te.iconName??"mic",ot=Ge.size??"40px",at=te.iconSize??ot,$t=parseFloat(at)||24;G.style.width=at,G.style.height=at,G.style.minWidth=at,G.style.minHeight=at;let cn=te.iconColor??Ge.textColor;G.innerHTML="";let Mn=oe(ht,$t,cn||"currentColor",1.5);Mn?G.appendChild(Mn):G.textContent="\u{1F3A4}";let Nt=te.backgroundColor??Ge.backgroundColor;Nt?G.style.backgroundColor=Nt:G.style.backgroundColor="",cn?G.style.color=cn:G.style.color="var(--persona-text, #111827)",te.borderWidth?(G.style.borderWidth=te.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),te.borderColor?G.style.borderColor=te.borderColor:G.style.borderColor="",te.paddingX?(G.style.paddingLeft=te.paddingX,G.style.paddingRight=te.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),te.paddingY?(G.style.paddingTop=te.paddingY,G.style.paddingBottom=te.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let jt=te.tooltipText??"Start voice recognition",jn=te.showTooltip??!1;G.setAttribute("aria-label",jt),Ue&&Ut({anchor:G,trigger:Ue,text:()=>G?.getAttribute("aria-label")??jt,enabled:jn}),Ue.style.display="",G.disabled=z.isStreaming()}else G&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():Wn&&uo());if(o.attachments?.enabled===!0){if(!qe||!he){let te=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Ht||(Ht=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ht.style.display="none",P.insertBefore(Ht,pe)),Fe||(Fe=document.createElement("input"),Fe.type="file",Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1,Fe.style.display="none",Fe.setAttribute("aria-label","Attach files"),P.insertBefore(Fe,pe)),qe=b("div","persona-send-button-wrapper"),he=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),he.type="button",he.setAttribute("aria-label",te.buttonTooltipText??"Attach file");let ot=te.buttonIconName??"paperclip",at=ht,$t=parseFloat(at)||40,cn=Math.round($t*.6);he.style.width=at,he.style.height=at,he.style.minWidth=at,he.style.minHeight=at,he.style.fontSize="18px",he.style.lineHeight="1";let Mn=oe(ot,cn,"currentColor",1.5);Mn?he.appendChild(Mn):he.textContent="\u{1F4CE}",he.addEventListener("click",jt=>{jt.preventDefault(),Fe?.click()}),qe.appendChild(he);let Nt=te.buttonTooltipText??"Attach file";Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Nt}),Qe?Qe.append(qe):P.appendChild(qe),!At&&Fe&&Ht&&(At=or.fromConfig(te),At.setPreviewsContainer(Ht),Fe.addEventListener("change",async()=>{At&&Fe?.files&&(await At.handleFileSelect(Fe.files),Fe.value="")}))}else{qe.style.display="";let te=o.attachments??{};Fe&&(Fe.accept=(te.allowedTypes??Yn).join(","),Fe.multiple=(te.maxFiles??4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Ih(o.attachments?.dropOverlay)),he){let te=o.attachments??{},Ge=te.buttonTooltipText??"Attach file";he.setAttribute("aria-label",Ge),he.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,ot=oe(te.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);ot?he.appendChild(ot):he.textContent="\u{1F4CE}",qe&&Ut({anchor:he,trigger:qe,text:()=>he?.getAttribute("aria-label")??Ge})}}else qe&&(qe.style.display="none"),At&&At.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Bt=o.sendButton??{},Ma=Bt.useIcon??!1,Vs=Bt.iconText??"\u2191",Tr=Bt.iconName,zs=Bt.tooltipText??"Send message",Zl=Bt.showTooltip??!1,Xo=Bt.size??"40px",$n=Bt.backgroundColor,Jo=Bt.textColor;if(Ma){if(ve.style.width=Xo,ve.style.height=Xo,ve.style.minWidth=Xo,ve.style.minHeight=Xo,ve.style.fontSize="18px",ve.style.lineHeight="1",Jo?ve.style.color=Jo:ve.style.color="var(--persona-button-primary-fg, #ffffff)",!z.isStreaming())if(ve.innerHTML="",Tr){let te=parseFloat(Xo)||24,Ge=Jo?.trim()||"currentColor",ht=oe(Tr,te,Ge,2);ht?ve.appendChild(ht):ve.textContent=Vs}else ve.textContent=Vs;ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-primary")):(ve.style.backgroundColor="",ve.classList.add("persona-bg-persona-primary"))}else ve.textContent=o.copy?.sendButtonLabel??"Send",ve.style.width="",ve.style.height="",ve.style.minWidth="",ve.style.minHeight="",ve.style.fontSize="",ve.style.lineHeight="",ve.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",$n?(ve.style.backgroundColor=$n,ve.classList.remove("persona-bg-persona-accent")):ve.classList.add("persona-bg-persona-accent"),Jo?ve.style.color=Jo:ve.classList.add("persona-text-white");Bt.borderWidth?(ve.style.borderWidth=Bt.borderWidth,ve.style.borderStyle="solid"):(ve.style.borderWidth="",ve.style.borderStyle=""),Bt.borderColor?ve.style.borderColor=Bt.borderColor:ve.style.borderColor="",Bt.paddingX?(ve.style.paddingLeft=Bt.paddingX,ve.style.paddingRight=Bt.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),Bt.paddingY?(ve.style.paddingTop=Bt.paddingY,ve.style.paddingBottom=Bt.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom=""),z.isStreaming()||ve.setAttribute("aria-label",zs),ee&&Ut({anchor:ve,trigger:ee,text:()=>ve.getAttribute("aria-label")??zs,enabled:Zl});let $s=o.layout?.contentMaxWidth??(O()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);$s?(Le.style.maxWidth=$s,Le.style.marginLeft="auto",Le.style.marginRight="auto",Le.style.width="100%",P&&(P.style.maxWidth=$s,P.style.marginLeft="auto",P.style.marginRight="auto"),it&&(it.style.maxWidth=$s,it.style.marginLeft="auto",it.style.marginRight="auto")):(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight="",Le.style.width="",P&&(P.style.maxWidth="",P.style.marginLeft="",P.style.marginRight=""),it&&(it.style.maxWidth="",it.style.marginLeft="",it.style.marginRight=""));let mo=o.statusIndicator??{},sb=mo.visible??!0;if(U.style.display=sb?"":"none",z){let te=z.getStatus();Kt(U,(ht=>ht==="idle"?mo.idleText??It.idle:ht==="connecting"?mo.connectingText??It.connecting:ht==="connected"?mo.connectedText??It.connected:ht==="error"?mo.errorText??It.error:It[ht])(te),mo,te)}U.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ib=mo.align==="left"?"persona-text-left":mo.align==="center"?"persona-text-center":"persona-text-right";U.classList.add(ib)},open(){q()&&ct(!0,"api")},close(){q()&&ct(!1,"api")},toggle(){q()&&ct(!Q,"api")},reconnect(){z.reconnectNow()},clearChat(){_n=!1,z.clearMessages(),qo.clear(),co();try{localStorage.removeItem(ea),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ea}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ea)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 i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),d?.clear&&Fl(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),u={},S.syncFromMetadata(),We?.clear(),_e?.reset(),Xe?.update()},setMessage(i){return!pe||z.isStreaming()?!1:(!Q&&q()&&ct(!0,"system"),pe.value=i,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let m=i?.trim()||pe.value.trim();return m?(!Q&&q()&&ct(!0,"system"),pe.value="",pe.style.height="auto",z.sendMessage(m),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),z.toggleVoice().then(()=>{Ke.active=z.isVoiceActive(),qn("user"),z.isVoiceActive()&&Sr()})),!0):Wn?!0:gf()?(!Q&&q()&&ct(!0,"system"),Ke.manuallyDeactivated=!1,Sn(),Fs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{Ke.active=!1,Ke.manuallyDeactivated=!0,Sn(),qn("user"),zn()}),!0):!1:Wn?(Ke.manuallyDeactivated=!0,Sn(),uo("user"),!0):!1},injectMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!Q&&q()&&ct(!0,"system");let m=z.injectAssistantMessage(i);return de&&(de=!1,be&&(clearTimeout(be),be=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),m},injectUserMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!Q&&q()&&ct(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!Q&&q()&&ct(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!Q&&q()&&ct(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!Q&&q()&&ct(!0,"system"),z.injectTestEvent(i)},async connectStream(i,m){return z.connectStream(i,m)},__pushEventStreamEvent(i){We&&(_e?.processEvent(i.type,i.payload),We.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!le||!We||Tl()},hideEventStream(){$e&&ra()},isEventStreamVisible(){return $e},showArtifacts(){Zt(o)&&(_n=!1,hr=!0,Un(),Ye?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(_n=!0,Un())},upsertArtifact(i){return Zt(o)?(Bn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(_n=!1,hr=!0),z.upsertArtifact(i)):null},selectArtifact(i){Zt(o)&&z.selectArtifact(i)},clearArtifacts(){Zt(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return C&&!Q&&!O()||!pe?!1:(pe.focus(),!0)},async resolveApproval(i,m,y){let L=z.getMessages().find(I=>I.variant==="approval"&&I.approval?.id===i);if(!L?.approval)throw new Error(`Approval not found: ${i}`);if(L.approval.toolType==="webmcp"){z.resolveWebMcpApproval(L.id,m);return}return z.resolveApproval(L.approval,m,y)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(i){E(i)},on(i,m){return p.on(i,m)},off(i,m){p.off(i,m)},isOpen(){return q()&&Q},isVoiceActive(){return Ke.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:q()&&Q,launcherEnabled:C,voiceActive:Ke.active,streaming:z.isStreaming()}},showCSATFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=yl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!Q&&q()&&ct(!0,"system");let m=Le.querySelector(".persona-feedback-container");m&&m.remove();let y=bl({onSubmit:async(v,L)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(v,L),i?.onSubmit?.(v,L)},onDismiss:i?.onDismiss,...i});Le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,m){return z.submitCSATFeedback(i,m)},async submitNPSFeedback(i,m){return z.submitNPSFeedback(i,m)},destroy(){$l(),Go!=null&&(clearInterval(Go),Go=null),Ve.forEach(i=>i()),He.remove(),et?.remove(),Ot?.destroy(),Xt?.remove(),Uo&&R.removeEventListener("click",Uo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,m={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:y=>y?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ve.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ve.push(()=>{window.removeEventListener("persona:focusInput",m)}),le){let V=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.showEventStream()},X=se=>{let fe=se.detail;(!fe?.instanceId||fe.instanceId===i)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",X),Ve.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",X)})}let y=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.showArtifacts()},v=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.hideArtifacts()},L=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||X?.artifact&&Lt.upsertArtifact(X.artifact)},I=V=>{let X=V.detail;X?.instanceId&&X.instanceId!==i||typeof X?.id=="string"&&Lt.selectArtifact(X.id)},J=V=>{let X=V.detail;(!X?.instanceId||X.instanceId===i)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",J),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",J)})}let yn=uw(o.persistState);if(yn&&q()){let i=fw(yn.storage),m=`${yn.keyPrefix}widget-open`,y=`${yn.keyPrefix}widget-voice`,v=`${yn.keyPrefix}widget-voice-mode`;if(i){let L=yn.persist?.openState&&i.getItem(m)==="true",I=yn.persist?.voiceState&&i.getItem(y)==="true",J=yn.persist?.voiceState&&i.getItem(v)==="true";if(L&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(I||J)Lt.startVoiceRecognition();else if(yn.persist?.focusInput){let V=e.querySelector("textarea");V&&V.focus()}},100)},0),yn.persist?.openState&&(p.on("widget:opened",()=>{i.setItem(m,"true")}),p.on("widget:closed",()=>{i.setItem(m,"false")})),yn.persist?.voiceState&&(p.on("voice:state",V=>{i.setItem(y,V.active?"true":"false")}),p.on("user:message",V=>{i.setItem(v,V.viaVoice?"true":"false")})),yn.clearOnChatClear){let V=()=>{i.removeItem(m),i.removeItem(y),i.removeItem(v)},X=()=>V();window.addEventListener("persona:clear-chat",X),Ve.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(f&&q()&&setTimeout(()=>{Lt.open()},0),Cr(),!Sy){let i=kr(()=>{z&&(Wl++,qo.clear(),ga(Le,z.getMessages(),ie))});Ve.push(i)}return Lt};var Wh=(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},hw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},yw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},bw=(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 a=o.offsetHeight>0;o.remove(),!(!r||a)&&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.")},Hh=(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"},gu=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=""},Bh=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",gu(e)},uu=e=>{e.style.transition=""},fu=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=""},mu=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Cl=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},xw=(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))},vw=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},Cw=e=>{let t=ko(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:Qt(t,r)??r;return{inset:o(n?.inset,Ii),canvasBackground:o(n?.canvasBackground,Wi)}},Dh=(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},ww=(e,t,n,o,r,a,s,l)=>{let p=rn(a),c=p.reveal==="push",d=l!=null,u=l?.inset??"",g=l?.canvasBackground??"";xw(e,t,n,o,c),vw(e,t,n,o,p.side,c),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"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,h=a?.launcher?.mobileFullscreen??!0,A=a?.launcher?.mobileBreakpoint??640,E=f!=null?f.innerWidth<=A:!1;if(h&&E&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),fu(t),uu(o),Bh(o),mu(n),Cl(r,o),Dh(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(a?.launcher?.zIndex??Gt),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(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"),Bh(o),hw(o,p.maxHeight),Dh(o,d&&s,u,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",fu(t),uu(o),mu(n),Cl(r,o);let M=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":S;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=M,o.style.transform=C,o.style.pointerEvents=s?"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",uu(o),gu(o),Cl(r,o);let M=Wh(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",T=p.side==="right"?s?-M:0:s?0:-M;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=`${S+M}px`,t.style.transition=C,t.style.marginLeft=`${T}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}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=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",fu(t),gu(o),mu(n),Cl(r,o);let M=p.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?p.width:"0px",C=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",T=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",yw(o,p.maxHeight),o.style.overflow=M||T?"hidden":"visible",o.style.transition=C,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let W=d?`calc(${Wh(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=W,r.style.minWidth=W,r.style.maxWidth=W,r.style.boxSizing="border-box"}}},Aw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Hh(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Hh(n,o)},destroy(){n.remove()}}},Sw=(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 a=e.nextSibling,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(s,e),p.appendChild(e);let g=null,f=()=>{g?.disconnect(),g=null},h=null,A=()=>{h=t?.launcher?.detachedPanel===!0?Cw(t):null};A();let E=()=>{ww(s,l,p,c,d,t,u,h)},k=null,M=()=>{k?.(),k=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(k=Nr(()=>{A(),E()}))},S=()=>{f(),rn(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{E()}),g.observe(s)))},C=!1,T=()=>{E(),S(),u&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,bw(s,rn(t)))},W=s.ownerDocument.defaultView,w=()=>{T()};return W?.addEventListener("resize",w),rn(t).reveal==="push"?(l.appendChild(p),l.appendChild(c),s.appendChild(l)):(s.appendChild(p),s.appendChild(c)),T(),M(),{mode:"docked",host:d,shell:s,syncWidgetState(D){let F=D.launcherEnabled?D.open:!0;u!==F&&(u=F,T())},updateConfig(D){t=D,(t?.launcher?.enabled??!0)===!1&&(u=!0),A(),T(),M()},destroy(){W?.removeEventListener("resize",w),k?.(),k=null,f(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},us=(e,t)=>Et(t)?Sw(e,t):Aw(e,t);var Mw=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)},Oh=e=>{let t=Mw(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=us(t,r),s,l=[],p=(E,k)=>{let S=!(k?.launcher?.enabled??!0)||Et(k),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),S&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0",C.style.minWidth="0"),n){let T=E.attachShadow({mode:"open"});T.appendChild(C),Fh(T,o)}else E.appendChild(C),Fh(E,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},c=()=>{a.syncWidgetState(s.getState())},d=()=>{l.forEach(E=>E()),l=[s.on("widget:opened",c),s.on("widget:closed",c)],c()},u=()=>{let E=p(a.host,r);s=vl(E,r,{debugTools:e.debugTools}),d()},g=()=>{l.forEach(E=>E()),l=[],s.destroy()};u(),e.onChatReady?.();let f=E=>{g(),a.destroy(),a=us(t,E),r=E,u()},h={update(E){let k=ul(r??{},E),M=Et(r),S=Et(k),C=Bo(r),T=Bo(k);if(M!==S||C!==T){f(k);return}r=k,a.updateConfig(r),s.update(E),c()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},A=new Proxy(h,{get(E,k,M){if(k==="host")return a.host;if(k in E)return Reflect.get(E,k,M);let S=s[k];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=A),A};function Tw(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 Ew(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(a=>a.toLowerCase().startsWith(o))?1:Tw(o,n)?2:3}function Nh(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function wl(e,t){let n=t.trim();if(!n)return[...e].sort(Nh);let o=[];for(let r of e){let a=Ew(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:Nh(r.item,a.item)),o.map(r=>r.item)}function kw(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 _h(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>wl(e.items,t),resolve:e.resolve}}function Uh(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=>wl(t,kw(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var jh=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Lw=new Set(["button","a","input","select","textarea","details","summary"]),Pw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),hu=/\b(product|card|item|listing|result)\b/i,bu=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Rw=3e3,Iw=100;function Gh(e){let t=typeof e.className=="string"?e.className:"";if(hu.test(t)||e.id&&hu.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&hu.test(o.value))return!0}return!1}function Kh(e){return bu.test((e.textContent??"").trim())}function Xh(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 Ww(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function qh(e){let t=e.match(bu);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 Hw(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 Bw="commerce-card",Dw="result-card";function zh(e){return!Gh(e)||!Kh(e)||!Xh(e)&&!Ww(e)?0:5200}function $h(e){return!Gh(e)||Kh(e)||!Xh(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xu=[{id:Bw,scoreElement(e){return zh(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||bu.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(zh(e)===0)return null;let{title:n,href:o}=Vh(e),r=qh((e.textContent??"").trim())??qh(t.text)??"",a=Hw(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
144
- `)}},{id:Dw,scoreElement(e){return $h(e)},formatSummary(e,t){if($h(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(`
145
- `)}}];function Fw(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Ow(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),c=e.rules??xu;return l==="simple"&&e.rules&&e.rules.length>0?(Fw(),c=[]):l==="simple"&&(c=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:c}}function yu(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Nw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function _w(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"||Lw.has(t)||n&&Pw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Jh(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 Uw(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 a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);let p=e.getAttribute("role");p&&(t.role=p);for(let c=0;c<e.attributes.length;c++){let d=e.attributes[c];d.name.startsWith("data-")&&(t[d.name]=d.value)}return t}function vu(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${yu(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of Nw){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${yu(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}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(s=>yu(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let l=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let p=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function qw(e){return e==="static"?Iw:Rw}function Qh(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:vu(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:_w(e),attributes:Uw(e)}}function Vw(e,t,n,o){let r=qw(t.interactivity),a=null;for(let s of n){let l=s.scoreElement(e,t,o);l>0&&(r+=l,s.formatSummary&&!a&&(a=s))}return{score:r,formattingRule:a}}function zw(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 $w(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let c=l,d=c.tagName.toLowerCase();if(jh.has(d)){l=s.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Jh(c)){l=s.nextNode();continue}let u=Qh(c,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!g&&!f){l=s.nextNode();continue}if(o.has(u.selector)){l=s.nextNode();continue}o.add(u.selector);let{score:h,formattingRule:A}=Vw(c,u,e.rules,n);r.push({el:c,domIndex:a,enriched:u,score:h,formattingRule:A}),a+=1}l=s.nextNode()}r.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex});let p=[];for(let c of r){if(p.length>=e.maxElements)break;zw(p,c)||p.push(c)}return p.sort((c,d)=>{let u=c.enriched.interactivity==="static"?1:0,g=d.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&d.score!==c.score?d.score-c.score:c.domIndex-d.domIndex}),p.map(c=>{let d;if(c.formattingRule?.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(d=g)}let u={...c.enriched};return d&&(u.formattedSummary=d),u})}function jw(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,c=p.tagName.toLowerCase();if(jh.has(c)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Jh(p)){a=r.nextNode();continue}let d=Qh(p,e.maxTextLength),u=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(f=>f==="role");if(!u&&!g){a=r.nextNode();continue}o.has(d.selector)||(o.add(d.selector),n.push(d))}a=r.nextNode()}let s=[],l=[];for(let p of n)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function Yh(e={}){let t=Ow(e),n=t.root??document.body;return n?t.mode==="simple"?jw(t,n):$w(t,n):[]}var Al=100;function Zh(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let a=e.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);a.length>0&&o.push(`Structured summaries:
142
+ ${Ct?"background: transparent !important;":""}
143
+ `}if(!x&&!i){let Lt="max-height: -moz-available !important; max-height: stretch !important;",an=u?"":"padding-top: 1.25em !important;",fi=u?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Le.style.cssText+=Lt+an+fi}An()},pc=()=>{e.style.setProperty("--persona-content-max-width",qo(o,Q()))},Kf=()=>{if(Q())return;let i=St(o),u=o.launcher?.sidebarMode??!1;if(i||u||(o.launcher?.fullHeight??!1)||!P)return;let x=e.ownerDocument.defaultView??window,k=o.launcher?.mobileFullscreen??!0,W=o.launcher?.mobileBreakpoint??640;if(k&&x.innerWidth<=W)return;let z=x.innerHeight,U=64,j=o.launcher?.heightOffset??0,Y=Math.max(200,z-U),pe=Math.min(640,Y);he.style.height=`${Math.max(200,pe-j)}px`};dc(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Zo=()=>{dc(),Kf(),Sr(e,o),Is(e,o),Ws(e,o),pc(),Vs?e.style.setProperty("--persona-artifact-welded-outer-radius",Vs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let De=[];De.push(()=>{document.removeEventListener("keydown",$f)}),De.push(()=>{Ra!==null&&clearTimeout(Ra)});let _n=null,Un=null;De.push(()=>{_n?.(),_n=null,Un?.(),Un=null}),Ha&&De.push(()=>{Ha?.disconnect(),Ha=null}),De.push(()=>{Fa?.(),Fa=null,cc(),xt&&(xt.remove(),xt=null),Ke?.element.style.removeProperty("width"),Ke?.element.style.removeProperty("maxWidth")}),me&&De.push(()=>{qe!==null&&(cancelAnimationFrame(qe),qe=null),Ae?.destroy(),Ae=null,Ne?.destroy(),Ne=null,Je=null});let tr=null,Xf=()=>{tr&&(tr(),tr=null),o.colorScheme==="auto"&&(tr=pa(()=>{Sr(e,o)}))};Xf(),De.push(()=>{tr&&(tr(),tr=null)}),De.push(d);let Js=o.features?.streamAnimation;if(Js?.type&&Js.type!=="none"){let i=ha(Js.type,Js.plugins);i&&(Al(i,e),De.push(()=>ry(e)))}let Qn=Es(I),Jf=Es(kn),Qf=Es(ee),nr=[Qn,Jf,Qf];De.push(()=>{nr.forEach(i=>i.destroy())});let or=null,q,rr=null,Yf=!1,Zf=0,em=null,tm=i=>i.reduce((u,h)=>h.role==="user"?u+1:u,0),nm=i=>{for(let u=i.length-1;u>=0;u--)if(br(i[u]))return i[u].id??null;return null},om=!1,tx=()=>{om||o.debug!==!0||(om=!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".'))},rm=!1,am=!1,sm=(i,u)=>{rm||o.debug!==!0||!u.enabled||u.expose||Yf||am&&(q.isStreaming()||i.some(br)||(rm=!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.")))},_r=i=>{if(!q)return;let u=i??q.getMessages(),h=Y=>{Y.render([],q,B,u)},x=Y=>{nr.forEach(pe=>{pe!==Y&&h(pe)})};rr&&(tm(u)>Zf||nm(u)!==em)&&(rr=null);let k=Bo(o);sm(u,k);let W=k.enabled?Ei(u):null,z=rr??W,U=rr?"host":"agent";if(z){let Y=o.suggestions?.followUps,pe=Y?.placement??(Y?"auto":"composer"),ye=(pe==="auto"?Q()?"composer":"after-message":pe)==="after-message"?Qf:Qn;x(ye),ye.render(z,q,B,u,o.suggestionChipsConfig,{source:U,surface:"followUp",variant:Y?.variant??"chip",behavior:Y?.behavior??"send",overflow:Y?.overflow??"wrap",maxItems:Y?.maxItems??4,config:o,plugins:a});return}if(u.some(Y=>Y.role==="user")){nr.forEach(h);return}let j=o.suggestions?.starters;if(j){let Y=Xo(mo(o),u),pe=j.placement??"auto",le=pe==="auto"?Y?"welcome":"composer":pe;if(le==="welcome"&&!Y){tx(),nr.forEach(h);return}let ye=le==="welcome"?Jf:Qn;x(ye),ye.render(j.items??o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:j.variant??"card",behavior:j.behavior??"send",overflow:j.overflow??"wrap",maxItems:j.maxItems??4,config:o,plugins:a});return}x(Qn),Qn.render(o.suggestionChips,q,B,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},im=()=>{rr&&(rr=null,_r())},nx=i=>{let u=Array.isArray(i)?[...i]:[];if(!u.length){im();return}let h=q?q.getMessages():[];rr=u,Yf=!0,Zf=tm(h),em=nm(h),_r(h)},In=!1,ar=Xh(),Ur=new Map,sr=new Map,bo=new Map,uc=0,ox=ao()!==null,dn=yl(),pn=0,xo=null,on=!1,Qs=!1,vo=0,Dt=null,ir=null,fc=!1,Ys=!1,lr=null,Oa=!0,Zs=!1,qr=null,ei=!1,cr=()=>{ei=!0,ix()},mc=null,rx=4,Yn=24,ax=80,sx=1e3,Zn=null,lm=()=>{e.setAttribute("data-persona-scrollbar",ec()),ec()!=="on-scroll"&&(Zn!==null&&clearTimeout(Zn),Zn=null,re.removeAttribute("data-persona-scrollbar-visible"))},ix=()=>{ec()==="on-scroll"&&(re.setAttribute("data-persona-scrollbar-visible",""),Zn!==null&&clearTimeout(Zn),Zn=setTimeout(()=>{Zn=null,uo(re,Yn)&&re.removeAttribute("data-persona-scrollbar-visible")},sx))};lm(),De.push(()=>{Zn!==null&&clearTimeout(Zn)});let gc=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cm=o.voiceRecognition?.autoResume??!1,eo=i=>{c.emit("voice:state",{active:je.active,source:i,timestamp:Date.now()})},Wn=()=>{A(i=>({...i,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},lx=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=cf(m.voiceState),u=!!i.active,h=Number(i.timestamp??0);je.manuallyDeactivated=!!i.manuallyDeactivated,u&&Date.now()-h<gS&&setTimeout(()=>{je.active||(je.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("restore"),q.isVoiceActive()&&Kr()}):ci("restore"))},1e3)},cx=()=>q?sb(q.getMessages()).filter(i=>!i.__skipPersist):[],ti=null,dm=(i,u)=>{typeof console<"u"&&console.error(i,u)},hc=(i,u)=>{let h=()=>{try{let z=i();return!z||typeof z.then!="function"?null:Promise.resolve(z).catch(U=>{dm(u,U)})}catch(z){return dm(u,z),null}},x=ti,k=x?x.then(()=>h()??void 0):h();if(!k)return;let W=k.finally(()=>{ti===W&&(ti=null)});ti=W};function yc(i){if(!g?.save)return;let h={messages:i?sb(i):q?cx():[],metadata:m,artifacts:Pn.artifacts,selectedArtifactId:Pn.selectedId};hc(()=>g.save(h),"[AgentWidget] Failed to persist state:")}let Vr=null,pm=()=>Le.querySelector("#persona-scroll-container")||re,zr=()=>{Vr!==null&&(cancelAnimationFrame(Vr),Vr=null),on=!1},um=()=>{xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!1,zr()},dx=()=>In&&xc()&&(cn()!=="anchor-top"||Tf()),bc=()=>{let i=ka()||"Jump to latest",u=dx();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),vo>0?(Jo.textContent=String(vo),Jo.style.display="",Pt.setAttribute("aria-label",`${i} (${vo} new)`)):(Jo.textContent="",Jo.style.display="none",Pt.setAttribute("aria-label",u?`${i} (response streaming below)`:i))},fm=()=>{vo!==0&&(vo=0,bc())},px=()=>{let i=Dt?.spacerHeight??0;return i<=0?uo(re,Yn):ri(i)-re.scrollTop-re.clientHeight<=Yn},xc=()=>ho()?!dn.isFollowing():!px(),vc=()=>!!q&&q.getMessages().length>0,Vt=()=>{if(!Xb()||Me){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==be&&be.appendChild(Pt),Yo();let u=jn(re)>0&&xc()&&vc();u?bc():fm(),Pt.style.display=u?"":"none"},Na=()=>{dn.pause()&&(um(),Vt())},Co=()=>{dn.resume(),fm(),Vt()},wo=(i=!1)=>{ho()&&vc()&&dn.isFollowing()&&(!i&&!In||(xo!==null&&(cancelAnimationFrame(xo),xo=null),Qs=!0,xo=requestAnimationFrame(()=>{xo=null,Qs=!1,dn.isFollowing()&&ux(pm(),i?220:140)})))},mm=(i,u,h,x=()=>!0)=>{let k=i.scrollTop,W=u(),z=W-k;if(zr(),Math.abs(z)<1){on=!0,i.scrollTop=W,pn=i.scrollTop,on=!1;return}let U=performance.now();on=!0;let j=pe=>1-Math.pow(1-pe,3),Y=pe=>{if(!x()){zr();return}let le=u();le!==W&&(W=le,z=W-k);let ye=pe-U,Ge=Math.min(ye/h,1),ht=j(Ge),ct=k+z*ht;i.scrollTop=ct,pn=i.scrollTop,Ge<1?Vr=requestAnimationFrame(Y):(i.scrollTop=W,pn=i.scrollTop,Vr=null,on=!1)};Vr=requestAnimationFrame(Y)},ux=(i,u=500)=>{let h=jn(i)-i.scrollTop;if(Math.abs(h)<1){pn=i.scrollTop;return}if(Math.abs(h)>=ax){zr(),on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1;return}mm(i,()=>jn(i),u,()=>dn.isFollowing())},gm=()=>{if(!vc()){Vt();return}let i=pm();on=!0,i.scrollTop=jn(i),pn=i.scrollTop,on=!1,Vt()},dr=i=>{let u=0,h=i;for(;h&&h!==re;)u+=h.offsetTop,h=h.offsetParent;return u},fx=()=>{let i=re.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??re.ownerDocument.getSelection()},ni=()=>ey(fx(),re),hm=()=>{if(Jb()!=="last-user-turn")return!1;let i=q?.getMessages()??[];if(i.length<2)return!1;let u=[...i].reverse().find(W=>W.role==="user");if(!u)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=re.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let k=Math.min(Math.max(0,dr(x)-La()),jn(re));return on=!0,re.scrollTop=k,pn=re.scrollTop,on=!1,cn()==="follow"&&!uo(re,Yn)&&dn.pause(),Vt(),!0},oi=i=>{let u=Math.max(0,Math.round(i));vn.style.height=`${u}px`,vn.style.display=u>0?"":"none",Dt&&(Dt.spacerHeight=Math.max(0,i))},ri=i=>{let u=parseFloat(getComputedStyle(re).paddingBottom)||0,h=0;for(let k of Array.from(re.children)){if(k===vn||k.offsetHeight===0)continue;let W=dr(k)+k.offsetHeight;W>h&&(h=W)}let x=re.scrollHeight-i;return h>0?Math.min(h+u,x):x},mx=()=>{if(!Dt||Dt.spacerHeight<=0)return;let i=ri(Dt.spacerHeight),u=Math.max(0,Math.round(re.scrollTop)+re.clientHeight-i+Yn);u<Dt.spacerHeight&&(oi(u),Vt())},_a=()=>{ir!==null&&(cancelAnimationFrame(ir),ir=null),zr(),Dt=null,vn.style.height="0px",vn.style.display="none"},ym=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Cc=i=>re.querySelector(`[data-message-id="${ym(i)}"]`),bm=i=>{ir!==null&&cancelAnimationFrame(ir),ir=requestAnimationFrame(()=>{ir=null;let u=ym(i),h=re.querySelector(`[data-message-id="${u}"]`);if(!h)return;let x=dr(h),k=Dt?.spacerHeight??0,W=ri(k),{targetScrollTop:z,spacerHeight:U}=Mu({anchorOffsetTop:x,topOffset:La(),viewportHeight:re.clientHeight,contentHeight:W,slack:Yn});Dt={initialSpacerHeight:U,contentHeightAtAnchor:W,spacerHeight:U},oi(U),mm(re,()=>h.isConnected?Math.max(0,dr(h)-La()):z,220)})},xm=()=>{if(cn()!=="anchor-top"||!Dt||!qr)return;let i=Cc(qr);if(!i)return;zr();let u=Dt.spacerHeight,h=ri(u),{targetScrollTop:x,spacerHeight:k}=Mu({anchorOffsetTop:dr(i),topOffset:La(),viewportHeight:re.clientHeight,contentHeight:h,slack:Yn});Dt={initialSpacerHeight:k,contentHeightAtAnchor:h,spacerHeight:k},oi(k),on=!0,re.scrollTop=x,pn=re.scrollTop,on=!1,Vt()},gx=()=>{if(ho()){if(!dn.isFollowing()||uo(re,1))return;wo(!In);return}if(Dt&&Dt.initialSpacerHeight>0){let i=re.scrollHeight-Dt.spacerHeight,u=ty({initialSpacerHeight:Dt.initialSpacerHeight,contentHeightAtAnchor:Dt.contentHeightAtAnchor,currentContentHeight:i});u!==Dt.spacerHeight&&oi(u)}Vt()},hx=i=>{let u=cn();u==="follow"?(Co(),wo(!0)):u==="anchor-top"&&(Oa=!1,Zs=!0,ei=!1,qr=i,bm(i))},yx=()=>{if(cn()==="anchor-top"){if(Zs){Oa=!1;return}Oa=!0,_a(),Co(),wo(!0)}},bx=96,xx=i=>{if(lr===null)return!0;let u=Cc(lr),h=Cc(i);if(!u||!h)return!0;let x=dr(h)-dr(u);return La()+x>re.clientHeight-bx},vx=i=>{if(cn()!=="anchor-top"||!Zs||ei||ni())return;let u=lr===null;for(let h of i){if(!u){h.id===lr&&(u=!0);continue}if(Zh(h)){if(h.id===qr||!xx(h.id))return;qr=h.id,bm(h.id);return}}},Cx=i=>{let u=new Map;i.forEach(h=>{let x=gc.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(c.emit("assistant:message",h),!Ys&&(cn()!=="anchor-top"||Tf())&&xc()&&(vo+=1,bc(),Vt(),kf(vo===1?"1 new message below.":`${vo} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&c.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&c.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):c.emit("approval:requested",{approval:h.approval,message:h}))}),gc.clear(),u.forEach((h,x)=>{gc.set(x,h)})},ai=(i,u)=>{let h=u==="user"?"user":"assistant",x=o.layout?.messages?.[h],k=x?.width??"content",W=x?.maxWidth??(k==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${u}`,`persona-message-width-${k}`),i.classList.toggle("persona-justify-end",u==="user"),i.setAttribute("data-message-role",u),i.setAttribute("data-message-width",k),i.style.setProperty("--persona-message-row-max-width",W)},pr=(i,u)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${i}`,h.setAttribute("data-wrapper-id",i),ai(h,u),h},wx=(i,u,h)=>{let x=document.createElement("div"),W=(()=>{let _=a.find(Re=>Re.renderLoadingIndicator);if(_?.renderLoadingIndicator)return _.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),z=(_,Re)=>Re==null?!1:typeof Re=="string"?(_.textContent=Re,!0):(_.appendChild(Re),!0),U=new Set,j=new Map,Y=new Set,pe=a.some(_=>_.renderAskUserQuestion),le=[],ye=[],Ge=o.enableComponentStreaming!==!1,ht=o.approval!==!1,ct=[];if(u.forEach(_=>{U.add(_.id),j.set(_.id,_.role);let Re=pe&&so(_),Fe=ht&&_.variant==="approval"&&!!_.approval,Ee=!Re&&_.role==="assistant"&&!_.variant&&Ge&&Os(_);!Fe&&bo.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id)),!Ee&&sr.has(_.id)&&(i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),sr.delete(_.id));let At=so(_)?`:${_.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${_.agentMetadata?.askUserQuestionAnswers?Object.keys(_.agentMetadata.askUserQuestionAnswers).length:0}`:"",dt=Kh(_,uc)+At,Ot=Re||Fe||Ee?null:Jh(ar,_.id,dt);if(Ot){x.appendChild(Ot.cloneNode(!0)),so(_)&&_.toolCall?.id&&_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let pt=null,rn=a.find(Oe=>!!(_.variant==="reasoning"&&Oe.renderReasoning||_.variant==="tool"&&Oe.renderToolCall||!_.variant&&Oe.renderMessage)),Wt=o.layout?.messages;if(so(_)&&_.agentMetadata?.askUserQuestionAnswered===!0){Ur.delete(_.id),i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime");return}if(br(_)&&Bo(o).enabled)return;if(so(_)&&o.features?.askUserQuestion?.enabled!==!1){let Oe=a.find(zt=>typeof zt.renderAskUserQuestion=="function");if(Oe&&at.current){let zt=Ur.get(_.id),$t=zt!==dt,Ct=null;if($t){let{payload:Xe,complete:He}=io(_),yt=_.id,jt=()=>at.current?.getMessages().find(An=>An.id===yt);Ct=Oe.renderAskUserQuestion({message:_,payload:Xe,complete:He,resolve:An=>{let Qa=jt();Qa&&at.current?.resolveAskUserQuestion(Qa,An)},dismiss:()=>{let An=jt();An?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(An),at.current?.resolveAskUserQuestion(An,"(dismissed)"))},config:o})}let st=zt!=null;if($t&&Ct===null&&!st){_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}let ft=pr(_.id,_.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),le.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}else{_.agentMetadata?.awaitingLocalTool===!0&&!_.agentMetadata?.askUserQuestionAnswered&&(Y.add(_.toolCall.id),aa(_,o,Te.composerOverlay));return}}else if(Fe){let Oe=a.find(st=>typeof st.renderApproval=="function")??p,$t=bo.get(_.id)!==dt,Ct=null;if($t&&Oe?.renderApproval){let st=_.id,ft=(Xe,He)=>{let yt=at.current?.getMessages().find(jt=>jt.id===st);yt?.approval&&(yt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(yt.id,Xe):at.current?.resolveApproval(yt.approval,Xe,He))};Ct=Oe.renderApproval({message:_,defaultRenderer:()=>Ol(_,o),config:o,approve:Xe=>ft("approved",Xe),deny:Xe=>ft("denied",Xe)})}if($t&&Ct===null)i.querySelector(`#wrapper-${_.id}`)?.removeAttribute("data-preserve-runtime"),bo.delete(_.id),pt=Ol(_,o);else{let st=pr(_.id,_.role);st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),x.appendChild(st),ct.push({messageId:_.id,fingerprint:dt,bubble:Ct});return}}else if(rn)if(_.variant==="reasoning"&&_.reasoning&&rn.renderReasoning){if(!ue)return;pt=rn.renderReasoning({message:_,defaultRenderer:()=>Gu(_,o),config:o})}else if(_.variant==="tool"&&_.toolCall&&rn.renderToolCall){if(!oe)return;pt=rn.renderToolCall({message:_,defaultRenderer:()=>Xu(_,o),config:o})}else rn.renderMessage&&(pt=rn.renderMessage({message:_,defaultRenderer:()=>{let Oe=ba(_,h,Wt,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o});return _.role!=="user"&&af(Oe,_,o,q),Oe},config:o}));if(!pt&&Ee){let Oe=jl(_);if(Oe){let zt=sr.get(_.id),$t=zt!==dt,Ct=o.wrapComponentDirectiveInBubble!==!1&&Nn.getOptions(Oe.component)?.bubbleChrome!==!1,st=null;if($t){let ft=$l(Oe,{config:o,message:_,transform:h});if(ft&&Oe.component==="PersonaArtifactInline"){let Xe=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),He=Xe?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(He):He,jt=He?i.querySelector(`#wrapper-${_.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;Xe&&jt&&jt!==Xe&&qh(jt)&&(Xe===ft?ft=jt:Xe.replaceWith(jt))}if(ft)if(Ct){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-${_.id}`,Xe.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-mb-3 persona-text-sm persona-leading-relaxed",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=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-${_.id}`,Xe.setAttribute("data-message-id",_.id),Xe.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let He=document.createElement("div");He.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",He.innerHTML=h({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),Xe.appendChild(He)}Xe.appendChild(ft),st=Xe}}if(st||zt!=null){let ft=pr(_.id,_.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),ye.push({messageId:_.id,fingerprint:dt,bubble:st});return}}}if(!pt)if(_.variant==="reasoning"&&_.reasoning){if(!ue)return;pt=Gu(_,o)}else if(_.variant==="tool"&&_.toolCall){if(!oe)return;pt=Xu(_,o)}else if(_.variant==="approval"&&_.approval){if(o.approval===!1)return;pt=Ol(_,o)}else{let Oe=o.layout?.messages;Oe?.renderUserMessage&&_.role==="user"?pt=Oe.renderUserMessage({message:_,config:o,streaming:!!_.streaming}):Oe?.renderAssistantMessage&&_.role==="assistant"?pt=Oe.renderAssistantMessage({message:_,config:o,streaming:!!_.streaming}):pt=ba(_,h,Oe,o.messageActions,gt,{loadingIndicatorRenderer:W,widgetConfig:o}),_.role!=="user"&&pt&&af(pt,_,o,q)}let Ie=pr(_.id,_.role);Ie.appendChild(pt),Qh(ar,_.id,dt,Ie),x.appendChild(Ie)}),Te.composerOverlay&&Te.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let Fe=Re.getAttribute("data-persona-ask-sheet-for");Fe&&!Y.has(Fe)&&Wo(Te.composerOverlay,Fe)}),o.features?.toolCallDisplay?.grouped){let _=[],Re=[],Fe=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Ee=>{if(Ee.variant==="tool"&&Ee.toolCall&&oe){Re.push(Ee);return}Ee.variant==="reasoning"&&!ue||((Re.length>1||Fe&&Re.length>0)&&_.push(Re),Re=[])}),(Re.length>1||Fe&&Re.length>0)&&_.push(Re),_.forEach(Ee=>{let At=Ee.map(Oe=>Array.from(x.children).find(zt=>zt instanceof HTMLElement&&zt.getAttribute("data-wrapper-id")===Oe.id)).filter(Oe=>!!Oe);if(At.length<(Fe?1:2))return;let dt=pr(`tool-group-${Ee[0].id}`,"assistant");dt.setAttribute("data-persona-tool-group-row","true");let Ot=document.createElement("div");Ot.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Ot.setAttribute("data-persona-tool-group","true");let pt=document.createElement("div");pt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",pt.id=`tool-group-summary-${Ee[0].id}`;let rn=`Called ${Ee.length} ${Ee.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Ee,toolCalls:Ee.map(Oe=>Oe.toolCall).filter(Oe=>!!Oe),defaultSummary:rn,config:o});z(pt,Wt)||(pt.textContent=rn);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Ee[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),Ot.appendChild(pt),Fe||Ot.appendChild(Ie),dt.appendChild(Ot),At[0].before(dt),At.forEach((Oe,zt)=>{if(Fe){Oe.remove();return}Oe.style.setProperty("--persona-message-row-max-width","100%");let $t=document.createElement("div");$t.className="persona-tool-group-item persona-relative",$t.setAttribute("data-persona-tool-group-item","true"),zt<At.length-1&&$t.setAttribute("data-persona-tool-group-connector","true"),$t.appendChild(Oe),Ie.appendChild($t)})})}Yh(ar,U);let un=u.some(_=>_.role==="assistant"&&_.streaming),Mt=u[u.length-1],It=Mt?.role==="assistant"&&!Mt.streaming&&Mt.variant!=="approval";if(In&&u.some(_=>_.role==="user")&&!un&&!It){let _={config:o,streaming:!0,location:"standalone",defaultRenderer:Pr},Re=a.find(Ee=>Ee.renderLoadingIndicator),Fe=null;if(Re?.renderLoadingIndicator&&(Fe=Re.renderLoadingIndicator(_)),Fe===null&&o.loadingIndicator?.render&&(Fe=o.loadingIndicator.render(_)),Fe===null&&(Fe=Pr()),Fe){let Ee=document.createElement("div"),At=o.loadingIndicator?.showBubble!==!1,dt=o.layout?.messages?.layout??"bubble";Ee.className=At?ks("assistant",dt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ee.setAttribute("data-typing-indicator","true"),At&&(Ee.style.color="var(--persona-message-assistant-text, var(--persona-text))",dt!=="flat"&&(Ee.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ee.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ee.appendChild(Fe);let Ot=pr("typing-indicator","assistant");Ot.appendChild(Ee),x.appendChild(Ot)}}if(!In&&u.length>0){let _=u[u.length-1],Re={config:o,lastMessage:_,messageCount:u.length},Fe=a.find(At=>At.renderIdleIndicator),Ee=null;if(Fe?.renderIdleIndicator&&(Ee=Fe.renderIdleIndicator(Re)),Ee===null&&o.loadingIndicator?.renderIdle&&(Ee=o.loadingIndicator.renderIdle(Re)),Ee){let At=document.createElement("div"),dt=o.loadingIndicator?.showBubble!==!1;At.className=dt?["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(" "),At.setAttribute("data-idle-indicator","true"),At.appendChild(Ee);let Ot=pr("idle-indicator","assistant");Ot.appendChild(At),x.appendChild(Ot)}}if(vg(x),hl(i,x),Gc(i),le.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of le){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),Ur.set(_,Re)))}if(Ur.size>0)for(let _ of Ur.keys())U.has(_)||Ur.delete(_);if(ye.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ye){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),sr.set(_,Re)))}if(sr.size>0)for(let _ of sr.keys())U.has(_)||sr.delete(_);if(ct.length>0)for(let{messageId:_,fingerprint:Re,bubble:Fe}of ct){let Ee=i.querySelector(`#wrapper-${_}`);Ee&&(ai(Ee,j.get(_)??"assistant"),Fe!==null&&(Ee.replaceChildren(Fe),Ee.setAttribute("data-bubble-fp",Re),bo.set(_,Re)))}if(bo.size>0)for(let _ of bo.keys())U.has(_)||bo.delete(_)},Ua=(i,u,h)=>{wx(i,u,h),qf()},qa=null,Ax=()=>{if(qa)return;let i=h=>{let x=h.composedPath();x.includes(Le)||tt&&x.includes(tt)||lt(!1,"user")};qa=i,(e.ownerDocument??document).addEventListener("pointerdown",i,!0)},vm=()=>{if(!qa)return;(e.ownerDocument??document).removeEventListener("pointerdown",qa,!0),qa=null};De.push(()=>vm());let Va=null,Sx=()=>{if(Va)return;let i=h=>{h.key==="Escape"&&(h.isComposing||lt(!1,"user"))};Va=i,(e.ownerDocument??document).addEventListener("keydown",i,!0)},Cm=()=>{if(!Va)return;(e.ownerDocument??document).removeEventListener("keydown",Va,!0),Va=null};De.push(()=>Cm());let za=!1,wm=new Set,Mx=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},$r=()=>{if(!Q())return;let i=Te.peekBanner,u=Te.peekTextNode;if(!i||!u)return;if(J){i.classList.remove("persona-pill-peek--visible");return}let h=q?.getMessages()??[],x;for(let Mt=h.length-1;Mt>=0;Mt--){let It=h[Mt];if(It.role==="assistant"&&It.content){x=It;break}}if(!x){i.classList.remove("persona-pill-peek--visible");return}let k=x.content,W=!!x.streaming,z=Mx(),U=vl(z),j=U.type!=="none"?ha(U.type,z?.plugins):null,Y=j?.isAnimating?.(x)===!0,pe=j!==null&&(W||Y);pe&&j&&!wm.has(j.name)&&(Al(j,e),wm.add(j.name));let le=pe&&j?.containerClass?j.containerClass:null,ye=u.dataset.personaPeekStreamClass??null;ye&&ye!==le&&(u.classList.remove(ye),delete u.dataset.personaPeekStreamClass),le&&ye!==le&&(u.classList.add(le),u.dataset.personaPeekStreamClass=le),pe?(u.style.setProperty("--persona-stream-step",`${U.speed}ms`),u.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Ge=pe?Cl(k,U.buffer,j,x,W):k;if(pe&&U.placeholder==="skeleton"&&W&&(!Ge||!Ge.trim())){let Mt=document.createElement("div"),It=Ss();It.classList.add("persona-pill-peek__skeleton"),Mt.appendChild(It),hl(u,Mt)}else{let Mt=Math.max(0,Ge.length-100),It=Ge.length>100?Ge.slice(-100):Ge,_=Vn(It);if(!pe||!j){let Re=Ge.length>100?`\u2026${It}`:It;u.textContent!==Re&&(u.textContent=Re)}else{let Re=_;(j.wrap==="char"||j.wrap==="word")&&(Re=As(_,j.wrap,`peek-${x.id}`,{skipTags:j.skipTags,startIndex:Mt}));let Fe=document.createElement("div");if(Fe.innerHTML=Re,j.useCaret&&It.length>0){let Ee=wl(),At=Fe.querySelectorAll(".persona-stream-char, .persona-stream-word"),dt=At[At.length-1];dt?.parentNode?dt.parentNode.insertBefore(Ee,dt.nextSibling):Fe.appendChild(Ee)}hl(u,Fe),j.onAfterRender?.({container:u,bubble:i,messageId:x.id,message:x,speed:U.speed,duration:U.duration})}}let un=In||za;i.classList.toggle("persona-pill-peek--visible",un)};if(Q()){let i=Te.peekBanner;if(i){let x=k=>{k.preventDefault(),k.stopPropagation(),lt(!0,"user")};i.addEventListener("pointerdown",x),De.push(()=>{i.removeEventListener("pointerdown",x)})}let u=()=>{za||(za=!0,$r())},h=()=>{za&&(za=!1,$r())};he.addEventListener("pointerenter",u),he.addEventListener("pointerleave",h),De.push(()=>{he.removeEventListener("pointerenter",u),he.removeEventListener("pointerleave",h)}),tt&&(tt.addEventListener("pointerenter",u),tt.addEventListener("pointerleave",h),De.push(()=>{tt.removeEventListener("pointerenter",u),tt.removeEventListener("pointerleave",h)}))}let Tx=i=>{let u=o.launcher?.composerBar??{},h=u.expandedSize??"anchored",x=u.bottomOffset??"16px",k=u.collapsedMaxWidth,W=u.expandedMaxWidth??"880px",z=u.expandedTopOffset??"5vh",U=u.modalMaxWidth??"880px",j=u.modalMaxHeight??"min(90vh, 800px)",Y="calc(100vw - 32px)",pe="var(--persona-pill-area-height, 80px)",le=Le.style;if(le.left="",le.right="",le.top="",le.bottom="",le.transform="",le.width="",le.maxWidth="",le.height="",le.maxHeight="",tt){let ye=tt.style;ye.bottom=x,ye.width=k??""}if(i&&h!=="fullscreen"){if(h==="modal"){le.top="50%",le.left="50%",le.transform="translate(-50%, -50%)",le.bottom="auto",le.right="auto",le.width=U,le.maxWidth=Y,le.maxHeight=j,le.height=j;return}le.left="50%",le.transform="translateX(-50%)",le.bottom=`calc(${x} + ${pe})`,le.top=z,le.width=W,le.maxWidth=Y}},$a=()=>{if(!Z())return;if(Q()){let Y=(o.launcher?.composerBar??{}).expandedSize??"anchored",pe=J?"expanded":"collapsed";Le.dataset.state=pe,Le.dataset.expandedSize=Y,tt&&(tt.dataset.state=pe,tt.dataset.expandedSize=Y),Le.style.removeProperty("display"),Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Tx(J),be.style.display=J?"flex":"none",Zo(),J?(Ax(),Sx()):(vm(),Cm()),$r();return}let i=St(o),u=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,k=u.innerWidth<=h,W=x&&k&&P,z=ln(o).reveal;J?(Le.style.removeProperty("display"),Le.style.display=i?"flex":"",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.classList.remove("persona-scale-95","persona-opacity-0"),he.classList.add("persona-scale-100","persona-opacity-100"),kt?(kt.setPanelOpen(!0),kt.element.style.display="none"):Yt&&(Yt.style.display="none")):(i?i&&(z==="overlay"||z==="push")&&!W?(Le.style.removeProperty("display"),Le.style.display="flex",Le.classList.remove("persona-pointer-events-none","persona-opacity-0"),he.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"),he.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"),he.classList.remove("persona-scale-100","persona-opacity-100"),he.classList.add("persona-scale-95","persona-opacity-0")),kt?(kt.setPanelOpen(!1),kt.element.style.display=i?"none":""):Yt&&(Yt.style.display=i?"none":""))},lt=(i,u="user")=>{if(!Z()||J===i)return;let h=J;J=i,$a();let x=(()=>{let W=o.launcher?.sidebarMode??!1,z=e.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,j=o.launcher?.mobileBreakpoint??640,Y=z.innerWidth<=j,pe=St(o)&&U&&Y,le=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return W||U&&Y&&P||pe||le})();if(J&&x){if(!_n){let W=e.getRootNode(),z=W instanceof ShadowRoot?W.host:e.closest(".persona-host");z&&(_n=Pu(z,o.launcher?.zIndex??Ut))}Un||(Un=Ru(e.ownerDocument))}else J||(_n?.(),_n=null,Un?.(),Un=null);J&&(Xa(),hm()||(cn()==="follow"?wo(!0):gm()));let k={open:J,source:u,timestamp:Date.now()};J&&!h?c.emit("widget:opened",k):!J&&h&&c.emit("widget:closed",k),c.emit("widget:state",{open:J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()})},si=i=>{Us(i?"stop":"send"),te&&(te.disabled=i),nr.forEach(u=>{u.elements.forEach(h=>{h.toggleAttribute("data-disabled",i),h instanceof HTMLButtonElement||h.setAttribute("aria-disabled",i?"true":"false")}),u.buttons.forEach(h=>{h.disabled=i})}),Tc.forEach(u=>{u.toggleAttribute("data-disabled",i),u instanceof HTMLButtonElement?u.disabled=i:u.setAttribute("aria-disabled",i?"true":"false"),u.querySelectorAll("button").forEach(h=>{h.disabled=i})}),we.dataset.personaComposerStreaming=i?"true":"false",we.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=i)})},wc=()=>{je.active||B&&B.focus()};c.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>wc(),200)});let Ac=!K.hidden,Ao=null,Am=!b,Sm=null,Mm,Tm=null,ja=null,Sc=i=>{let u=mo(o),h=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(h!==Sm||u.icon!==Mm)&&(Sm=h,Mm=u.icon,Bl({host:K,iconHolder:V,title:ce,subtitle:Ve,starterSuggestions:kn},u));let x=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;x!==Tm&&(Tm=x,Dl(X,u.message,o));let k=i??(q?q.getMessages():o.initialMessages),W=Xo(u,k),z=W!==Ac;if(Ac=W,ja){Ao?.cancel(),Ao=null,xa(re,K,!0);return}if(z&&!W&&u.dismiss==="on-first-message"&&Am){Ao=yy(K,U=>{Ao===U&&(Ao=null),!Ac&&!ja&&(xa(re,K,!1),xm()),U?.cancel()});return}if(Ao){if(!W)return;Ao.cancel(),Ao=null}xa(re,K,W),z&&!W&&xm()},Mc=[],Tc=[],Ec=!1,Em=null,km,Lm=()=>{Tc.length=0;let i=Mc.splice(0,Mc.length);for(let u of i)try{u()}catch(h){console.warn("[persona] renderWelcome cleanup threw",h)}};De.push(Lm);let Ex=(i,u)=>{let h=Wu(i,u);if(!h)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let x=o.suggestions?.starters,k=Hu({item:{...h,behavior:h.behavior??x?.behavior??"send"},index:u,surface:"starter",source:"config",variant:x?.variant??"card",streaming:s?q.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:q,getTextarea:()=>B,eventTarget:K});return Tc.push(k),k},kc=()=>{if(Ec)return;Ec=!0;let i=mo(o);Em=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,km=i.icon;try{Lm(),gy(re,K,ja),ja=null;let u=q?q.getMessages():o.initialMessages,h=Xo(i,u),x=0,k=null;for(let W of a)if(W.renderWelcome&&(k=W.renderWelcome({config:i,variant:i.variant,visible:h,defaultRenderer:()=>K,sendMessage:z=>{if(!q||q.isStreaming())return;let U=z.trim();U&&q.sendMessage(U)},requestRender:()=>kc(),renderStarter:z=>Ex(z,x++),storage:l(W.id),onCleanup:z=>{Mc.push(z)}}),k))break;k&&k!==K&&(ja=k,my(re,K,k))}finally{Ec=!1}Sc()},kx=()=>{let i=mo(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Em&&i.icon===km||kc()},Lc=()=>{Sc(),rc||(B.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(y.textContent=o.copy?.sendButtonLabel??"Send")),B.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',B.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let i=m.sessionId;return typeof i=="string"?i:null},setStoredSessionId:i=>{A(u=>({...u,sessionId:i}))}});let ur=null,Lx=()=>{ur==null&&(ur=setInterval(()=>{let i=xe.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval(ur),ur=null;return}let u=Date.now();i.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Li(u-x))})},100))},Pc=(i,u)=>{if(Object.is(i,u))return!0;if(i===null||u===null||typeof i!="object"||typeof u!="object")return!1;if(Array.isArray(i)||Array.isArray(u))return!Array.isArray(i)||!Array.isArray(u)||i.length!==u.length?!1:i.every((z,U)=>Pc(z,u[U]));let h=i,x=u,k=Object.keys(h),W=Object.keys(x);return k.length===W.length&&k.every(z=>Object.prototype.hasOwnProperty.call(x,z)&&Pc(h[z],x[z]))},Pm=i=>{let{content:u,rawContent:h,llmContent:x,...k}=i;return k},Rc=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!Os(i),Px=(i,u,h)=>{if(i.length!==u.length)return!1;let x=i[h.index],k=u[h.index];return!x||!k||x.id!==h.id||k.id!==h.id?!1:(!Object.is(x.content,k.content)||!Object.is(x.rawContent,k.rawContent)||!Object.is(x.llmContent,k.llmContent))&&Rc(x)&&Rc(k)&&Pc(Pm(x),Pm(k))},Rm=null,jr=null,fr=null,to=null,ii=i=>{Rm=i;let u,h;jr=null;for(let k=i.length-1;k>=0;k-=1){let W=i[k];if(!u&&W.role==="user"&&(u=W),!h&&W.role==="assistant"&&(h=W),!jr&&Rc(W)&&(jr={index:k,id:W.id}),u&&h&&jr)break}Ua(xe,i,ie),Cu(xe,Pn.artifacts,{suppressTransition:In}),Lx(),Sc(i),_r(i),wo(!In),Cx(i),i.length===0&&(_a(),Oa=!0,Zs=!1,qr=null,ei=!1),!fc||Ys?(fc=!0,lr=u?.id??null,mc=h?.id??null):u&&u.id!==lr?(lr=u.id,hx(u.id)):h&&h.id!==mc&&yx(),h&&(mc=h.id),vx(i);let x=je.lastUserMessageId;u&&u.id!==x&&(je.lastUserMessageId=u.id,c.emit("user:message",u)),je.lastUserMessageWasVoice=!!u?.viaVoice,yc(i),$r()},Ic=()=>{to!==null&&(cancelAnimationFrame(to),to=null);let i=fr;fr=null,i&&ii(i)},Im=()=>{to!==null&&cancelAnimationFrame(to),to=null,fr=null},Rx=i=>{let u=fr??Rm;if(In&&u&&jr&&Px(u,i,jr)){fr=i,to===null&&(to=requestAnimationFrame(()=>{to=null;let h=fr;fr=null,h&&ii(h)}));return}if(i.length===0){Im(),ii(i);return}Ic(),ii(i)};q=new ca(o,{onMessagesChanged(i){Rx(i)},onStatusChanged(i){let u=o.statusIndicator??{};En(N,(x=>x==="idle"?u.idleText??Ht.idle:x==="connecting"?u.connectingText??Ht.connecting:x==="connected"?u.connectedText??Ht.connected:x==="error"?u.errorText??Ht.error:x==="paused"?u.pausedText??Ht.paused:x==="resuming"?u.resumingText??Ht.resuming:Ht[x])(i),u,i)},onStreamingChanged(i){i||(q?.getMessages().length===0?Im():Ic()),In=i,si(i),q&&Ua(xe,q.getMessages(),ie),i||(wo(!0),mx(),am=!0,q&&sm(q.getMessages(),Bo(o))),Vt(),kf(i?"Responding\u2026":"Response complete."),$r()},onVoiceStatusChanged(i){if(c.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":no(),Kr();break;case"processing":no(),qx();break;case"speaking":no(),Vx();break;default:i==="idle"&&q.isBargeInActive()?(no(),Kr(),te?.setAttribute("aria-label","End voice session")):(je.active=!1,no(),eo("system"),Wn());break}},onArtifactsState(i){Pn=i,i.artifacts.length===0&&(Fr=!1),Cu(xe,i.artifacts,{suppressTransition:In}),Jn(),yc()},onReconnect(i){let{executionId:u,lastEventId:h}=i.handle;i.phase==="paused"?c.emit("stream:paused",{executionId:u,after:h}):i.phase==="resuming"?c.emit("stream:resuming",{executionId:u,after:h,attempt:i.attempt??1}):c.emit("stream:resumed",{executionId:u,after:h})}}),at.current=q,De.push(()=>q.cancel());let Wc=null;if(q.onReadAloudChange((i,u)=>{_f=i,Uf=u,qf();let h=i??Wc;i&&(Wc=i);let x=h?q.getMessages().find(k=>k.id===h)??null:null;c.emit("message:read-aloud",{messageId:h,message:x,state:u,timestamp:Date.now()}),u==="idle"&&(Wc=null)}),s=!0,fc=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}o.clientToken&&q.initClientSession().catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ne||o.onSSEEvent)&&q.setSSEEventCallback((i,u)=>{o.onSSEEvent?.(i,u),_e?.processEvent(i,u),Ne?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(u)})});let Wm=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};b?b.then(i=>{if(i){if(i.metadata&&(m=cf(i.metadata),M.syncFromMetadata()),i.messages?.length){Ys=!0;try{q.hydrateMessages(i.messages)}finally{Ys=!1}}i.artifacts?.length&&q.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Am=!0,Wm()}):Wm();let Hm=()=>{!Q()||J||!(o.launcher?.composerBar?.expandOnSubmit??!0)||lt(!0,"auto")},Ix=(i,u)=>i?u?{refs:[...i.refs,...u.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([i.finalize(),u.finalize()]),k=[];return h.status==="fulfilled"?k.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?k.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),wS(k)}}:i:u,Wx=()=>{let u=B.getInlineMessageFields?.();return u&&u.contentSegments.some(x=>x.kind==="mention")?u.contentSegments:void 0},Ga=!1,Hx=async i=>{let u=B.value.trim(),h=bt?.hasAttachments()??!1,x=u?await(Qt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(x?.kind==="action"){B.value="",B.style.height="auto",Ka(),Qt?.clear();return}let k=Qt?.collectForSubmit()??null,W=x?.kind==="server"?x.mentions:null,z=Ix(k,W),U=x?.kind==="prompt"?x.sendText:u,j=!!k&&k.refs.length>0;if(!U&&!h&&!j&&!W)return;Hm();let Y;h&&(Y=[],Y.push(...bt.getContentParts()),U&&Y.push(Oo(U)));let pe=x?.kind==="prompt"?void 0:Wx();B.value="",B.style.height="auto",Ka(),q.sendMessage(U,{contentParts:Y,mentions:z??void 0,contentSegments:pe,viaVoice:i?.viaVoice}),h&&bt.clearAttachments(),k&&Qt?.clear()},Hc=async i=>{if(!Ga){Ga=!0;try{await Hx(i)}finally{Ga=!1}}},li=i=>{if(i.preventDefault(),q.isStreaming()){q.cancel(),_e?.reset(),Ae?.update();return}Ga||Hc()},Bx=()=>o.features?.composerHistory!==!1,Bc={...Su},Dc=!1,Ka=()=>{Bc={...Su}},Dx=()=>q.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Fx=i=>{if(!B)return;Dc=!0,B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),Dc=!1;let u=B.value.length;B.setSelectionRange(u,u)},Ox=i=>{Dc||(i.isComposing||Qt?.handleInput(i.inputType??void 0),Ka())},Nx=i=>{if(B&&!(!i.isComposing&&Qt?.handleKeydown(i))){if(Bx()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let u=B.selectionStart===0&&B.selectionEnd===0,h=Gh({direction:i.key==="ArrowUp"?"up":"down",history:Dx(),currentValue:B.value,atStart:u,state:Bc});if(Bc=h.state,h.handled){i.preventDefault(),h.value!==void 0&&Fx(h.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(q.isStreaming()){i.preventDefault();return}if(Ga){i.preventDefault();return}Ka(),i.preventDefault(),y.click()}}},Bm=i=>{i.key!=="Escape"||i.isComposing||q.isStreaming()&&i.composedPath().includes(be)&&(q.cancel(),_e?.reset(),Ae?.update(),Ka(),i.preventDefault(),i.stopImmediatePropagation())},_x=async i=>{if(o.attachments?.enabled!==!0||!bt)return;let u=bS(i.clipboardData);u.length!==0&&(i.preventDefault(),await bt.handleFiles(u))},Cn=null,qn=!1,Gr=null,vt=null,Dm=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ci=(i="user")=>{if(qn||q.isStreaming())return;let u=Dm();if(!u)return;Cn=new u;let x=(o.voiceRecognition??{}).pauseDuration??2e3;Cn.continuous=!0,Cn.interimResults=!0,Cn.lang="en-US";let k=B.value;Cn.onresult=W=>{let z="",U="";for(let Y=0;Y<W.results.length;Y++){let pe=W.results[Y],le=pe[0].transcript;pe.isFinal?z+=le+" ":U=le}let j=k+z+U;B.value=j,Gr&&clearTimeout(Gr),(z||U)&&(Gr=window.setTimeout(()=>{B.value.trim()&&Cn&&qn&&(So(),Hc({viaVoice:!0}))},x))},Cn.onerror=W=>{W.error!=="no-speech"&&So()},Cn.onend=()=>{if(qn){let W=B.value.trim();W&&W!==k.trim()&&Hc({viaVoice:!0}),So()}};try{if(Cn.start(),qn=!0,je.active=!0,i!=="system"&&(je.manuallyDeactivated=!1),eo(i),Wn(),te){let W=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:W.iconName??"mic",iconSize:parseFloat(W.iconSize??o.sendButton?.size??"40")||24};let z=W.recordingBackgroundColor,U=W.recordingIconColor,j=W.recordingBorderColor;if(te.classList.add("persona-voice-recording"),te.style.backgroundColor=z??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let Y=te.querySelector("svg");Y&&Y.setAttribute("stroke",U)}j&&(te.style.borderColor=j),te.setAttribute("aria-label","Stop voice recognition")}}catch{So("system")}},So=(i="user")=>{if(qn){if(qn=!1,Gr&&(clearTimeout(Gr),Gr=null),Cn){try{Cn.stop()}catch{}Cn=null}if(je.active=!1,eo(i),Wn(),te){if(te.classList.remove("persona-voice-recording"),vt){te.style.backgroundColor=vt.backgroundColor,te.style.color=vt.color,te.style.borderColor=vt.borderColor;let u=te.querySelector("svg");u&&u.setAttribute("stroke",vt.color||"currentColor"),vt=null}te.setAttribute("aria-label","Start voice recognition")}}},Ux=(i,u)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=i?.provider?.type==="runtype",k=i?.provider?.type==="custom";if(!(h||x||k))return null;let z=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button";let j=i?.tooltipText??"Start voice recognition";U.setAttribute("aria-label",j);let Y=i?.iconName??"mic",pe=u?.size??"40px",le=i?.iconSize??pe,ye=parseFloat(le)||24,Ge=i?.backgroundColor??u?.backgroundColor,ht=i?.iconColor??u?.textColor;U.style.width=le,U.style.height=le,U.style.minWidth=le,U.style.minHeight=le,U.style.fontSize="18px",U.style.lineHeight="1",ht?U.style.color=ht:U.style.color="var(--persona-text, #111827)";let un=ae(Y,ye,ht||"currentColor",1.5);un?U.appendChild(un):U.textContent="\u{1F3A4}",Ge?U.style.backgroundColor=Ge:U.style.backgroundColor="",i?.borderWidth&&(U.style.borderWidth=i.borderWidth,U.style.borderStyle="solid"),i?.borderColor&&(U.style.borderColor=i.borderColor),i?.paddingX&&(U.style.paddingLeft=i.paddingX,U.style.paddingRight=i.paddingX),i?.paddingY&&(U.style.paddingTop=i.paddingY,U.style.paddingBottom=i.paddingY),z.appendChild(U);let Mt=i?.showTooltip??!1;return qt({anchor:U,trigger:z,text:()=>U.getAttribute("aria-label")??j,enabled:Mt}),{micButton:U,micButtonWrapper:z}},Fc=()=>{if(!te||vt)return;let i=o.voiceRecognition??{};vt={backgroundColor:te.style.backgroundColor,color:te.style.color,borderColor:te.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Oc=(i,u)=>{if(!te)return;let h=te.querySelector("svg");h&&h.remove();let x=vt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),k=ae(i,x,u,1.5);k&&te.appendChild(k)},di=()=>{te&&te.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Kr=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=i.recordingBackgroundColor,h=i.recordingIconColor,x=i.recordingBorderColor;if(di(),te.classList.add("persona-voice-recording"),te.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",te.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let k=te.querySelector("svg");k&&k.setAttribute("stroke",h)}x&&(te.style.borderColor=x),te.setAttribute("aria-label","Stop voice recognition")},qx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=i.processingIconName??"loader",x=i.processingIconColor??vt?.color??"",k=i.processingBackgroundColor??vt?.backgroundColor??"",W=i.processingBorderColor??vt?.borderColor??"";di(),te.classList.add("persona-voice-processing"),te.style.backgroundColor=k,te.style.borderColor=W;let z=x||"currentColor";te.style.color=z,Oc(h,z),te.setAttribute("aria-label","Processing voice input"),u==="none"&&(te.style.cursor="default")},Vx=()=>{if(!te)return;Fc();let i=o.voiceRecognition??{},u=q.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",x=i.speakingIconName??h,k=i.speakingIconColor??(u==="barge-in"?i.recordingIconColor??vt?.color??"":vt?.color??""),W=i.speakingBackgroundColor??(u==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":vt?.backgroundColor??""),z=i.speakingBorderColor??(u==="barge-in"?i.recordingBorderColor??"":vt?.borderColor??"");di(),te.classList.add("persona-voice-speaking"),te.style.backgroundColor=W,te.style.borderColor=z;let U=k||"currentColor";te.style.color=U,Oc(x,U);let j=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";te.setAttribute("aria-label",j),u==="none"&&(te.style.cursor="default"),u==="barge-in"&&te.classList.add("persona-voice-recording")},no=()=>{te&&(di(),vt&&(te.style.backgroundColor=vt.backgroundColor??"",te.style.color=vt.color??"",te.style.borderColor=vt.borderColor??"",Oc(vt.iconName,vt.color||"currentColor"),vt=null),te.style.cursor="",te.setAttribute("aria-label","Start voice recognition"))},Xr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=q.getVoiceStatus(),u=q.getVoiceInterruptionMode();if(u==="none"&&(i==="processing"||i==="speaking"))return;if(u==="cancel"&&(i==="processing"||i==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()});return}q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),je.manuallyDeactivated=!q.isVoiceActive(),Wn(),eo("user"),q.isVoiceActive()?Kr():no()});return}if(qn){let i=B.value.trim();je.manuallyDeactivated=!0,Wn(),So("user"),i&&(B.value="",B.style.height="auto",q.sendMessage(i))}else je.manuallyDeactivated=!1,Wn(),ci("user")};Pf=Xr,te&&(te.addEventListener("click",Xr),De.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),no()):So("system"),te&&te.removeEventListener("click",Xr)}));let zx=c.on("assistant:complete",()=>{cm&&(je.active||je.manuallyDeactivated||cm==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{!je.active&&!je.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("auto"),q.isVoiceActive()&&Kr()}):ci("auto"))},600))});De.push(zx);let $x=c.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});De.push($x);let Fm=()=>{lt(!J,"user")},kt=null,Yt=null;if(P&&!Q()){let{instance:i,element:u}=ju({config:o,plugins:a,onToggle:Fm});kt=i,i||(Yt=u)}kt?e.appendChild(kt.element):Yt&&e.appendChild(Yt),$a(),_r(),Lc(),kc(),si(q.isStreaming()),hm()||(cn()==="follow"?wo(!0):gm()),lx(),F&&(!P||Q()?setTimeout(()=>wc(),0):J&&setTimeout(()=>wc(),200));let Xa=()=>{if(Q()){Yo(),$a();return}let i=St(o),u=o.launcher?.sidebarMode??!1,h=e.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,k=o.launcher?.mobileBreakpoint??640,W=h.innerWidth<=k,z=x&&W&&P;try{if(z){Zo(),Ba=Xs();return}let U=!1;G&&(G=!1,Zo(),U=!0);let j=Xs();if(!U&&j!==Ba&&(Zo(),U=!0),Ba=j,U&&lc(),!P&&!i){he.style.height="",he.style.width="";return}if(!u&&!i){let pe=o?.launcher?.width??o?.launcherWidth??mn;he.style.width=pe,he.style.maxWidth=pe}Ks(),Kf()}finally{if(Yo(),$a(),J&&P){let j=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),Y=o.launcher?.sidebarMode??!1,pe=o.launcher?.mobileFullscreen??!0,le=St(o)&&pe&&j,ye=Y||pe&&j&&P||le;if(ye&&!Un){let Ge=e.getRootNode(),ht=Ge instanceof ShadowRoot?Ge.host:e.closest(".persona-host");ht&&!_n&&(_n=Pu(ht,o.launcher?.zIndex??Ut)),Un=Ru(e.ownerDocument)}else ye||(_n?.(),_n=null,Un?.(),Un=null)}}};Xa();let Om=e.ownerDocument.defaultView??window;if(Om.addEventListener("resize",Xa),De.push(()=>Om.removeEventListener("resize",Xa)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Yo()});i.observe(we),De.push(()=>i.disconnect())}pn=re.scrollTop;let Nm=jn(re),_m=()=>{let i=re.scrollTop,u=jn(re),h=u<Nm;if(Nm=u,!ho()){pn=i,Vt();return}let{action:x,nextLastScrollTop:k}=bl({following:dn.isFollowing(),currentScrollTop:i,lastScrollTop:pn,nearBottom:uo(re,Yn),userScrollThreshold:rx,isAutoScrolling:on||Qs||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=k,x==="resume"){ni()||Co();return}x==="pause"&&Na()};if(re.addEventListener("scroll",_m,{passive:!0}),De.push(()=>re.removeEventListener("scroll",_m)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{gx(),Gc(xe)});i.observe(xe),i.observe(re),De.push(()=>i.disconnect())}let Um=()=>{ho()&&dn.isFollowing()&&ni()&&Na()},qm=re.ownerDocument;qm.addEventListener("selectionchange",Um),De.push(()=>{qm.removeEventListener("selectionchange",Um)});let jx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Vm=i=>{jx.has(i.key)&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())},zm=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(cr(),Mf()&&ho()&&dn.isFollowing()&&Na())};re.addEventListener("keydown",Vm),re.addEventListener("focusin",zm),De.push(()=>{re.removeEventListener("keydown",Vm),re.removeEventListener("focusin",zm)});let $m=i=>{if(i.deltaY!==0&&cr(),!ho())return;let u=xl({following:dn.isFollowing(),deltaY:i.deltaY,nearBottom:uo(re,Yn),resumeWhenNearBottom:!0});u==="pause"?Na():u==="resume"&&!ni()&&Co()};re.addEventListener("wheel",$m,{passive:!0}),re.addEventListener("touchmove",cr,{passive:!0}),re.addEventListener("pointerdown",cr,{passive:!0}),De.push(()=>{re.removeEventListener("touchmove",cr),re.removeEventListener("pointerdown",cr)}),De.push(()=>re.removeEventListener("wheel",$m)),Pt.addEventListener("click",()=>{_a(),re.scrollTop=re.scrollHeight,pn=re.scrollTop,Co(),wo(!0),Vt()}),De.push(()=>Pt.remove()),De.push(()=>{um(),_a()});let jm=()=>{de&&(or&&(de.removeEventListener("click",or),or=null),Z()?(de.style.display="",or=()=>{lt(!1,"user")},de.addEventListener("click",or)):de.style.display="none")};jm(),(()=>{let{clearChatButton:i}=Te;i&&i.addEventListener("click",()=>{q.clearMessages(),ar.clear(),Co(),Wo(Te.composerOverlay);try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()})})(),H&&H.addEventListener("submit",li);let Gm=[["keydown",Nx],["input",Ox],["paste",_x],["focus",Qb]],Nc=i=>{if(i)for(let[u,h]of Gm)i.addEventListener(u,h)},_c=i=>{if(i)for(let[u,h]of Gm)i.removeEventListener(u,h)};Nc(B);let Km=()=>{Qt?.onComposerSwap((i,u)=>{_c(u),B=i,Nc(i)})};Km();let Uc=!1;function Gx(){if(!Uc){Uc=!0;try{let i=B?.value??"",u=we.ownerDocument??document,h=B?u.activeElement===B:!1;_c(B),H?.removeEventListener("submit",li),te?.removeEventListener("click",Xr),Qt?.destroy(),Qt=null;let x=null,k=()=>(x=Q()?Wl({config:o}):Lr({config:o}),x.footer),W=Wf(k)??k();et.replaceComposer(W),we=et.composer.footer;let z=x!==null&&W===x.footer;rc=!z,Us=z?x.setSendButtonMode:()=>{},If(we),Bf(we),Df(),Ff(),Of(),Km(),H&&H.addEventListener("submit",li),Nc(B),te?.addEventListener("click",Xr);let U=nr.indexOf(Qn);Qn.destroy(),Qn=Es(I),U>=0&&(nr[U]=Qn),B&&(B.value=i),Lc(),_r(),si(q.isStreaming()),Zo(),Yo(),h&&B?.focus()}finally{Uc=!1}}}let Xm=e.ownerDocument??document;Xm.addEventListener("keydown",Bm,!0);let Jm="persona-attachment-drop-active",Ja=0,qc=()=>{Ja=0,be.classList.remove(Jm)},Jr=()=>o.attachments?.enabled===!0&&bt!==null,Qm=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja++,Ja===1&&be.classList.add(Jm))},Ym=i=>{!Xl(i.dataTransfer)||!Jr()||(Ja--,Ja<=0&&qc())},Zm=i=>{!Xl(i.dataTransfer)||!Jr()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},eg=i=>{if(!Xl(i.dataTransfer)||!Jr())return;i.preventDefault(),i.stopPropagation(),qc();let u=Array.from(i.dataTransfer.files??[]);u.length!==0&&bt.handleFiles(u)},Mo=!0;be.addEventListener("dragenter",Qm,Mo),be.addEventListener("dragleave",Ym,Mo),e.addEventListener("dragover",Zm,Mo),e.addEventListener("drop",eg,Mo);let pi=e.ownerDocument,tg=i=>{Jr()&&i.preventDefault()},ng=i=>{Jr()&&i.preventDefault()};pi.addEventListener("dragover",tg),pi.addEventListener("drop",ng),De.push(()=>{H&&H.removeEventListener("submit",li),_c(B),Xm.removeEventListener("keydown",Bm,!0),Qt?.destroy()}),De.push(()=>{be.removeEventListener("dragenter",Qm,Mo),be.removeEventListener("dragleave",Ym,Mo),e.removeEventListener("dragover",Zm,Mo),e.removeEventListener("drop",eg,Mo),pi.removeEventListener("dragover",tg),pi.removeEventListener("drop",ng),qc()}),De.push(()=>{q.cancel()}),kt?De.push(()=>{kt?.destroy()}):Yt&&De.push(()=>{Yt?.remove()});let Rt={update(i){let u=o.toolCall,h=o.messageActions,x=o.layout?.messages,k=o.colorScheme,W=o.loadingIndicator,z=o.iterationDisplay,U=o.features?.showReasoning,j=o.features?.showToolCalls,Y=o.features?.toolCallDisplay,pe=o.features?.reasoningDisplay,le=o.features?.streamAnimation?.type;o=ql({...o,features:r},i),r=o.features,o=Hs(o),dc(),Sr(e,o),Is(e,o),Ws(e,o),Jn(),o.colorScheme!==k&&Xf();let ye=Bs.getForInstance(o.plugins);a.length=0,a.push(...ye),P=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,ue=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,Se=o.features?.scrollToBottom??{};let Ge=cn();Ce=o.features?.scrollBehavior??{},Ge!==cn()&&(_a(),Co()),lm(),Lf(),Vt();let ht=me;if(me=o.features?.showEventStreamToggle??!1,me&&!ht){if(Ne||(Je=new Ps(ut),Ne=new Ls(Qe,Je),_e=_e??new Rs,Je.open().then(()=>Ne?.restore()).catch(()=>{}),q.setSSEEventCallback((se,$e)=>{o.onSSEEvent?.(se,$e),_e?.processEvent(se,$e),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:se,timestamp:Date.now(),payload:JSON.stringify($e)})})),!Ye&&We){let se=o.features?.eventStream?.classNames,$e="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",$e),Ye.style.width="28px",Ye.style.height="28px",Ye.style.color=Xt.actionIconColor,Ye.type="button",Ye.setAttribute("aria-label","Event Stream"),Ye.title="Event Stream";let mt=ae("activity","18px","currentColor",1.5);mt&&Ye.appendChild(mt);let Ze=Te.clearChatButtonWrapper,ot=Te.closeButtonWrapper,Gt=Ze||ot;Gt&&Gt.parentNode===We?We.insertBefore(Ye,Gt):We.appendChild(Ye),Ye.addEventListener("click",()=>{Me?Ia():nc()})}}else!me&&ht&&(Ia(),Ye&&(Ye.remove(),Ye=null),Ne?.clear(),Je?.destroy(),Ne=null,Je=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&kt&&(kt.destroy(),kt=null),o.launcher?.enabled===!1&&Yt&&(Yt.remove(),Yt=null),o.launcher?.enabled!==!1&&!kt&&!Yt){let{instance:se,element:$e}=ju({config:o,plugins:a,onToggle:Fm});kt=se,se||(Yt=$e),e.appendChild($e)}kt&&kt.update(o),ze&&o.launcher?.title!==void 0&&(ze.textContent=o.launcher.title),Ue&&o.launcher?.subtitle!==void 0&&(Ue.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==E&&We){let se=ct?ya(o,ct,{showClose:Z(),onClose:()=>lt(!1,"user")}):fo({config:o,showClose:Z(),onClose:()=>lt(!1,"user")});et.replaceHeader(se),We=et.header.element,Pe=et.header.iconHolder,ze=et.header.headerTitle,Ue=et.header.headerSubtitle,de=et.header.closeButton,E=ct?.layout}else if(ct){if(Pe&&(Pe.style.display=ct.showIcon===!1?"none":""),ze&&(ze.style.display=ct.showTitle===!1?"none":""),Ue&&(Ue.style.display=ct.showSubtitle===!1?"none":""),de){let se=Z()&&ct.showCloseButton!==!1;de.style.display=se?"":"none"}if(Te.clearChatButtonWrapper){let se=ct.showClearChat;if(se!==void 0){Te.clearChatButtonWrapper.style.display=se?"":"none";let{closeButtonWrapper:$e}=Te;$e&&!$e.classList.contains("persona-absolute")&&(se?$e.classList.remove("persona-ml-auto"):$e.classList.add("persona-ml-auto"))}}}let Mt=o.layout?.showHeader!==!1;We&&(We.style.display=Mt?"":"none");let It=o.layout?.showFooter!==!1;we&&(we.style.display=It?"":"none"),Yo(),Vt(),P!==$?P?lt(R,"auto"):(J=!0,$a()):R!==O&&lt(R,"auto"),O=R,$=P,Xa(),jm();let Fe=JSON.stringify(o.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(o.messageActions)!==JSON.stringify(h),At=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),dt=o.loadingIndicator?.render!==W?.render||o.loadingIndicator?.renderIdle!==W?.renderIdle||o.loadingIndicator?.showBubble!==W?.showBubble,Ot=o.iterationDisplay!==z,pt=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(j??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(Y)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(pe);(Fe||Ee||At||dt||Ot||pt)&&q&&(uc++,Ua(xe,q.getMessages(),ie));let Wt=o.features?.streamAnimation?.type;if(Wt!==le&&Wt&&Wt!=="none"){let se=ha(Wt,o.features?.streamAnimation?.plugins);se&&Al(se,e)}let Ie=o.launcher??{},Oe=Ie.headerIconHidden??!1,zt=o.layout?.header?.showIcon,$t=Oe||zt===!1,Ct=Ie.headerIconName,st=Ie.headerIconSize??"48px";if(Pe){let se=be.querySelector(".persona-border-b-persona-divider"),$e=se?.querySelector(".persona-flex-col");if($t)Pe.style.display="none",se&&$e&&!se.contains($e)&&se.insertBefore($e,se.firstChild);else{if(Pe.style.display="",Pe.style.height=st,Pe.style.width=st,se&&$e&&(se.contains(Pe)?Pe.nextSibling!==$e&&(Pe.remove(),se.insertBefore(Pe,$e)):se.insertBefore(Pe,$e)),Ct){let Ze=parseFloat(st)||24,ot=ae(Ct,Ze*.6,"currentColor",1);ot?Pe.replaceChildren(ot):Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let Ze=Pe.querySelector("img");if(Ze)Ze.src=Ie.iconUrl,Ze.style.height=st,Ze.style.width=st;else{let ot=document.createElement("img");ot.src=Ie.iconUrl,ot.alt="",ot.className="persona-rounded-xl persona-object-cover",ot.style.height=st,ot.style.width=st,Pe.replaceChildren(ot)}}else{let Ze=Pe.querySelector("svg"),ot=Pe.querySelector("img");(Ze||ot)&&Pe.replaceChildren(),Pe.textContent=Ie.agentIconText??"\u{1F4AC}"}let mt=Pe.querySelector("img");mt&&(mt.style.height=st,mt.style.width=st)}}let ft=o.layout?.header?.showTitle,Xe=o.layout?.header?.showSubtitle;if(ze&&(ze.style.display=ft===!1?"none":""),Ue&&(Ue.style.display=Xe===!1?"none":""),de){let se=Z()&&o.layout?.header?.showCloseButton!==!1;de.style.display=se?"":"none";let $e=Ie.closeButtonSize??"32px",mt=Ie.closeButtonPlacement??"inline";de.style.height=$e,de.style.width=$e;let{closeButtonWrapper:Ze}=Te,ot=mt==="top-right",Gt=Ze?.classList.contains("persona-absolute");if(Ze&&ot!==Gt)if(Ze.remove(),ot)Ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",be.style.position="relative",be.appendChild(Ze);else{let Eo=Ie.clearChat?.placement??"inline",Za=Ie.clearChat?.enabled??!0;Ze.className=Za&&Eo==="inline"?"":"persona-ml-auto";let og=be.querySelector(".persona-border-b-persona-divider");og&&og.appendChild(Ze)}if(de.style.color=Ie.closeButtonColor||Xt.actionIconColor,Ie.closeButtonBackgroundColor?(de.style.backgroundColor=Ie.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let Eo=Ie.closeButtonBorderWidth||"0px",Za=Ie.closeButtonBorderColor||"transparent";de.style.border=`${Eo} solid ${Za}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(de.style.borderRadius=Ie.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(de.style.paddingLeft=Ie.closeButtonPaddingX,de.style.paddingRight=Ie.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),Ie.closeButtonPaddingY?(de.style.paddingTop=Ie.closeButtonPaddingY,de.style.paddingBottom=Ie.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let fn=Ie.closeButtonIconName??"x",Hn=Ie.closeButtonIconText??"\xD7";de.innerHTML="";let Nt=ae(fn,"28px","currentColor",1);Nt?(Nt.style.display="block",de.appendChild(Nt)):de.textContent=Hn;let Kt=Ie.closeButtonTooltipText??"Close chat",ro=Ie.closeButtonShowTooltip??!0;de.setAttribute("aria-label",Kt),Ze&&qt({anchor:de,trigger:Ze,text:()=>de?.getAttribute("aria-label")??Kt,enabled:ro})}let{clearChatButton:He,clearChatButtonWrapper:yt}=Te;if(He){let se=Ie.clearChat??{},$e=se.enabled??!0,mt=o.layout?.header?.showClearChat,Ze=mt!==void 0?mt:$e,ot=se.placement??"inline";if(yt){yt.style.display=Ze?"":"none";let{closeButtonWrapper:Gt}=Te;!Q()&&Gt&&!Gt.classList.contains("persona-absolute")&&(Ze?Gt.classList.remove("persona-ml-auto"):Gt.classList.add("persona-ml-auto"));let fn=ot==="top-right",Hn=yt.classList.contains("persona-absolute");if(!Q()&&fn!==Hn&&Ze){if(yt.remove(),fn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",be.style.position="relative",be.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Kt=be.querySelector(".persona-border-b-persona-divider"),ro=Te.closeButtonWrapper;Kt&&ro&&ro.parentElement===Kt?Kt.insertBefore(yt,ro):Kt&&Kt.appendChild(yt)}let Nt=Te.closeButtonWrapper;Nt&&!Nt.classList.contains("persona-absolute")&&(fn?Nt.classList.add("persona-ml-auto"):Nt.classList.remove("persona-ml-auto"))}}if(Ze){if(!Q()){let Eo=se.size??"32px";He.style.height=Eo,He.style.width=Eo}let Gt=se.iconName??"refresh-cw",fn=se.iconColor??"";He.style.color=fn||Xt.actionIconColor,He.innerHTML="";let Hn=Q()?"14px":"20px",Nt=ae(Gt,Hn,"currentColor",1);if(Nt&&(Nt.style.display="block",He.appendChild(Nt)),se.backgroundColor?(He.style.backgroundColor=se.backgroundColor,He.classList.remove("hover:persona-bg-gray-100")):(He.style.backgroundColor="",He.classList.add("hover:persona-bg-gray-100")),se.borderWidth||se.borderColor){let Eo=se.borderWidth||"0px",Za=se.borderColor||"transparent";He.style.border=`${Eo} solid ${Za}`,He.classList.remove("persona-border-none")}else He.style.border="",He.classList.add("persona-border-none");se.borderRadius?(He.style.borderRadius=se.borderRadius,He.classList.remove("persona-rounded-full")):(He.style.borderRadius="",He.classList.add("persona-rounded-full")),se.paddingX?(He.style.paddingLeft=se.paddingX,He.style.paddingRight=se.paddingX):(He.style.paddingLeft="",He.style.paddingRight=""),se.paddingY?(He.style.paddingTop=se.paddingY,He.style.paddingBottom=se.paddingY):(He.style.paddingTop="",He.style.paddingBottom="");let Kt=se.tooltipText??"Clear chat",ro=se.showTooltip??!0;He.setAttribute("aria-label",Kt),yt&&qt({anchor:He,trigger:yt,text:()=>He?.getAttribute("aria-label")??Kt,enabled:ro})}}let jt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ds],An=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Dr.message,Dr.messageAndClick];M=Fs({parsers:jt,handlers:An,getSessionMetadata:L,updateSessionMetadata:A,emit:c.emit,documentRef:typeof document<"u"?document:null}),ie=ib(o,M,ge),q.updateConfig(o),Ua(xe,q.getMessages(),ie),_r(),Lc(),kx(),si(q.isStreaming());let Qa=o.voiceRecognition?.enabled===!0,ui=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if(Qa&&(ui||Lt))if(!te||!bn){let se=Ux(o.voiceRecognition,o.sendButton);se&&(te=se.micButton,bn=se.micButtonWrapper,wt.insertBefore(bn,D),te.addEventListener("click",Xr),te.disabled=q.isStreaming())}else{let se=o.voiceRecognition??{},$e=o.sendButton??{},mt=se.iconName??"mic",Ze=$e.size??"40px",ot=se.iconSize??Ze,Gt=parseFloat(ot)||24;te.style.width=ot,te.style.height=ot,te.style.minWidth=ot,te.style.minHeight=ot;let fn=se.iconColor??$e.textColor;te.innerHTML="";let Hn=ae(mt,Gt,fn||"currentColor",1.5);Hn?te.appendChild(Hn):te.textContent="\u{1F3A4}";let Nt=se.backgroundColor??$e.backgroundColor;Nt?te.style.backgroundColor=Nt:te.style.backgroundColor="",fn?te.style.color=fn:te.style.color="var(--persona-text, #111827)",se.borderWidth?(te.style.borderWidth=se.borderWidth,te.style.borderStyle="solid"):(te.style.borderWidth="",te.style.borderStyle=""),se.borderColor?te.style.borderColor=se.borderColor:te.style.borderColor="",se.paddingX?(te.style.paddingLeft=se.paddingX,te.style.paddingRight=se.paddingX):(te.style.paddingLeft="",te.style.paddingRight=""),se.paddingY?(te.style.paddingTop=se.paddingY,te.style.paddingBottom=se.paddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Kt=se.tooltipText??"Start voice recognition",ro=se.showTooltip??!1;te.setAttribute("aria-label",Kt),bn&&qt({anchor:te,trigger:bn,text:()=>te?.getAttribute("aria-label")??Kt,enabled:ro}),bn.style.display="",te.disabled=q.isStreaming()}else te&&bn&&(bn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():qn&&So());if(o.attachments?.enabled===!0){if(!xn||!it){let se=o.attachments??{},mt=(o.sendButton??{}).size??"40px";Ln||(Ln=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ln.style.display="none",H.insertBefore(Ln,B)),Et||(Et=document.createElement("input"),Et.type="file",Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1,Et.style.display="none",Et.setAttribute("aria-label","Attach files"),H.insertBefore(Et,B)),xn=v("div","persona-send-button-wrapper"),it=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",se.buttonTooltipText??"Attach file");let Ze=se.buttonIconName??"paperclip",ot=mt,Gt=parseFloat(ot)||40,fn=Math.round(Gt*.6);it.style.width=ot,it.style.height=ot,it.style.minWidth=ot,it.style.minHeight=ot,it.style.fontSize="18px",it.style.lineHeight="1";let Hn=ae(Ze,fn,"currentColor",1.5);Hn?it.appendChild(Hn):it.textContent="\u{1F4CE}",it.addEventListener("click",Kt=>{Kt.preventDefault(),Et?.click()}),xn.appendChild(it);let Nt=se.buttonTooltipText??"Attach file";qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??Nt}),yn?yn.append(xn):H.appendChild(xn),!bt&&Et&&Ln&&(bt=Ar.fromConfig(se),bt.setPreviewsContainer(Ln),Et.addEventListener("change",async()=>{bt&&Et?.files&&(await bt.handleFileSelect(Et.files),Et.value="")}))}else{xn.style.display="";let se=o.attachments??{};Et&&(Et.accept=(se.allowedTypes??co).join(","),Et.multiple=(se.maxFiles??4)>1),bt&&bt.updateConfig({allowedTypes:se.allowedTypes,maxFileSize:se.maxFileSize,maxFiles:se.maxFiles})}if(be.querySelector(".persona-attachment-drop-overlay")?.remove(),be.appendChild(lb(o.attachments?.dropOverlay)),it){let se=o.attachments??{},$e=se.buttonTooltipText??"Attach file";it.setAttribute("aria-label",$e),it.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,Ze=ae(se.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);Ze?it.appendChild(Ze):it.textContent="\u{1F4CE}",xn&&qt({anchor:it,trigger:xn,text:()=>it?.getAttribute("aria-label")??$e})}}else xn&&(xn.style.display="none"),bt&&bt.clearAttachments(),be.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},Ya=Ft.useIcon??!1,mi=Ft.iconText??"\u2191",Qr=Ft.iconName,gi=Ft.tooltipText??"Send message",Vc=Ft.showTooltip??!1,mr=Ft.size??"40px",oo=Ft.backgroundColor,gr=Ft.textColor;if(Ya){if(y.style.width=mr,y.style.height=mr,y.style.minWidth=mr,y.style.minHeight=mr,y.style.fontSize="18px",y.style.lineHeight="1",gr?y.style.color=gr:y.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(y.innerHTML="",Qr){let se=parseFloat(mr)||24,$e=gr?.trim()||"currentColor",mt=ae(Qr,se,$e,2);mt?y.appendChild(mt):y.textContent=mi}else y.textContent=mi;y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-primary")):(y.style.backgroundColor="",y.classList.add("persona-bg-persona-primary"))}else y.textContent=o.copy?.sendButtonLabel??"Send",y.style.width="",y.style.height="",y.style.minWidth="",y.style.minHeight="",y.style.fontSize="",y.style.lineHeight="",y.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",oo?(y.style.backgroundColor=oo,y.classList.remove("persona-bg-persona-accent")):y.classList.add("persona-bg-persona-accent"),gr?y.style.color=gr:y.classList.add("persona-text-white");Ft.borderWidth?(y.style.borderWidth=Ft.borderWidth,y.style.borderStyle="solid"):(y.style.borderWidth="",y.style.borderStyle=""),Ft.borderColor?y.style.borderColor=Ft.borderColor:y.style.borderColor="",Ft.paddingX?(y.style.paddingLeft=Ft.paddingX,y.style.paddingRight=Ft.paddingX):(y.style.paddingLeft="",y.style.paddingRight=""),Ft.paddingY?(y.style.paddingTop=Ft.paddingY,y.style.paddingBottom=Ft.paddingY):(y.style.paddingTop="",y.style.paddingBottom=""),q.isStreaming()||y.setAttribute("aria-label",gi),D&&qt({anchor:y,trigger:D,text:()=>y.getAttribute("aria-label")??gi,enabled:Vc});let Yr=qo(o,Q());pc(),Yr?(xe.style.maxWidth=Yr,xe.style.marginLeft="auto",xe.style.marginRight="auto",xe.style.width="100%",X.style.maxWidth=Yr,X.style.marginLeft="auto",X.style.marginRight="auto",X.style.width="100%",H&&(H.style.maxWidth=Yr,H.style.marginLeft="auto",H.style.marginRight="auto"),I&&(I.style.maxWidth=Yr,I.style.marginLeft="auto",I.style.marginRight="auto"),N.style.maxWidth=Yr,N.style.marginLeft="auto",N.style.marginRight="auto"):(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight="",xe.style.width="",X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight="",X.style.width="",H&&(H.style.maxWidth="",H.style.marginLeft="",H.style.marginRight=""),I&&(I.style.maxWidth="",I.style.marginLeft="",I.style.marginRight=""),N.style.maxWidth="",N.style.marginLeft="",N.style.marginRight="");let To=o.statusIndicator??{},Kx=To.visible??!0;if(N.style.display=Kx?"":"none",q){let se=q.getStatus();En(N,(mt=>mt==="idle"?To.idleText??Ht.idle:mt==="connecting"?To.connectingText??Ht.connecting:mt==="connected"?To.connectedText??Ht.connected:mt==="error"?To.errorText??Ht.error:Ht[mt])(se),To,se)}N.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Xx=To.align==="left"?"persona-text-left":To.align==="center"?"persona-text-center":"persona-text-right";N.classList.add(Xx)},open(){Z()&&lt(!0,"api")},close(){Z()&&lt(!1,"api")},toggle(){Z()&&lt(!J,"api")},reconnect(){q.reconnectNow()},clearChat(){Xn=!1,q.clearMessages(),ar.clear(),Co();try{localStorage.removeItem(Ta),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ta}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Ta)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 i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),g?.clear&&hc(()=>g.clear(),"[AgentWidget] Failed to clear storage adapter:"),m={},M.syncFromMetadata(),Ne?.clear(),_e?.reset(),Ae?.update()},setMessage(i){return!B||q.isStreaming()?!1:(!J&&Z()&&lt(!0,"system"),B.value=i,B.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(q.isStreaming())return!1;let u=i?.trim()||B.value.trim();return u?(!J&&Z()&&lt(!0,"system"),B.value="",B.style.height="auto",q.sendMessage(u),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!J&&Z()&&lt(!0,"system"),je.manuallyDeactivated=!1,Wn(),q.toggleVoice().then(()=>{je.active=q.isVoiceActive(),eo("user"),q.isVoiceActive()&&Kr()})),!0):qn?!0:Dm()?(!J&&Z()&&lt(!0,"system"),je.manuallyDeactivated=!1,Wn(),ci("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Wn(),eo("user"),no()}),!0):!1:qn?(je.manuallyDeactivated=!0,Wn(),So("user"),!0):!1},injectMessage(i){return!J&&Z()&&lt(!0,"system"),q.injectMessage(i)},injectAssistantMessage(i){!J&&Z()&&lt(!0,"system");let u=q.injectAssistantMessage(i);return fe&&(fe=!1,ne&&(clearTimeout(ne),ne=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),u},injectUserMessage(i){return!J&&Z()&&lt(!0,"system"),q.injectUserMessage(i)},injectSystemMessage(i){return!J&&Z()&&lt(!0,"system"),q.injectSystemMessage(i)},injectMessageBatch(i){return!J&&Z()&&lt(!0,"system"),q.injectMessageBatch(i)},injectComponentDirective(i){return!J&&Z()&&lt(!0,"system"),q.injectComponentDirective(i)},injectTestMessage(i){!J&&Z()&&lt(!0,"system"),q.injectTestEvent(i)},async connectStream(i,u){return q.connectStream(i,u)},__pushEventStreamEvent(i){Ne&&(_e?.processEvent(i.type,i.payload),Ne.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!me||!Ne||nc()},hideEventStream(){Me&&Ia()},isEventStreamVisible(){return Me},showArtifacts(){tn(o)&&(Xn=!1,Fr=!0,Jn(),Ke?.setMobileOpen(!0))},hideArtifacts(){tn(o)&&(Xn=!0,Jn())},upsertArtifact(i){return tn(o)?(zn(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Xn=!1,Fr=!0),q.upsertArtifact(i)):null},selectArtifact(i){tn(o)&&q.selectArtifact(i)},clearArtifacts(){tn(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return P&&!J&&!Q()||!B?!1:(B.focus(),!0)},async resolveApproval(i,u,h){let k=q.getMessages().find(W=>W.variant==="approval"&&W.approval?.id===i);if(!k?.approval)throw new Error(`Approval not found: ${i}`);if(k.approval.toolType==="webmcp"){q.resolveWebMcpApproval(k.id,u);return}return q.resolveApproval(k.approval,u,h)},setFollowUpSuggestions(i){nx(i)},clearFollowUpSuggestions(){im()},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...m}},updatePersistentMetadata(i){A(i)},on(i,u){return c.on(i,u)},off(i,u){c.off(i,u)},isOpen(){return Z()&&J},isVoiceActive(){return je.active},toggleReadAloud(i){q.toggleReadAloud(i)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(i){return q.getReadAloudState(i)},onReadAloudChange(i){return q.onReadAloudChange(i)},getState(){return{open:Z()&&J,launcherEnabled:P,voiceActive:je.active,streaming:q.isStreaming()}},showCSATFeedback(i){!J&&Z()&&lt(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Gl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!J&&Z()&&lt(!0,"system");let u=xe.querySelector(".persona-feedback-container");u&&u.remove();let h=Kl({onSubmit:async(x,k)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,k),i?.onSubmit?.(x,k)},onDismiss:i?.onDismiss,...i});xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,u){return q.submitCSATFeedback(i,u)},async submitNPSFeedback(i,u){return q.submitNPSFeedback(i,u)},destroy(){Ic(),ur!=null&&(clearInterval(ur),ur=null),De.forEach(i=>i()),Le.remove(),tt?.remove(),kt?.destroy(),Yt?.remove(),or&&de.removeEventListener("click",or)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,u={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:h=>h?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,De.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",u),De.push(()=>{window.removeEventListener("persona:focusInput",u)}),me){let U=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.showEventStream()},j=Y=>{let pe=Y.detail;(!pe?.instanceId||pe.instanceId===i)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",j),De.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",j)})}let h=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.showArtifacts()},x=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.hideArtifacts()},k=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||j?.artifact&&Rt.upsertArtifact(j.artifact)},W=U=>{let j=U.detail;j?.instanceId&&j.instanceId!==i||typeof j?.id=="string"&&Rt.selectArtifact(j.id)},z=U=>{let j=U.detail;(!j?.instanceId||j.instanceId===i)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),De.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let wn=xS(o.persistState);if(wn&&Z()){let i=vS(wn.storage),u=`${wn.keyPrefix}widget-open`,h=`${wn.keyPrefix}widget-voice`,x=`${wn.keyPrefix}widget-voice-mode`;if(i){let k=wn.persist?.openState&&i.getItem(u)==="true",W=wn.persist?.voiceState&&i.getItem(h)==="true",z=wn.persist?.voiceState&&i.getItem(x)==="true";if(k&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open(),setTimeout(()=>{if(W||z)Rt.startVoiceRecognition();else if(wn.persist?.focusInput){let U=e.querySelector("textarea");U&&U.focus()}},100)},0)),wn.persist?.openState&&(c.on("widget:opened",()=>{i.setItem(u,"true")}),c.on("widget:closed",()=>{i.setItem(u,"false")})),wn.persist?.voiceState&&(c.on("voice:state",U=>{i.setItem(h,U.active?"true":"false")}),c.on("user:message",U=>{i.setItem(x,U.viaVoice?"true":"false")})),wn.clearOnChatClear){let U=()=>{i.removeItem(u),i.removeItem(h),i.removeItem(x)},j=()=>U();window.addEventListener("persona:clear-chat",j),De.push(()=>{window.removeEventListener("persona:clear-chat",j)})}}}if(w&&Z()&&(kt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open()},0)),$r(),!ox){let i=ea(()=>{q&&(uc++,ar.clear(),Ua(xe,q.getMessages(),ie))});De.push(i)}return Rt};var cb=(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},AS=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},SS=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},MS=(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 a=o.offsetHeight>0;o.remove(),!(!r||a)&&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.")},db=(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"},ff=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=""},pb=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ff(e)},df=e=>{e.style.transition=""},pf=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=""},uf=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ql=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},TS=(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))},ES=(e,t,n,o,r,a)=>{let s=a?t:e;r==="left"?s.firstElementChild!==o&&s.replaceChildren(o,n):s.lastElementChild!==o&&s.replaceChildren(n,o)},kS=e=>{let t=Uo(e),n=t.components?.panel,o=(r,a)=>r==null||r===""?a:en(t,r)??r;return{inset:o(n?.inset,rl),canvasBackground:o(n?.canvasBackground,al)}},ub=(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},LS=(e,t,n,o,r,a,s,l)=>{let p=ln(a),d=p.reveal==="push",c=l!=null,f=l?.inset??"",g=l?.canvasBackground??"";TS(e,t,n,o,d),ES(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=s?"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=a?.launcher?.mobileFullscreen??!0,w=a?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=w:!1;if(b&&T&&s){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),pf(t),df(o),pb(o),uf(n),Ql(r,o),ub(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(a?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),pb(o),AS(o,p.maxHeight),ub(o,c&&s,f,g),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",pf(t),df(o),uf(n),Ql(r,o);let A=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",C=s?"translateX(0)":S;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=A,o.style.transform=C,o.style.pointerEvents=s?"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",df(o),ff(o),Ql(r,o);let A=cb(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),C=p.animate?"margin-left 180ms ease":"none",M=p.side==="right"?s?-A:0:s?0:-A;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=`${S+A}px`,t.style.transition=C,t.style.marginLeft=`${M}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}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=s?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",pf(t),ff(o),uf(n),Ql(r,o);let A=p.reveal==="emerge";A?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=s?p.width:"0px",C=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",M=!s;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",SS(o,p.maxHeight),o.style.overflow=A||M?"hidden":"visible",o.style.transition=C,A){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let P=c?`calc(${cb(p.width,e.clientWidth)}px - (2 * ${f}))`:p.width;r.style.width=P,r.style.minWidth=P,r.style.maxWidth=P,r.style.boxSizing="border-box"}}},PS=(e,t)=>{let n=e.ownerDocument.createElement("div");return db(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){db(n,o)},destroy(){n.remove()}}},RS=(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 a=e.nextSibling,s=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),f=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(s,e),p.appendChild(e);let g=null,m=()=>{g?.disconnect(),g=null},b=null,w=()=>{b=t?.launcher?.detachedPanel===!0?kS(t):null};w();let T=()=>{LS(s,l,p,d,c,t,f,b)},L=null,A=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=pa(()=>{w(),T()}))},S=()=>{m(),ln(t).reveal==="push"&&(typeof ResizeObserver>"u"||(g=new ResizeObserver(()=>{T()}),g.observe(s)))},C=!1,M=()=>{T(),S(),f&&!C&&s.dataset.personaDockMobileFullscreen!=="true"&&(C=!0,MS(s,ln(t)))},P=s.ownerDocument.defaultView,R=()=>{M()};return P?.addEventListener("resize",R),ln(t).reveal==="push"?(l.appendChild(p),l.appendChild(d),s.appendChild(l)):(s.appendChild(p),s.appendChild(d)),M(),A(),{mode:"docked",host:c,shell:s,syncWidgetState(F){let O=F.launcherEnabled?F.open:!0;f!==O&&(f=O,M())},updateConfig(F){t=F,(t?.launcher?.enabled??!0)===!1&&(f=!0),w(),M(),A()},destroy(){P?.removeEventListener("resize",R),L?.(),L=null,m(),o.isConnected&&(a&&a.parentNode===o?o.insertBefore(e,a):o.appendChild(e)),s.remove()}}},Ns=(e,t)=>St(t)?RS(e,t):PS(e,t);var IS=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},fb=(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)},mb=e=>{let t=IS(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,a=Ns(t,r),s,l=[],p=(T,L)=>{let S=!(L?.launcher?.enabled??!0)||St(L),C=o.createElement("div");if(C.setAttribute("data-persona-root","true"),S&&(C.style.height="100%",C.style.display="flex",C.style.flexDirection="column",C.style.flex="1",C.style.minHeight="0",C.style.minWidth="0"),n){let M=T.attachShadow({mode:"open"});M.appendChild(C),fb(M,o)}else T.appendChild(C),fb(T,o);return t.id&&C.setAttribute("data-persona-instance",t.id),C},d=()=>{a.syncWidgetState(s.getState())},c=()=>{l.forEach(T=>T()),l=[s.on("widget:opened",d),s.on("widget:closed",d)],d()},f=()=>{let T=p(a.host,r);s=Jl(T,r,{debugTools:e.debugTools}),c()},g=()=>{l.forEach(T=>T()),l=[],s.destroy()};f(),e.onChatReady?.();let m=T=>{g(),a.destroy(),a=Ns(t,T),r=T,f()},b={update(T){let L=ql(r??{},T),A=St(r),S=St(L),C=Ko(r),M=Ko(L);if(A!==S||C!==M){m(L);return}r=L,a.updateConfig(r),s.update(T),d()},destroy(){g(),a.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},w=new Proxy(b,{get(T,L,A){if(L==="host")return a.host;if(L in T)return Reflect.get(T,L,A);let S=s[L];return typeof S=="function"?S.bind(s):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=w),w};function WS(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 HS(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(a=>a.toLowerCase().startsWith(o))?1:WS(o,n)?2:3}function gb(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function Yl(e,t){let n=t.trim();if(!n)return[...e].sort(gb);let o=[];for(let r of e){let a=HS(r.label,n);a!==3&&o.push({item:r,tier:a})}return o.sort((r,a)=>r.tier!==a.tier?r.tier-a.tier:gb(r.item,a.item)),o.map(r=>r.item)}function BS(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 hb(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>Yl(e.items,t),resolve:e.resolve}}function yb(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=>Yl(t,BS(r).name),resolve:(r,a)=>{let s=n.get(r.id);return s?s.kind==="server"?{context:(typeof s.data=="function"?s.data(a.args):s.data)??{}}:{insertText:typeof s.prompt=="function"?s.prompt(a.args):s.prompt??""}:{}}}}var wb=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),DS=new Set(["button","a","input","select","textarea","details","summary"]),FS=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mf=/\b(product|card|item|listing|result)\b/i,hf=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,OS=3e3,NS=100;function Ab(e){let t=typeof e.className=="string"?e.className:"";if(mf.test(t)||e.id&&mf.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&mf.test(o.value))return!0}return!1}function Sb(e){return hf.test((e.textContent??"").trim())}function Mb(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 _S(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function bb(e){let t=e.match(hf);return t?t[0]:null}function xb(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 US(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 qS="commerce-card",VS="result-card";function vb(e){return!Ab(e)||!Sb(e)||!Mb(e)&&!_S(e)?0:5200}function Cb(e){return!Ab(e)||Sb(e)||!Mb(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var yf=[{id:qS,scoreElement(e){return vb(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||hf.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(vb(e)===0)return null;let{title:n,href:o}=xb(e),r=bb((e.textContent??"").trim())??bb(t.text)??"",a=US(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,a.length?`actions: ${a.join(", ")}`:""].filter(Boolean).join(`
144
+ `)}},{id:VS,scoreElement(e){return Cb(e)},formatSummary(e,t){if(Cb(e)===0)return null;let{title:n,href:o}=xb(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
145
+ `)}}];function zS(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function $S(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,a=t.visibleOnly??e.visibleOnly??!0,s=t.root??e.root,l=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??yf;return l==="simple"&&e.rules&&e.rules.length>0?(zS(),d=[]):l==="simple"&&(d=[]),{mode:l,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:a,root:s,rules:d}}function gf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var jS=["data-testid","data-product","data-action","data-id","data-name","data-type"];function GS(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"||DS.has(t)||n&&FS.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Tb(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 KS(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 a=e.getAttribute("type");a&&(t.type=a);let s=e.getAttribute("value");s&&(t.value=s);let l=e.getAttribute("name");l&&(t.name=l);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 bf(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${gf(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of jS){let a=e.getAttribute(r);if(a){let s=`${t}[${r}="${gf(a)}"]`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}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(s=>gf(s)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let a=e.parentElement;if(a){let l=Array.from(a.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(l>=0){let p=`${r}:nth-of-type(${l+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let a=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(a>=0)return`${t}:nth-of-type(${a+1})`}return t}function XS(e){return e==="static"?NS:OS}function Eb(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:bf(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:GS(e),attributes:KS(e)}}function JS(e,t,n,o){let r=XS(t.interactivity),a=null;for(let s of n){let l=s.scoreElement(e,t,o);l>0&&(r+=l,s.formatSummary&&!a&&(a=s))}return{score:r,formattingRule:a}}function QS(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 YS(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],a=0,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),l=s.currentNode;for(;l&&r.length<e.maxCandidates;){if(l.nodeType===Node.ELEMENT_NODE){let d=l,c=d.tagName.toLowerCase();if(wb.has(c)){l=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){l=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Tb(d)){l=s.nextNode();continue}let f=Eb(d,e.maxTextLength),g=f.text.length>0,m=Object.keys(f.attributes).length>0&&!Object.keys(f.attributes).every(T=>T==="role");if(!g&&!m){l=s.nextNode();continue}if(o.has(f.selector)){l=s.nextNode();continue}o.add(f.selector);let{score:b,formattingRule:w}=JS(d,f,e.rules,n);r.push({el:d,domIndex:a,enriched:f,score:b,formattingRule:w}),a+=1}l=s.nextNode()}r.sort((d,c)=>{let f=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return f!==g?f-g: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;QS(p,d)||p.push(d)}return p.sort((d,c)=>{let f=d.enriched.interactivity==="static"?1:0,g=c.enriched.interactivity==="static"?1:0;return f!==g?f-g:f===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let g=d.formattingRule.formatSummary(d.el,d.enriched,n);g&&(c=g)}let f={...d.enriched};return c&&(f.formattedSummary=c),f})}function ZS(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),a=r.currentNode;for(;a&&n.length<e.maxElements;){if(a.nodeType===Node.ELEMENT_NODE){let p=a,d=p.tagName.toLowerCase();if(wb.has(d)){a=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){a=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Tb(p)){a=r.nextNode();continue}let c=Eb(p,e.maxTextLength),f=c.text.length>0,g=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(m=>m==="role");if(!f&&!g){a=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}a=r.nextNode()}let s=[],l=[];for(let p of n)p.interactivity!=="static"?s.push(p):l.push(p);return[...s,...l].slice(0,e.maxElements)}function kb(e={}){let t=$S(e),n=t.root??document.body;return n?t.mode==="simple"?ZS(t,n):YS(t,n):[]}var Zl=100;function Lb(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let a=e.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);a.length>0&&o.push(`Structured summaries:
146
146
  ${a.map(s=>`- ${s.split(`
147
147
  `).join(`
148
148
  `)}`).join(`
149
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,Al)}" (clickable)`);o.push(`Interactive elements:
149
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||r[a.interactivity].push(a);if(r.clickable.length>0){let a=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,Zl)}" (clickable)`);o.push(`Interactive elements:
150
150
  ${a.join(`
151
- `)}`)}if(r.navigable.length>0){let a=r.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,Al)}" (navigable)`);o.push(`Navigation links:
151
+ `)}`)}if(r.navigable.length>0){let a=r.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,Zl)}" (navigable)`);o.push(`Navigation links:
152
152
  ${a.join(`
153
- `)}`)}if(r.input.length>0){let a=r.input.map(s=>`- ${s.selector}${s.attributes.type?`[type="${s.attributes.type}"]`:""}: "${s.text.substring(0,Al)}" (input)`);o.push(`Form inputs:
153
+ `)}`)}if(r.input.length>0){let a=r.input.map(s=>`- ${s.selector}${s.attributes.type?`[type="${s.attributes.type}"]`:""}: "${s.text.substring(0,Zl)}" (input)`);o.push(`Form inputs:
154
154
  ${a.join(`
155
- `)}`)}if(r.static.length>0){let a=r.static.map(s=>`- ${s.selector}: "${s.text.substring(0,Al)}"`);o.push(`Content:
155
+ `)}`)}if(r.static.length>0){let a=r.static.map(s=>`- ${s.selector}: "${s.text.substring(0,Zl)}"`);o.push(`Content:
156
156
  ${a.join(`
157
157
  `)}`)}return o.join(`
158
158
 
159
- `)}function ey(){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 ty(){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 ny(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:Nn(e.colors.primary,.95),100:Nn(e.colors.primary,.9),200:Nn(e.colors.primary,.8),300:Nn(e.colors.primary,.7),400:Nn(e.colors.primary,.6),500:e.colors.primary,600:Nn(e.colors.primary,.8),700:Nn(e.colors.primary,.7),800:Nn(e.colors.primary,.6),900:Nn(e.colors.primary,.5),950:Nn(e.colors.primary,.45)}}),{...t,palette:n}}}}function oy(){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 ry(){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 Nn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),s=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function ay(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Gw={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"}}},sy={components:{panel:{borderRadius:"0",shadow:"none"}}},Cu={id:"shop",label:"Shopping Assistant",config:{theme:Gw,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:["What can you help me with?","Tell me about your features","How does this work?"]}},wu={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:sy}},Au={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:sy}},Su={shop:Cu,minimal:wu,fullscreen:Au};function iy(e){return Su[e]}var Kw=`
159
+ `)}function Pb(){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 Rb(){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 Ib(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:Kn(e.colors.primary,.95),100:Kn(e.colors.primary,.9),200:Kn(e.colors.primary,.8),300:Kn(e.colors.primary,.7),400:Kn(e.colors.primary,.6),500:e.colors.primary,600:Kn(e.colors.primary,.8),700:Kn(e.colors.primary,.7),800:Kn(e.colors.primary,.6),900:Kn(e.colors.primary,.5),950:Kn(e.colors.primary,.45)}}),{...t,palette:n}}}}function Wb(){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 Hb(){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 Kn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),a=Math.round(n+(255-n)*(1-t)),s=Math.round(o+(255-o)*(1-t)),l=Math.round(r+(255-r)*(1-t));return`#${a.toString(16).padStart(2,"0")}${s.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}`}function Bb(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var e0={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"}}},Db={components:{panel:{borderRadius:"0",shadow:"none"}}},xf={id:"shop",label:"Shopping Assistant",config:{theme:e0,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:mn},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"]}},vf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Db}},Cf={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Db}},wf={shop:xf,minimal:vf,fullscreen:Cf};function Fb(e){return wf[e]}var t0=`
160
160
  @keyframes persona-stream-wipe {
161
161
  from { -webkit-mask-position: 100% 0; mask-position: 100% 0; }
162
162
  to { -webkit-mask-position: 0% 0; mask-position: 0% 0; }
@@ -192,7 +192,7 @@ ${a.join(`
192
192
  mask-image: none !important;
193
193
  }
194
194
  }
195
- `.trim(),Xw={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:Kw};sr(Xw);var Jw=`
195
+ `.trim(),n0={name:"wipe",containerClass:"persona-stream-wipe",wrap:"word",styles:t0};Er(n0);var o0=`
196
196
  [data-persona-root] .persona-stream-glyph-cycle .persona-stream-char {
197
197
  animation: persona-stream-glyph-cycle-fade
198
198
  calc(var(--persona-stream-step, 120ms) * 1.5) ease-out both;
@@ -210,7 +210,7 @@ ${a.join(`
210
210
  opacity: 1 !important;
211
211
  }
212
212
  }
213
- `.trim(),fs="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",Qw=10,Yw=120,Mu=120,Zw=.4,eA=50,tA=e=>{if(!e)return Mu;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Mu},gy=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=tA(t);return Yw*n/Mu},Tu=e=>{let t=fs[Math.floor(Math.random()*fs.length)];return e&&t===e&&(t=fs[(fs.indexOf(t)+1)%fs.length]),t},nA=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<Zw&&(r.textContent=Tu())}},ly=new WeakMap,dy=25,cy=.5,oA=6,py=.25,uy=new WeakMap,fy=new WeakMap,rA=(e,t)=>{if(!e)return dy*cy;let n=uy.get(e);uy.set(e,t);let o=fy.get(e)??dy;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-py)+r*py,fy.set(e,o))}return Math.max(oA,o*cy)},ta=new Map,aA=e=>e.closest("[data-message-id]")?.dataset.messageId??null,sA=e=>{e&&ta.set(e,(ta.get(e)??0)+1)},iA=e=>{if(!e)return;let t=ta.get(e)??0;t<=1?ta.delete(e):ta.set(e,t-1)},hy=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Tu();let n=aA(e);n&&(e.dataset.glyphCycleMessageId=n),sA(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=rA(o,r),s=gy(e),l=Qw*s,p=r+l;if(o){let c=ly.get(o);c!==void 0&&(p=Math.max(p,c)),ly.set(o,p+a)}lA(e,t,p)},lA=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=gy(e),r=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,iA(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Tu(r);e.textContent=s,r=s,nA(e),setTimeout(a,o)};setTimeout(a,o)},my=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))hy(n)},dA=e=>e.nodeType===1,cA={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:Jw,bufferContent(e){if(e.length<eA)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(ta.get(e.id)??0)>0},onAttach(e){my(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))dA(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?hy(r):my(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};sr(cA);var en=typeof document<"u"?document.currentScript?.src??null:null;om(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});Uf(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});ka().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});Um(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});Ym(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});Zm(()=>{let e=en?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===en?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${en??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return mb(pA);})();
213
+ `.trim(),_s="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#$%&@",r0=10,a0=120,Af=120,s0=.4,i0=50,l0=e=>{if(!e)return Af;let n=(e.style.getPropertyValue("--persona-stream-step")?.trim()).match(/([\d.]+)\s*ms/);return n?parseFloat(n[1]):Af},$b=e=>{let t=e.closest(".persona-stream-glyph-cycle"),n=l0(t);return a0*n/Af},Sf=e=>{let t=_s[Math.floor(Math.random()*_s.length)];return e&&t===e&&(t=_s[(_s.indexOf(t)+1)%_s.length]),t},c0=e=>{let t=e.closest(".persona-stream-glyph-cycle");if(!t)return;let n=t.querySelectorAll(".persona-stream-char[data-glyph-cycle-final]"),o=!1;for(let r of Array.from(n)){if(r===e){o=!0;continue}o&&Math.random()<s0&&(r.textContent=Sf())}},Ob=new WeakMap,Nb=25,_b=.5,d0=6,Ub=.25,qb=new WeakMap,Vb=new WeakMap,p0=(e,t)=>{if(!e)return Nb*_b;let n=qb.get(e);qb.set(e,t);let o=Vb.get(e)??Nb;if(n!==void 0){let r=t-n;r>1&&(o=o*(1-Ub)+r*Ub,Vb.set(e,o))}return Math.max(d0,o*_b)},Ea=new Map,u0=e=>e.closest("[data-message-id]")?.dataset.messageId??null,f0=e=>{e&&Ea.set(e,(Ea.get(e)??0)+1)},m0=e=>{if(!e)return;let t=Ea.get(e)??0;t<=1?Ea.delete(e):Ea.set(e,t-1)},jb=e=>{if(e.dataset.glyphCycleScheduled==="true")return;let t=e.textContent??"";if(!t||/\s/.test(t))return;e.dataset.glyphCycleScheduled="true",e.dataset.glyphCycleFinal=t,e.setAttribute("data-preserve-runtime","stream-glyph-cycle"),e.textContent=Sf();let n=u0(e);n&&(e.dataset.glyphCycleMessageId=n),f0(n);let o=e.closest(".persona-stream-glyph-cycle"),r=Date.now(),a=p0(o,r),s=$b(e),l=r0*s,p=r+l;if(o){let d=Ob.get(o);d!==void 0&&(p=Math.max(p,d)),Ob.set(o,p+a)}g0(e,t,p)},g0=(e,t,n)=>{if(e.dataset.glyphCycleStarted==="true")return;e.dataset.glyphCycleStarted="true";let o=$b(e),r=e.textContent??void 0,a=()=>{if(!e.isConnected)return;if(Date.now()>=n){e.textContent=t,e.removeAttribute("data-preserve-runtime"),delete e.dataset.glyphCycleStarted,delete e.dataset.glyphCycleFinal,m0(e.dataset.glyphCycleMessageId??null),delete e.dataset.glyphCycleMessageId;return}let s=Sf(r);e.textContent=s,r=s,c0(e),setTimeout(a,o)};setTimeout(a,o)},zb=e=>{let t=e.querySelectorAll?.(".persona-stream-glyph-cycle .persona-stream-char:not([data-glyph-cycle-scheduled])");if(t)for(let n of Array.from(t))jb(n)},h0=e=>e.nodeType===1,y0={name:"glyph-cycle",containerClass:"persona-stream-glyph-cycle",wrap:"char",skipTags:["a","script","style"],styles:o0,bufferContent(e){if(e.length<i0)return"";let t=0,n=-1,o=0;for(;o<e.length;){if(e[o]==="*"&&e[o+1]==="*"){t+=1,o+=2;continue}/\s/.test(e[o])&&t%2===0&&(n=o),o+=1}return n<0?"":e.slice(0,n)},isAnimating(e){return(Ea.get(e.id)??0)>0},onAttach(e){zb(e);let t=new MutationObserver(n=>{for(let o of n)for(let r of Array.from(o.addedNodes))h0(r)&&(r.classList.contains("persona-stream-char")&&r.closest(".persona-stream-glyph-cycle")?jb(r):zb(r))});return t.observe(e,{childList:!0,subtree:!0}),()=>t.disconnect()}};Er(y0);var nn=typeof document<"u"?document.currentScript?.src??null:null;Ag(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"webmcp-polyfill.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the webmcp-polyfill.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should install @mcp-b/webmcp-polyfill on the page themselves before enabling config.webmcp.`)):import(e)});ig(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"markdown-parsers.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the markdown-parsers.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host markdown-parsers.js alongside it.`)):import(e)});ts().catch(e=>{typeof console<"u"&&console.warn("[Persona] Failed to pre-load markdown parsers",e)});ih(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"runtype-tts.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the runtype-tts.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host runtype-tts.js alongside it, or set textToSpeech.createEngine to supply a speech engine directly.`)):import(e)});bh(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"context-mentions.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the context-mentions.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions.js alongside it.`)):import(e)});xh(()=>{let e=nn?.replace(/index\.global\.js($|\?)/,"context-mentions-inline.js$1");return!e||e===nn?Promise.reject(new Error(`Could not derive the context-mentions-inline.js URL from the widget script URL (${nn??"unavailable"}). Self-hosted deployments that rename index.global.js should host context-mentions-inline.js alongside it.`)):import(e)});return nv(b0);})();
214
214
  /*! Bundled license information:
215
215
 
216
216
  lucide/dist/esm/icons/activity.mjs:
@@ -228,6 +228,7 @@ lucide/dist/esm/icons/building.mjs:
228
228
  lucide/dist/esm/icons/calendar-days.mjs:
229
229
  lucide/dist/esm/icons/calendar.mjs:
230
230
  lucide/dist/esm/icons/camera.mjs:
231
+ lucide/dist/esm/icons/chart-column.mjs:
231
232
  lucide/dist/esm/icons/check.mjs:
232
233
  lucide/dist/esm/icons/chevron-down.mjs:
233
234
  lucide/dist/esm/icons/chevron-left.mjs:
@@ -269,6 +270,7 @@ lucide/dist/esm/icons/image-plus.mjs:
269
270
  lucide/dist/esm/icons/image.mjs:
270
271
  lucide/dist/esm/icons/info.mjs:
271
272
  lucide/dist/esm/icons/key.mjs:
273
+ lucide/dist/esm/icons/lightbulb.mjs:
272
274
  lucide/dist/esm/icons/link.mjs:
273
275
  lucide/dist/esm/icons/loader-circle.mjs:
274
276
  lucide/dist/esm/icons/loader.mjs:
@@ -287,6 +289,7 @@ lucide/dist/esm/icons/moon.mjs:
287
289
  lucide/dist/esm/icons/package.mjs:
288
290
  lucide/dist/esm/icons/paperclip.mjs:
289
291
  lucide/dist/esm/icons/pause.mjs:
292
+ lucide/dist/esm/icons/pen-line.mjs:
290
293
  lucide/dist/esm/icons/pencil.mjs:
291
294
  lucide/dist/esm/icons/percent.mjs:
292
295
  lucide/dist/esm/icons/phone.mjs: